dalanmiller
dalanmiller

Reputation: 3662

Simplifying logging in Flask

I currently have this as my basic logger for my Flask application. Although I see that there is an Flask.logger object. How do I make use of the native Flask logger? Or is what I'm doing below just fine?

I'm also a little confused as to where the different logging statuses go, for example logging to info versus logging to error?

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

Upvotes: 9

Views: 7509

Answers (1)

Yinian Chin
Yinian Chin

Reputation: 98

Probably what you want is described as following.

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

Upvotes: 4

Related Questions