Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to output SQLAlchemy logger only to a file

From what I read in the SQLAlchemy logging configuration documentation, I understood that the echo argument on sqlalchemy.create_engine controls whether sqlalchemy logging is forced to stdout, but shouldn't affect whether log messages are available to log handlers.

In the code below, I get no output to stdout OR db.log if echo=False and I get output to both stdout AND db.log if echo=True. I want nothing to stdout while db.log is still populated. How can I accomplish that?

This is python 2.7.6 and sqlalchemy 0.9.9

import sqlalchemy
import logging

active_db_url = 'postgres://user:pass@localhost/log_test'

db_log_file_name = 'db.log'
db_log_level = logging.INFO

db_handler = logging.FileHandler(db_log_file_name)
db_handler.setLevel(db_log_level)

db_logger = logging.getLogger('sqlalchemy')
db_logger.addHandler(db_handler)

engine = sqlalchemy.create_engine(active_db_url, echo=True)
engine.connect()

** EDIT SOLVED** db_logger requires its logLevel be set, too. Not just db_handler.

import sqlalchemy
import logging

active_db_url = 'postgres://user:pass@localhost/log_test'

db_log_file_name = 'db.log'
db_handler_log_level = logging.INFO
db_logger_log_level = logging.DEBUG

db_handler = logging.FileHandler(db_log_file_name)
db_handler.setLevel(db_handler_log_level)

db_logger = logging.getLogger('sqlalchemy')
db_logger.addHandler(db_handler)
db_logger.setLevel(db_logger_log_level)

engine = sqlalchemy.create_engine(active_db_url, echo=False)
engine.connect()
like image 801
Jobu Avatar asked Mar 18 '15 05:03

Jobu


1 Answers

First create a file handle to write logs.

handler = logging.FileHandler('app.log')
handler.setLevel(logging.DEBUG)

Get sqlalchemy logger and add this handle.

logging.getLogger('sqlalchemy').addHandler(handler)
like image 162
Brijesh Gupta Avatar answered Sep 21 '22 02:09

Brijesh Gupta