I'm seeking a way to let the python logger module to log to database and falls back to file system when the db is down.
So basically 2 things: How to let the logger log to database and how to make it fall to file logging when the db is down.
I'm seeking a way to let the python logger module to log to database and falls back to file system when the db is down.
So basically 2 things: How to let the logger log to database and how to make it fall to file logging when the db is down.
Old question, but dropping this for others. If you want to use python logging, you can add two handlers. One for writing to file, a rotating file handler. This is robust, and can be done regardless if the dB is up or not. The other one can write to another service/module, like a pymongo integration.
Look up logging.config on how to setup your handlers from code or json.
Write yourself a handler that directs the logs to the database in question. When it fails, you can remove it from the handler list of the logger. There are many ways to deal with the failure-modes.
I am digging this out again.
There is a solution with SqlAlchemy (Pyramid is NOT required for this recipe):
https://docs.pylonsproject.org/projects/pyramid-cookbook/en/latest/logging/sqlalchemy_logger.html
And you could improve logging by adding extra fields, here is a guide: https://stackoverflow.com/a/17558764/1115187
Fallback to FS
Not sure that this is 100% correct, but you could have 2 handlers:
Just wrap the DB-commit with a
try-except
. But be aware: the file will contain ALL log entries, but not only entries for which DB saving was failed.geez... lots of time passed, but I recently managed to write my own database logger in Python. Since I couldn't find any example I thought I post mine here. Maybe someone will find this helpful :) Works with MS SQL.
Database table could look like this:
The class itself:
And usage example:
Above will log both to the database and to the file. If file is not needed - skip the 'logging.basicConfig(filename=log_file_path)' line. Everything logged using 'log' - will be logged as MY_LOGGER. If some external error appears (i.e. in the module imported or something) - error will appear as 'root', since 'root' logger is also active, and is using the database handler.
Have you seen log4mongo library? https://pypi.python.org/pypi/log4mongo/ It provides a handle for Mongo. The fallback is not there but I suppose it would be relatively easy to add.