John Mee
John Mee

Reputation: 52313

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

Upvotes: 17

Views: 11333

Answers (2)

Balthazar Rouberol
Balthazar Rouberol

Reputation: 7180

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

Upvotes: 7

Alexander
Alexander

Reputation: 419

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')

Upvotes: 18

Related Questions