Python 日志同时输出到屏幕和文件的配置方法
本文详细介绍如何在Python中利用logging模块将日志同时输出到控制台屏幕和指定文件。通过配置Handler分别设置屏幕和文件的日志级别,并结合Formatter格式化输出内容,实现调试信息与持久化记录的同步保存。
Python日志输出到屏幕的配置
在Python开发中,日志记录是排查问题和监控系统状态的重要手段。首先介绍如何将日志信息输出到屏幕控制台。
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import logging
logging.basicConfig(level=logging.NOTSET, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logging.debug('This is a debug message.')
logging.info('This is an info message.')
logging.warning('This is a warning message.')
logging.error('This is an error message.')
logging.critical('This is a critical message.')
Python的logging模块默认日志级别为logging.WARNING,这意味着只有WARNING及以上级别的日志才会被显示。如果希望看到更低级别的日志内容,例如调试信息,需要引入logging.NOTSET级别进行配置,从而允许所有级别的日志通过。
DEBUG级别用于打印所有日志信息,通常包含详细的调试数据,仅在诊断具体问题时使用。
INFO级别用于确认程序按预期正常运行,该级别会输出INFO、WARNING、ERROR和CRITICAL日志。
WARNING级别表示系统出现了一些潜在问题,但软件仍能按预期继续工作,该级别会输出WARNING、ERROR和CRITICAL日志。
ERROR级别表示发生了更严重的问题,导致软件部分功能无法执行,该级别会输出ERROR和CRITICAL日志。
CRITICAL级别表示发生了严重错误,可能导致程序本身无法继续运行,仅输出CRITICAL级别的日志。
/usr/bin/python2.7 /home/strong/git_workspace/MonoGRNet/test.py
2019-06-26 16:00:45,990 - root - DEBUG - This is a debug message.
2019-06-26 16:00:45,990 - root - INFO - This is an info message.
2019-06-26 16:00:45,990 - root - WARNING - This is a warning message.
2019-06-26 16:00:45,990 - root - ERROR - This is an error message.
2019-06-26 16:00:45,990 - root - CRITICAL - This is a critical message.
Process finished with exit code 0
Python日志输出到文件的配置
接下来介绍如何将日志信息记录到文件中,以便进行持久化存储和后续分析。
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import logging
import os.path
import time
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
time_line = time.strftime('%Y%m%d%H%M', time.localtime(time.time()))
print(os.getcwd())
log_path = os.path.dirname(os.getcwd()) + '/'
logfile = log_path + time_line + '.log'
handler = logging.FileHandler(logfile, mode='w')
handler.setLevel(logging.INFO)
formatter = logging.Formatter("%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s")
handler.setFormatter(formatter)
logger.addHandler(handler)
logger.debug('This is a debug message.')
logger.info('This is an info message.')
logger.warning('This is a warning message.')
logger.error('This is an error message.')
logger.critical('This is a critical message.')
/usr/bin/python2.7 /home/strong/git_workspace/MonoGRNet/test.py
/home/strong/git_workspace/MonoGRNet
Process finished with exit code 0
示例中生成的日志文件名为201906261627.log,具体文件名可根据时间戳动态生成。
2019-06-26 16:27:26,899 - test.py[line:30] - INFO: This is an info message.
2019-06-26 16:27:26,899 - test.py[line:31] - WARNING: This is a warning message.
2019-06-26 16:27:26,899 - test.py[line:32] - ERROR: This is an error message.
2019-06-26 16:27:26,899 - test.py[line:33] - CRITICAL: This is a critical message.
Python日志同时输出到屏幕和文件
最后,介绍如何配置Python日志系统,使其同时输出到屏幕控制台和指定文件,兼顾实时调试与历史记录的保存。
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import logging
import os.path
import time
logger = logging.getLogger(__name__)
logger.setLevel(level=logging.DEBUG)
time_line = time.strftime('%Y%m%d%H%M', time.localtime(time.time()))
print(os.getcwd())
log_path = os.path.dirname(os.getcwd()) + '/'
logfile = log_path + time_line + '.log'
handler = logging.FileHandler(logfile, mode='w')
handler.setLevel(logging.INFO)
formatter = logging.Formatter("%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s")
handler.setFormatter(formatter)
console = logging.StreamHandler()
console.setLevel(logging.WARNING)
logger.addHandler(handler)
logger.addHandler(console)
logger.debug('This is a debug message.')
logger.info('This is an info message.')
logger.warning('This is a warning message.')
logger.error('This is an error message.')
logger.critical('This is a critical message.')
/usr/bin/python2.7 /home/strong/git_workspace/MonoGRNet/test.py
/home/strong/git_workspace/MonoGRNet
This is a warning message.
This is an error message.
This is a critical message.
Process finished with exit code 0
示例中生成的日志文件名为201906261636.log,文件名同样基于当前时间生成。
2019-06-26 16:36:38,385 - test.py[line:34] - INFO: This is an info message.
2019-06-26 16:36:38,385 - test.py[line:35] - WARNING: This is a warning message.
2019-06-26 16:36:38,385 - test.py[line:36] - ERROR: This is an error message.
2019-06-26 16:36:38,385 - test.py[line:37] - CRITICAL: This is a critical message.
以上介绍了Python实现日志同时输出到屏幕和文件的具体配置方法,希望能为开发者提供实用的参考。
免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。









