【发布时间】:2013-05-31 13:06:07
【问题描述】:
我有一个log.py 模块,它至少用于其他两个模块(server.py 和device.py)。
它有这些全局变量:
fileLogger = logging.getLogger()
fileLogger.setLevel(logging.DEBUG)
consoleLogger = logging.getLogger()
consoleLogger.setLevel(logging.DEBUG)
file_logging_level_switch = {
'debug': fileLogger.debug,
'info': fileLogger.info,
'warning': fileLogger.warning,
'error': fileLogger.error,
'critical': fileLogger.critical
}
console_logging_level_switch = {
'debug': consoleLogger.debug,
'info': consoleLogger.info,
'warning': consoleLogger.warning,
'error': consoleLogger.error,
'critical': consoleLogger.critical
}
它有两个功能:
def LoggingInit( logPath, logFile, html=True ):
global fileLogger
global consoleLogger
logFormatStr = "[%(asctime)s %(threadName)s, %(levelname)s] %(message)s"
consoleFormatStr = "[%(threadName)s, %(levelname)s] %(message)s"
if html:
logFormatStr = "<p>" + logFormatStr + "</p>"
# File Handler for log file
logFormatter = logging.Formatter(logFormatStr)
fileHandler = logging.FileHandler(
"{0}{1}.html".format( logPath, logFile ))
fileHandler.setFormatter( logFormatter )
fileLogger.addHandler( fileHandler )
# Stream Handler for stdout, stderr
consoleFormatter = logging.Formatter(consoleFormatStr)
consoleHandler = logging.StreamHandler()
consoleHandler.setFormatter( consoleFormatter )
consoleLogger.addHandler( consoleHandler )
还有:
def WriteLog( string, print_screen=True, remove_newlines=True,
level='debug' ):
if remove_newlines:
string = string.replace('\r', '').replace('\n', ' ')
if print_screen:
console_logging_level_switch[level](string)
file_logging_level_switch[level](string)
我从server.py 调用LoggingInit,它初始化文件和控制台记录器。然后我从各处调用WriteLog,因此多个线程正在访问fileLogger 和consoleLogger。
我的日志文件是否需要任何进一步的保护?文档指出线程锁由处理程序处理。
【问题讨论】:
-
如果你想写的时候没有加锁,你的日志记录可能会混在一起,造成一个不可读的日志。
-
@AliBZ - 什么日志记录?在日志记录级别? python日志记录服务不涵盖它们吗? stackoverflow.com/questions/2973900/…
-
当您在两个不同的线程中使用“fileLogger.info('1 2 3 4')”时,您的最终日志可能是它们的混合,类似于“1 2 1 2 3 3 4 4"
-
我今天遇到了同样的问题,你应该在登录前后加锁以防止这种情况。
-
这不是直接与 python 文档相矛盾(见我的回答)吗?你提出过错误吗?还是我理解错了?
标签: python multithreading logging