Reputation:
This is how my app
is currently set up:
Directory
/xampp/code/menumaster
menumaster
__init__.py
views.py
sqltables.py
__init__.py
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
from sqlalchemy.orm import sessionmaker
from sqlalchemy import *
app = Flask(__name__)
app.debug = True
DBSession = sessionmaker(bind=engine)
import menumaster.views
views.py
from menumaster import app, DBSession
@app.route('/restaurants', methods = ['GET'])
def getRestaurants():
# Code here...
I'm wondering where and how I should be configuring the logger
such that I would be able to use it in different modules and write to some file mylog.txt
.
I have seen examples like this: https://gist.github.com/ibeex/3257877#file-foo-log
However, in my code I don't use
if __name__ == '__main__':
Should I add the logger
configuration code in my __init__.py
file and try it call from there? Any help with the proper way to do this would be greatly appreciated.
UPDATE
My code currently looks like this:
views.py
import logging
import logging.config
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'verbose': {
'format': '%(levelname)s %(asctime)s %(module)s %(process)d % (thread)d %(message)s'
},
},
'handlers': {
'file': {
'level': 'DEBUG',
'class': 'logging.FileHandler',
'filename': 'error.log',
'formatter': 'verbose',
},
},
'loggers': {
'': {
'level': 'WARN',
'handlers': ['file'],
},
}
}
logging.config.dictConfig(LOGGING)
logging.getLogger('sqlalchemy.engine').setLevel(logging.INFO)
logger = logging.getLogger('__name__')
@app.route('/restaurants', methods = ['GET'])
def getRestaurants():
logger.debug('write something to log file')
return 'something'
I currently have two issues:
1) The text "write something to log file"
is not appearing in error.log
.
2) When I remove setLevel(logging.INFO)
from logging.getLogger('sqlalchemy.engine').setLevel(logging.INFO)
, nothing is written to error.log
. I thought this would work as this information was already set in the LOGGING
variable.
I tried changing both the handler
and logger
level to INFO
in LOGGING
but to no avail.
Upvotes: 3
Views: 4224
Reputation: 83348
The best practice is that each Python module declares its own logger like this:
import logging
logger = logging.getLogger(__name__)
Then you can use the standard Python logging configuration to increase or decrease logging verbosity per module and redirect log output from different modules to different logging handlers / files.
See configuring Python logging.
Below is a simple logging configuration dict showing how to set up file logging:
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'verbose': {
'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s'
},
},
'handlers': {
'file': {
'level': 'DEBUG',
'class': 'logging.FileHandler',
'filename': 'logs/django.log',
'formatter': 'verbose',
},
},
'loggers': {}
'': {
'level': 'WARN',
'handlers': ['file'],
},
}
}
Upvotes: 1