Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change the 'tag' when logging to syslog from 'Unknown'?

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"?

like image 910
John Mee Avatar asked Mar 03 '12 01:03

John Mee


2 Answers

Simple Way of Tagging Log Messages

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.

Better Solution

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')
like image 149
Alexander Avatar answered Nov 16 '22 13:11

Alexander


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
like image 43
Balthazar Rouberol Avatar answered Nov 16 '22 11:11

Balthazar Rouberol