class MyHandler(StreamHandler):
pass
class Logger:
def __init__(self):
self._l = logging.getLogger('someident')
self._l.addHandler(MyHandler('/path/to/logfile'))
Now I want to configure this logger through a configuration
file. How can I refer to the new handler in the configuration file?
Something like "class=MyHandler" did not work.
Any ideas?
Thanks,
Andreas
you will have to be a tad more specific, i´m afraid. what does your
file layout look like? assuming that you have ::
fx.py
class X:
...
fy.py
class Y:
...
y = Y()
then, in order to refer to X, Y, or y from a third file, you can do
something like ::
from fx import X
from fy import Y
from fy import y
or ::
import fx.X
or ::
import fx.X as foo
there. does that help?
_wolf
> I am trying to write a custom logger with a custom handler:
> Now I want to configure this logger through a configuration
> file. How can I refer to the new handler in the configuration file?
> Something like "class=MyHandler" did not work.
>
> Any ideas?
The handler's class is evaluatated like so in module logging.config:
klass = eval(klass, vars(logging))
For this to succeed you could do something like:
import logging
import logging.config
class MyHandler(logging.StreamHandler):
pass
logging.MyHandler = MyHandler
logging.config.fileConfig("test.cfg")
lgr = logging.getLogger("test")
lgr.info("Hello world")
where the relevant handler section has the line
class=MyHandler
I do not know if there is an "official" way to achieve the same, but then,
why would you build your own Handler in the first place?
Peter
Peter> I do not know if there is an "official" way to achieve the
Peter> same, but then, why would you build your own Handler in the
Peter> first place?
I've just done exactly the same approach (independently), because of a
need to build two Handlers of my own. One is to avoid tracebacks
being logged with a SysLogHandler (it makes the syslog messages too
long, so nothing is logged), and the other is a subclass of
SMTPHandler which changes the subject of the mail if an exception of a
certain type is raised. [1]
I can think of plenty of other instances where building a custom
Handler is needed; for example, an SQLHandler which might log messages
to a database.
[1] This might be better done with a different Formatter, but getting
a custom Formatter to be used by logging.config is much harder than a
custom Handler, due to logging.Formatter() being called from within
logging.config.fileConfig().
Personally I think logging.config.fileConfig() is in need of some
serious refactoring... if only I had time to look into it!
-- Neil