简化Flask中的日志记录

时间:2012-10-18 22:11:23

标签: python logging flask

我目前将此作为Flask应用程序的基本记录器。虽然我看到有一个Flask.logger object。如何使用本机Flask记录器?或者我正在做什么就好了?

我对于不同的日志记录状态的位置也有点困惑,例如记录到信息与记录到错误?

LOG_FILENAME = 'app_access_logs.log'

info_log = logging.getLogger('app_info_log')
info_log.setLevel(logging.INFO)

handler = logging.handlers.RotatingFileHandler(
    LOG_FILENAME,
    maxBytes=1024 * 1024 * 100,
    backupCount=20
    )

info_log.addHandler(handler)

...

@app.before_request
def pre_request_logging():
    #Logging statement
    if 'text/html' in request.headers['Accept']:
        info_log.info('\t'.join([
            datetime.datetime.today().ctime(),
            request.remote_addr,
            request.method,
            request.url,
            request.data,
            ', '.join([': '.join(x) for x in request.headers])])
        )

1 个答案:

答案 0 :(得分:4)

你想要的可能描述如下。

LOG_FILENAME = 'app_access_logs.log'

app.logger.setLevel(logging.INFO) # use the native logger of flask

handler = logging.handlers.RotatingFileHandler(
    LOG_FILENAME,
    maxBytes=1024 * 1024 * 100,
    backupCount=20
    )

app.logger.addHandler(handler)

...

@app.before_request
def pre_request_logging():
    #Logging statement
    if 'text/html' in request.headers['Accept']:
        app.logger.info('\t'.join([
            datetime.datetime.today().ctime(),
            request.remote_addr,
            request.method,
            request.url,
            request.data,
            ', '.join([': '.join(x) for x in request.headers])])
        )