gpt4 book ai didi

python - 如何实现全局 Python 记录器?

转载 作者:太空狗 更新时间:2023-10-30 02:18:01 25 4
gpt4 key购买 nike

如何为我的所有 python 文件实现一个全局记录器?一些相关的 SE 问题是 onetwo ,但两者都不完全是我想要的,简单地说。我也希望在控制台中看到日志文件输出。

最佳答案

这是多年来一直为我工作的解决方案:

主.py

import log
import test

logger = log.setup_custom_logger('root')

def main():
logger.info("informational message")
logger.debug("debugging message")
logger.critical("critical message")
test.test_message()
return 0

if __name__ == '__main__':
main()

日志.py

import logging
import logging.handlers

def setup_custom_logger(name):
# logger settings
log_file = "log/testing.log"
log_file_max_size = 1024 * 1024 * 20 # megabytes
log_num_backups = 3
log_format = "%(asctime)s [%(levelname)s] %(filename)s/%(funcName)s:%(lineno)s >> %(message)s"
log_filemode = "w" # w: overwrite; a: append

# setup logger
logging.basicConfig(filename=log_file, format=log_format,
filemode=log_filemode, level=logging.DEBUG)
rotate_file = logging.handlers.RotatingFileHandler(
log_file, maxBytes=log_file_max_size, backupCount=log_num_backups
)
logger = logging.getLogger(name)
logger.addHandler(rotate_file)

# print log messages to console
consoleHandler = logging.StreamHandler()
logFormatter = logging.Formatter(log_format)
consoleHandler.setFormatter(logFormatter)
logger.addHandler(consoleHandler)

return logger

# source: https://docs.python.org/2/howto/logging.html
# logger.debug("") // Detailed information, typically of interest only when diagnosing problems.
# logger.info("") // Confirmation that things are working as expected.
# logger.warning("") // An indication that something unexpected happened, or indicative of some problem in the near future
# logger.error("") // Due to a more serious problem, the software has not been able to perform some function.
# logger.critical("") // A serious error, indicating that the program itself may be unable to continue running.

测试.py

import logging

logger = logging.getLogger('root')

def test_message():
logger.warning("warning message")
logger.error("error message")
return 0

确保您有一个名为 log 的目录对于文件 testing.log从你打电话的地方python3 main.py从。对于使用日志记录的每个文件,您必须像在 test.py 中一样调用这两行:import logginglogger = logging.getLogger('root') .

示例控制台和日志文件输出:

2016-06-21 23:24:43,945 [DEBUG] main.py/main:11 >> debugging message
2016-06-21 23:24:43,945 [INFO] main.py/main:10 >> informational message
2016-06-21 23:24:43,945 [CRITICAL] main.py/main:12 >> critical message
2016-06-21 23:24:43,946 [WARNING] test.py/test_message:9 >> warning message
2016-06-21 23:24:43,946 [ERROR] test.py/test_message:10 >> error message

关于python - 如何实现全局 Python 记录器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37958568/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com