【问题标题】:How to turn on/off debugging in Python for production and development mode?How to turn on/off debugging in Python for production and development mode?
【发布时间】:2022-12-27 23:08:11
【问题描述】:

I created a my_logger class as below:

import logging
import logging.handlers
import os

abspath = os.path.abspath(os.path.dirname(__file__))

format = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(lineno)d - %(message)s')

def my_logger(module_name):

    logger = logging.getLogger(module_name)
    logger.setLevel(logging.DEBUG)

    # stream handler
    c_handler = logging.StreamHandler()
    c_handler.setLevel(logging.DEBUG)
    c_handler.setFormatter(format)

    # debug handler
    f1_handler = logging.handlers.RotatingFileHandler(os.path.join(abspath, "logs/debug.log"))
    f1_handler.setLevel(logging.DEBUG)
    f1_handler.setFormatter(format)

    # info handler
    f2_handler = logging.handlers.RotatingFileHandler(os.path.join(abspath, "logs/info.log"))
    f2_handler.setLevel(logging.INFO)
    f2_handler.setFormatter(format)

    # warning handler
    f3_handler = logging.handlers.RotatingFileHandler(os.path.join(abspath, "logs/warning.log"))
    f3_handler.setLevel(logging.WARNING)
    f3_handler.setFormatter(format)

    # error handler
    f4_handler = logging.handlers.RotatingFileHandler(os.path.join(abspath, "logs/error.log"))
    f4_handler.setLevel(logging.ERROR)
    f4_handler.setFormatter(format)

    # Add handlers to the logger
    logger.addHandler(c_handler)
    logger.addHandler(f1_handler)
    logger.addHandler(f2_handler)
    logger.addHandler(f3_handler)
    logger.addHandler(f4_handler)

    return logger

Then in my code, I used it in any python file this way:

logger = my_logger(__name__)
logger.warning('This is a warning')
logger.error('This is an error')
logger.info('This is an info')
logger.debug('This is an debug')

How to turn off and on in production and development mode in the project? I have never done this before.

【问题讨论】:

  • Did you read the documentation of the logging module? I believe they have some examples or explanations about this use case.
  • @mkrieger1 for example, if I want only warning and error messages, should I set it to: logging.basicConfig(level=logging.WARNING)? Also, do I need to add this line to every file that I used logging? Is this the way to turn on and off logging?

标签: python debugging


【解决方案1】:

If anyone still looking for answer the Official python docs has this section which might be helpful:

https://docs.python.org/3/howto/logging.html#what-happens-if-no-configuration-is-provided and all other section preceding to this.

【讨论】:

    猜你喜欢
    • 2022-12-27
    • 2022-12-02
    • 2022-12-28
    • 2022-12-02
    • 2022-12-27
    • 2022-12-02
    • 1970-01-01
    • 2022-11-09
    • 2022-12-02
    相关资源
    最近更新 更多