skip to Main Content

Don’t the different logging levels in Python (v3.11.4) logging work for a file and for telegrams?

So the logs of the WARNING level and above go both to the Telegram and to the file, and the logs of the INFO level only go to the file.

There is a script:

import logging
import tg_logger
import os
from dotenv import load_dotenv
from pathlib import Path
from logging.handlers import RotatingFileHandler

dotenv_path = os.path.join(os.path.dirname(__file__), '.env')
if os.path.exists(dotenv_path):
    load_dotenv(dotenv_path)
token = os.getenv("TELEGRAM_BOT_TOKEN")
users = [os.getenv("TELEGRAM_CHAT_ID")]
script_path = Path(__file__).resolve()
script_name = os.path.splitext(os.path.basename(script_path))[0]
log_dir = script_path.parent
log_file = Path(str(log_dir) + "/" + script_name + ".log")
logger = logging.getLogger(script_name)
tg_logger.setup(logger, token=token, users=users, tg_format="<b><u>%(name)s</u> : %(levelname)s</b>nn<code>%(message)s</code>")
file_handler = RotatingFileHandler(log_file, maxBytes=1024*1024, backupCount=10)
file_handler.setLevel(logging.INFO)
file_handler.setFormatter(logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s'))
logger.addHandler(file_handler)
logger.setLevel(logging.WARNING)

logger.info(f"Hello from tg_logger by {script_name}")
logger.warning(f"Test WARNING {script_name}")
#logger.error(f

"Test ERROR {script_name}")

2

Answers


  1. Chosen as BEST ANSWER

    The answer was suggested to me by a good person on qna.habr.com And as always, everything turned out to be very simple and elegant.

    import logging
    import tg_logger
    import os
    from dotenv import load_dotenv
    from pathlib import Path
    from logging.handlers import RotatingFileHandler
    dotenv_path = os.path.join(os.path.dirname(__file__), '.env')
    if os.path.exists(dotenv_path):
        load_dotenv(dotenv_path)
    token = os.getenv("TELEGRAM_BOT_TOKEN")
    users = [os.getenv("TELEGRAM_CHAT_ID")]
    
    script_path = Path(__file__).resolve()
    script_name = os.path.splitext(os.path.basename(script_path))[0]
    log_dir = script_path.parent
    log_file = Path(str(log_dir) + "/" + script_name + ".log")
    logger = logging.getLogger(script_name)
    logger.setLevel(logging.INFO)
    file_handler = RotatingFileHandler(log_file, maxBytes=1024*1024, backupCount=10)
    file_handler.setLevel(logging.INFO)
    file_handler.setFormatter(logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s'))
    logger.addHandler(file_handler)
    t_handler = tg_logger.setup(logger, token=token, users=users, tg_format="<b><u>%(name)s</u> : %(levelname)s</b>nn<code>%(message)s</code>")
    t_handler.setLevel(logging.WARNING)
    logger.addHandler(t_handler)
    logger.info(f"Hello from tg_logger by {script_name}")
    logger.warning(f"Test WARNING {script_name}")
    #logger.error(f"Test ERROR {script_name}")
    

  2. You need to set INFO level on root logger, WARNING on file_handler:

    import logging, sys
    #import tg_logger
    
    script_name = "FOO"
    
    logger = logging.getLogger(script_name)
    logger.setLevel(logging.INFO)
    
    file_handler = logging.FileHandler("/tmp/foo_file.log")
    file_handler.setFormatter(logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s'))
    file_handler.setLevel(logging.WARNING)
    
    tg_handler = logging.FileHandler("/tmp/foo_tg.log")
    tg_handler.setFormatter(logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s'))
    #tg_logger.setup(tg_handler, token=token, users=users, tg_format="<b><u>%(name)s</u> : %(levelname)s</b>nn<code>%(message)s</code>")
    
    logger.addHandler(file_handler)
    logger.addHandler(tg_handler)
    
    logger.info("info message")
    logger.warning("warn message")
    logger.debug("debug message")
    logger.error("error message")
    
    print(open("/tmp/foo_tg.log").read())
    print(open("/tmp/foo_file.log").read())
    

    Out:

    2024-08-20 12:28:55,491 - FOO - INFO - info message
    2024-08-20 12:28:55,491 - FOO - WARNING - warn message
    2024-08-20 12:28:55,492 - FOO - ERROR - error message
    
    2024-08-20 12:28:55,491 - FOO - WARNING - warn message
    2024-08-20 12:28:55,492 - FOO - ERROR - error message
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search