使用logging.basicConfig时,python日志文件无法正常工作

Phi*_*hil 30 python logging

我有以下几行代码来初始化日志记录.我评论一个,留下另一个使用.我面临的问题是那个用于登录文件而不是记录到文件的问题.而是登录到控制台.请帮忙.

要登录到控制台:

logging.basicConfig(level=logging.INFO,
        format='%(asctime)s [%(levelname)s] (%(threadName)-10s) %(message)s',)
Run Code Online (Sandbox Code Playgroud)

用于文件记录

logging.basicConfig(filename='server-soap.1.log',level=logging.INFO,
        format='%(asctime)s [%(levelname)s] (%(threadName)-10s) %(message)s')
Run Code Online (Sandbox Code Playgroud)

Phi*_*hil 56

我发现了问题所在.它是在导入和日志记录定义的顺序中.

不良排序的影响是我在定义日志记录之前导入的库logging.basicConfig()定义了日志记录.因此,这优先于我稍后尝试使用的日志记录logging.basicConfig()

以下是我需要订购的方式:

import logging
## for file logging
logging.basicConfig(filename='server-soap.1.log',
        level=logging.INFO,
        format='%(asctime)s %(levelname)s %(threadName)-10s %(message)s',)

from pysimplesoap.server import SoapDispatcher, SOAPHandler
from BaseHTTPServer import HTTPServer
import time,random,datetime,pytz,sys,threading
from datetime import timedelta
#DB
import psycopg2, psycopg2.extras
from psycopg2.pool import ThreadedConnectionPool

#ESB Call
from suds import WebFault
from suds.client import Client
Run Code Online (Sandbox Code Playgroud)

但我最初的错误订单是:

from pysimplesoap.server import SoapDispatcher, SOAPHandler
from BaseHTTPServer import HTTPServer
import logging
import time,random,datetime,pytz,sys,threading
from datetime import timedelta
#DB
import psycopg2, psycopg2.extras
from psycopg2.pool import ThreadedConnectionPool

#ESB Call
from suds import WebFault
from suds.client import Client

## for file logging

logging.basicConfig(filename='server-soap.1.log',
        level=logging.INFO,
        format='%(asctime)s %(levelname)s %(threadName)-10s %(message)s',)
Run Code Online (Sandbox Code Playgroud)

  • 棘手的一个。这让我发疯了! (5认同)
  • 我的天啊!伙计,我需要这个。我花了几天时间试图解决这个问题。非常感谢。 (4认同)
  • 为什么会这样。 (2认同)

vac*_*ing 14

日志记录源代码中,我发现了流程:

This function does nothing if the root logger already has handlers
configured. It is a convenience method intended for use by simple scripts
to do one-shot configuration of the logging package.
Run Code Online (Sandbox Code Playgroud)

因此,如果我们导入的某个模块basicConfig()在我们之前调用了方法,那么我们的调用将无济于事。

我发现可以使用的解决方案是您可以在调用之前重新加载日志记录basicConfig(),例如

def init_logger(*, fn=None):

    # !!! here
    from imp import reload # python 2.x don't need to import reload, use it directly
    reload(logging)

    logging_params = {
        'level': logging.INFO,
        'format': '%(asctime)s__[%(levelname)s, %(module)s.%(funcName)s](%(name)s)__[L%(lineno)d] %(message)s',
    }

    if fn is not None:
        logging_params['filename'] = fn

    logging.basicConfig(**logging_params)
    logging.error('init basic configure of logging success')
Run Code Online (Sandbox Code Playgroud)


Sha*_*ani 10

如果basicConfig()不起作用:

logger = logging.getLogger('Spam Logger')
logger.setLevel(logging.DEBUG)
# create file handler which logs even debug messages
fh = logging.FileHandler('spam.log')
fh.setLevel(logging.DEBUG)
# create console handler with a higher log level
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
# create formatter and add it to the handlers
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
ch.setFormatter(formatter)
fh.setFormatter(formatter)
# add the handlers to logger
logger.addHandler(ch)
logger.addHandler(fh)

# 'application' code
logger.debug('debug Spam message')
logging.debug('debug Spam message')
logger.info('info Ham message')
logger.warning('warn Eggs message')
logger.error('error Spam and Ham message')
logger.critical('critical Ham and Eggs message')
Run Code Online (Sandbox Code Playgroud)

这给了我以下输出:

2019-06-20 11:33:48,967 - Spam Logger - DEBUG - debug Spam message
2019-06-20 11:33:48,968 - Spam Logger - INFO - info Ham message
2019-06-20 11:33:48,968 - Spam Logger - WARNING - warn Eggs message
2019-06-20 11:33:48,968 - Spam Logger - ERROR - error Spam and Ham message
2019-06-20 11:33:48,968 - Spam Logger - CRITICAL - critical Ham and Eggs message
Run Code Online (Sandbox Code Playgroud)

为了便于参考,Python Logging Cookbook值得一读。

  • 只是想强调“logger.setLevel()”至关重要,因为这花了我一个小时,因为我在答案中没有注意到;即,即使您的处理程序具有“DEBUG”级别,“logger”的默认值也是“WARN”,因此如果没有“logger.setLevel()”,您的“INFO”和“DEBUG”将无法通过。 (4认同)

Ale*_*ese 5

我遇到了同样的错误,我通过将以下参数传递给基本配置来修复它。

logging.basicConfig(
    level="WARNING",
    format="%(asctime)s - %(name)s - [ %(message)s ]",
    datefmt='%d-%b-%y %H:%M:%S',
    force=True,
    handlers=[
        logging.FileHandler("debug.log"),
        logging.StreamHandler()
    ])
Run Code Online (Sandbox Code Playgroud)

在这里你可以看到传递force=True覆盖任何其他BasicConfigs

  • “3.8 版更改:添加了力参数。” 我认为这是新版本更好的选择 (2认同)
  • 这应该被标记为已接受的答案。非常感谢,添加 `force=True` 就成功了。 (2认同)