I'm logging to syslog fine but can't work out how to specify the 'tag'. The logging currently posts this:
Mar 3 11:45:34 TheMacMini Unknown: INFO FooBar
but I want that 'Unknown' to be set to something. eg:
Mar 3 11:45:34 TheMacMini Foopybar: INFO FooBar
If I use logger
from the command line it can be controlled via the -t
option...
$ logger -t Foopybar FooBar && tail -1 /var/log/system.log
Mar 3 12:05:00 TheMacMini Foopybar[4566]: FooBar
But logging from python I don't seem to be able to specify the tag:
import logging
logging.info("FooBar")
Just gives me the 'Unknown' tag shown at the top. I've defined this spec:
LOGGING = {
'version': 1,
'formatters': {
'simple': {
'format': '%(levelname)s %(message)s'
},
},
'handlers': {
'syslog':{
'address': '/var/run/syslog',
'class': 'logging.handlers.SysLogHandler',
'facility': 'local2',
'formatter': 'simple'
}
},
'loggers': {
'': {
'handlers': ['syslog'],
'level': 'INFO',
}
}
}
How do I specify the tag so it's not always "Unknown"?
Do this:
logging.info("TagName: FooBar")
and you message will be tagged! You just need to start all your messages with "TagName: ". And this is of course not very elegant.
Setup your logger:
log = logging.getLogger('name')
address=('log-server',logging.handlers.SYSLOG_UDP_PORT)
facility=logging.handlers.SysLogHandler.LOG_USER
h=logging.handlers.SysLogHandler( address,facility )
f = logging.Formatter('TagName: %(message)s')
h.setFormatter(f)
log.addHandler(h)
And use it:
log.info('FooBar')
I'm adding this just for the sake of completion, even though @sasha's answer is absolutely correct.
If you happen to log messages to syslog directly using syslog.syslog
, you can set the tag using the syslog.openlog
function:
import syslog
syslog.openlog('foo')
syslog.syslog('bar')
Going back to the linux shell:
$ tail -f /var/log/syslog
Sep 7 07:01:58 dev-balthazar foo: bar
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With