简体   繁体   中英

How to deal with regular messages in Python's logging?

Python's logging facility comes with several levels of severity:

  • CRITICAL
  • ERROR
  • WARNING*
  • INFO
  • DEBUG
  • NOTSET

*The root logger defaults to WARNING.


How does one deal with regular messages in this setup?

With "regular messages" I mean those that are not warnings but should always be shown to the user.

An example could be:

Loop over a list of files and apply an accumulating operation to them. A "regular message" could be "currently working on {filename}". The INFO level might hold the status of individual sub-steps of the file treatment that the user may not be interested in knowing most of the time. On the WARNING level could be potential problems like two files containing differing entries for the same key.

I think that I want a level between WARNING and INFO, which might be called NOTICE, NOTE, REGULAR or similar. This level would be my default instead of WARNING. Why does logging not provide such a level?

I understand that I can add such a level fairly easily but the logging manual strongly argues against custom levels . Thus, I assume there must be a canonical way of logging messages like the above ...


EDIT: Just to clarify regarding the vote to close for being "opinion-based": I would like to know how logging is supposed to be used sticking to the given set of levels and conventions. Thus, I would think that the correct answer is not necessarily an opinion but should be the best practice of using this module.

The manual states "Defining your own levels is possible, but should not be necessary, as the existing levels have been chosen on the basis of practical experience". In my example above, I seem to be lacking one level: either "regular messages" or -- if I switch to INFO meaning "regular messages" -- something like "verbose info" for the user.

Log messages are not really indented for the user. What you are describing sounds more like regular output. However there are at least two possible ways to solve this. Either make the regular message INFO level and move the not-as-interesting messages to the DEBUG level, or use a log filter . To quote the documentation:

Filters can be used by Handlers and Loggers for more sophisticated filtering than is provided by levels.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM