From 3eb019f875fc63eadfab29b4e0ad143409cf4cb2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Zbigniew=20J=C4=99drzejewski-Szmek?= Date: Thu, 28 Jun 2012 13:50:49 -0400 Subject: Use traceback module to specify CODE_{LINE,FUNC,FILE} $python3 -c 'import journald; x = lambda: journald.send("tescik"); x()' gives a message like: MESSAGE=tescik CODE_FILE= CODE_LINE=1 CODE_FUNC= _TRANSPORT=journal ... This makes the CODE_* fields much more useful: before they would always give the location of the sd_journald_sendv() call in the module source, and now they specify the location of the caller of journald.send(). When using the low-level journald.sendv() is becomes the responsibility of the caller to specify the CODE_* fields. --- journald/__init__.py | 21 +++++++++++++++++---- journald/_journald.c | 1 + 2 files changed, 18 insertions(+), 4 deletions(-) diff --git a/journald/__init__.py b/journald/__init__.py index b892faf..23941a6 100644 --- a/journald/__init__.py +++ b/journald/__init__.py @@ -1,6 +1,9 @@ +import traceback from ._journald import sendv -def send(MESSAGE, MESSAGE_ID=None, **kwargs): +def send(MESSAGE, MESSAGE_ID=None, + CODE_FILE=None, CODE_LINE=None, CODE_FUNC=None, + **kwargs): """Send a message to journald. >>> journald.send('Hello world') @@ -16,15 +19,25 @@ def send(MESSAGE, MESSAGE_ID=None, **kwargs): CODE_LINE, CODE_FILE, and CODE_FUNC can be specified to identify the caller. Unless at least on of the three is given, values are extracted from the stack frame of the caller of send(). CODE_FILE - and CODE_FUNC should be strings, CODE_LINE should be an integer. + and CODE_FUNC must be strings, CODE_LINE must be an integer. Other useful fields include PRIORITY, SYSLOG_FACILITY, SYSLOG_IDENTIFIER, SYSLOG_PID. """ args = ['MESSAGE=' + MESSAGE] + if MESSAGE_ID is not None: args.append('MESSAGE_ID=' + MESSAGE_ID) - for key, val in kwargs.items(): - args.append(key + '=' + val) + + if CODE_LINE == CODE_FILE == CODE_FUNC == None: + CODE_FILE, CODE_LINE, CODE_FUNC = traceback.extract_stack(limit=2)[0][:3] + if CODE_FILE is not None: + args.append('CODE_FILE=' + CODE_FILE) + if CODE_LINE is not None: + args.append('CODE_LINE={:d}'.format(CODE_LINE)) + if CODE_FUNC is not None: + args.append('CODE_FUNC=' + CODE_FUNC) + + args.extend(key + '=' + val for key, val in kwargs.items()) return sendv(*args) diff --git a/journald/_journald.c b/journald/_journald.c index 024ebc6..a289255 100644 --- a/journald/_journald.c +++ b/journald/_journald.c @@ -1,4 +1,5 @@ #include +#define SD_JOURNAL_SUPPRESS_LOCATION #include static PyObject * -- cgit v1.2.1