温馨提示×

Linux下Python日志如何配置

小樊
45
2025-11-14 15:59:01
栏目: 编程语言

在Linux下配置Python日志,通常使用内置的logging模块。以下是一个简单的配置示例:

  1. 首先,导入logging模块:
import logging
  1. 然后,配置日志记录器:
logging.basicConfig(
    level=logging.DEBUG,  # 设置日志级别
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',  # 设置日志格式
    datefmt='%Y-%m-%d %H:%M:%S',  # 设置日期格式
    filename='app.log',  # 设置日志文件名
    filemode='a'  # 设置文件模式,'a'表示追加,'w'表示覆盖
)
  1. 使用日志记录器记录日志:
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')

以上代码将在当前目录下创建一个名为app.log的日志文件,并将日志记录到该文件中。日志级别设置为DEBUG,这意味着所有级别的日志都会被记录。你可以根据需要调整日志级别。

如果你想要更高级的配置,可以使用logging.config.fileConfig()函数从配置文件中加载日志设置。首先,创建一个名为logging.conf的配置文件:

[loggers]
keys=root

[handlers]
keys=fileHandler

[formatters]
keys=simpleFormatter

[logger_root]
level=DEBUG
handlers=fileHandler

[handler_fileHandler]
class=FileHandler
level=DEBUG
formatter=simpleFormatter
args=('app.log', 'a')

[formatter_simpleFormatter]
format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
datefmt=%Y-%m-%d %H:%M:%S

然后,在Python代码中使用logging.config.fileConfig()函数加载配置文件:

import logging
import logging.config

logging.config.fileConfig('logging.conf')

logger = logging.getLogger(__name__)

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')

这样,日志配置将根据logging.conf文件中的设置进行配置。你可以根据需要修改配置文件以满足你的需求。

0