2

So I'm using python's built in logging module to perform logging. In general, I really like the way it works but I'm wondering if there is an easy way to do the following:

I want to log data out to a file and console as my script is executing, preferably using logger.info(). I would also like to log warnings/errors out to the console, preferably using logger.warning() and logger.error(). That part is easy. However, I would also like if the warnings/errors did not also go to the info log.

Right now from my understanding, if I have a handler set at the info level, it will always pass anything at the info level and higher.

The only solution I can think of is to separate my logging to two separate loggers but I would like to avoid that.

Jeff LaFay
  • 12,882
  • 13
  • 71
  • 101
MattyP
  • 821
  • 2
  • 9
  • 16
  • Although I did do searching before asking, I actually found my answer in this question: http://stackoverflow.com/questions/1383254/logging-streamhandler-and-standard-streams (If there is an appropriate way to mark this, will someone let me know? Thanks!) – MattyP Apr 13 '12 at 21:22
  • Add your answer as an answer rather than as a comment, and then accept it. – Vinay Sajip Apr 14 '12 at 08:53

1 Answers1

1

I believe the cleaner approach would be to process log messages differently in handler, based on the levels of log records. LogRecord objects have levelno and levelname properties, so you have pretty much everything you need to distinguish logging.error() from logging.warning() and logging.debug().

More details: http://docs.python.org/library/logging.html#logrecord-objects

Tadeck
  • 132,510
  • 28
  • 152
  • 198
  • does that mean I would need to create my own loging handler? – MattyP Apr 13 '12 at 20:48
  • @MattyP: Not necessarily. You can use existing handlers (one for each method of logging) and add different filters to them. Answering the question you may have ("_do I need to create my own filter?_"): it depends - any instance with `filter` method will do (http://docs.python.org/library/logging.html#filter-objects), you just need to find some suitable existing filter :) – Tadeck Apr 13 '12 at 23:24