Python logging: Per-file/module logger -


i have python code need add logging to.

i've preferred nice big c macro looking statements "debug()", "error()", etc logging. feel makes code easier read (no objects) when trace-points visually differentiable actual code.

i able set logging levels @ per-module level.

how make module called "log" capable of doing (while making use of python std library logging module)?

e.g.:

file: main.py

# imports log_module_name, debug, warn, etc log import * import my_module  log_module_name("main")  log.set_level("main", log.lvl_debug) log.set_level("my_module", log.lvl_warn)  if __name__ == "__main__":     foo = my_module.myfunc(2)  debug("exiting main.py") 

file: my_module.py

from log import *  log_module_name("my_module")   def myfunc(x):     debug("entering function")     if x != 1:          warn("i thought 1")     debug("exiting function")     return x+1 

i'd expect output like:

[warn:my_module - my_module.py:9] thought 1 [debug:main - main.py:11] exiting main.py 

if want have logger's name indicate module in used, can use logger.getlogger([name]) module function, , pass __name__ (optional) argument, explained here.

if want use names debug(), in each of files...

log_module_name = logging.getlogger(__name__)  def debug(msg):     global log_module_name     log_module_name.debug(msg) 

i not clear on way global namespaces work in python... this answer says

each module has own "global" namespace.

so guess fine that, since log_module_name won't collide between modules.

i believe approach give one logfile, lines this:

debug:my_module:entering function warn:my_module:i thought 1 debug:my_module:exiting function debug:root:exiting main.py 

not instrospective enough? want inpsect module, give lot of information program while it's running. will, instance, current line number.

your note "setting log levels @ per-module level" makes me think want geteffectivelevel(). try smush in this:

log_module_name = logging.getlogger(__name__) module_log_level = log.lvl_warn  def debug(msg):     if module_log_level = log.lvl_debug:         global log_module_name         log_module_name.debug(msg) 

i'm not experienced enough logging module able tell how might able make each module's log change levels dynamically, though.


Comments

Popular posts from this blog

php - Calling a template part from a post -

Firefox SVG shape not printing when it has stroke -

How to mention the localhost in android -