3

What I have

I have written a Python class that writes messages to a custom log via rsyslog. This is scaling off of my previous question, which I have temporarily circumvented by prepending my app's name to each message and have rsyslog configured to put all logs containing my app's name to my custom log. However, I am concerned that something else on the system writes to rsyslog and that message just so happens to contain my app's name, rsyslog will detect this send that log entry to my log. I would also prefer the look of my app's name instead of journal appearing throughout my log.

Attached is my code:

import logging
from logging import handlers

lumberjack = logging.getLogger("MyAppName")
lumberjack.setLevel(logging.INFO)
handler = handlers.SysLogHandler(address='/dev/log')
handler.setFormatter(logging.Formatter('%(name)s %(levelname)s: %(message)s'))
handler.ident = "MyAppName"
lumberjack.addHandler(handler)
lumberjack.critical("I'm okay") 

Goal

The following two messages are examples. The first was written by my Python class. The second was written by me running logger -t MyAppName -s "Hey buddy, I think you’ve got the wrong app name"

Aug 22 15:49:53 melchior journal: MyAppNameMyAppName CRITICAL: I'm okay.
Aug 22 15:57:06 melchior MyAppName: Hey buddy, I think you’ve got the wrong app name

Question

What do I have to change in my Python code to get these lines to look the same, but with the levelname included as I have already done so?

Nathan Smith
  • 683
  • 1
  • 10
  • 24

1 Answers1

0

Change the following line

handler.setFormatter(logging.Formatter('%(name)s %(levelname)s: %(message)s'))

to look like this (basically just add a colon after %(name)s:

handler.setFormatter(logging.Formatter('%(name)s: %(levelname)s: %(message)s'))

then remove the following line to avoid app name duplication:

handler.ident = "MyAppName"

and now it does the trick:

Sep 10 06:52:33 hostname MyAppName: CRITICAL: I'm okay

Konstantin Kelemen
  • 85
  • 1
  • 1
  • 11
  • Hmm, python 3.8.6 this seems to come up as MyAppName__main__: INFO message ... EDIT: This is because I have a logger name, and ident. I was using logging.getLogger(\_\_name\_\_) – Raid Jun 04 '21 at 21:31