@@ -320,9 +320,11 @@ def messageid_match(self, messageid):
320320 self .add_match (MESSAGE_ID = messageid )
321321
322322 def this_boot (self , bootid = None ):
323- """Add match for _BOOT_ID equal to current boot ID or the specified boot ID.
323+ """Add match for _BOOT_ID equal to current boot ID or the specified
324+ boot ID.
324325
325- If specified, bootid should be either a UUID or a 32 digit hex number.
326+ If specified, bootid should be either a UUID or a 32 digit hex
327+ number.
326328
327329 Equivalent to add_match(_BOOT_ID='bootid').
328330 """
@@ -353,201 +355,197 @@ def get_catalog(mid):
353355 return _get_catalog (mid )
354356
355357def _make_line (field , value ):
356- if isinstance (value , bytes ):
357- return field .encode ('utf-8' ) + b'=' + value
358- elif isinstance (value , int ):
359- return field + '=' + str (value )
360- else :
361- return field + '=' + value
358+ if isinstance (value , bytes ):
359+ return field .encode ('utf-8' ) + b'=' + value
360+ elif isinstance (value , int ):
361+ return field + '=' + str (value )
362+ else :
363+ return field + '=' + value
362364
363365def send (MESSAGE , MESSAGE_ID = None ,
364366 CODE_FILE = None , CODE_LINE = None , CODE_FUNC = None ,
365367 ** kwargs ):
366- r"""Send a message to the journal.
368+ r"""Send a message to the journal.
367369
368- >>> from systemd import journal
369- >>> journal.send('Hello world')
370- >>> journal.send('Hello, again, world', FIELD2='Greetings!')
371- >>> journal.send('Binary message', BINARY=b'\xde\xad\xbe\xef')
370+ >>> from systemd import journal
371+ >>> journal.send('Hello world')
372+ >>> journal.send('Hello, again, world', FIELD2='Greetings!')
373+ >>> journal.send('Binary message', BINARY=b'\xde\xad\xbe\xef')
372374
373- Value of the MESSAGE argument will be used for the MESSAGE=
374- field. MESSAGE must be a string and will be sent as UTF-8 to
375- the journal.
375+ Value of the MESSAGE argument will be used for the MESSAGE=
376+ field. MESSAGE must be a string and will be sent as UTF-8 to the
377+ journal.
376378
377- MESSAGE_ID can be given to uniquely identify the type of
378- message. It must be a string or a uuid.UUID object.
379+ MESSAGE_ID can be given to uniquely identify the type of
380+ message. It must be a string or a uuid.UUID object.
379381
380- CODE_LINE, CODE_FILE, and CODE_FUNC can be specified to
381- identify the caller. Unless at least on of the three is given,
382- values are extracted from the stack frame of the caller of
383- send(). CODE_FILE and CODE_FUNC must be strings, CODE_LINE
384- must be an integer.
382+ CODE_LINE, CODE_FILE, and CODE_FUNC can be specified to identify
383+ the caller. Unless at least on of the three is given, values are
384+ extracted from the stack frame of the caller of send(). CODE_FILE
385+ and CODE_FUNC must be strings, CODE_LINE must be an integer.
385386
386- Additional fields for the journal entry can only be specified
387- as keyword arguments. The payload can be either a string or
388- bytes. A string will be sent as UTF-8, and bytes will be sent
389- as-is to the journal.
387+ Additional fields for the journal entry can only be specified as
388+ keyword arguments. The payload can be either a string or bytes. A
389+ string will be sent as UTF-8, and bytes will be sent as-is to the
390+ journal.
390391
391- Other useful fields include PRIORITY, SYSLOG_FACILITY,
392- SYSLOG_IDENTIFIER, SYSLOG_PID.
393- """
392+ Other useful fields include PRIORITY, SYSLOG_FACILITY,
393+ SYSLOG_IDENTIFIER, SYSLOG_PID.
394+ """
394395
395- args = ['MESSAGE=' + MESSAGE ]
396+ args = ['MESSAGE=' + MESSAGE ]
396397
397- if MESSAGE_ID is not None :
398- id = getattr (MESSAGE_ID , 'hex' , MESSAGE_ID )
399- args .append ('MESSAGE_ID=' + id )
398+ if MESSAGE_ID is not None :
399+ id = getattr (MESSAGE_ID , 'hex' , MESSAGE_ID )
400+ args .append ('MESSAGE_ID=' + id )
400401
401- if CODE_LINE == CODE_FILE == CODE_FUNC == None :
402- CODE_FILE , CODE_LINE , CODE_FUNC = \
403- _traceback .extract_stack (limit = 2 )[0 ][:3 ]
404- if CODE_FILE is not None :
405- args .append ('CODE_FILE=' + CODE_FILE )
406- if CODE_LINE is not None :
407- args .append ('CODE_LINE={:d}' .format (CODE_LINE ))
408- if CODE_FUNC is not None :
409- args .append ('CODE_FUNC=' + CODE_FUNC )
402+ if CODE_LINE == CODE_FILE == CODE_FUNC == None :
403+ CODE_FILE , CODE_LINE , CODE_FUNC = _traceback .extract_stack (limit = 2 )[0 ][:3 ]
404+ if CODE_FILE is not None :
405+ args .append ('CODE_FILE=' + CODE_FILE )
406+ if CODE_LINE is not None :
407+ args .append ('CODE_LINE={:d}' .format (CODE_LINE ))
408+ if CODE_FUNC is not None :
409+ args .append ('CODE_FUNC=' + CODE_FUNC )
410410
411- args .extend (_make_line (key , val ) for key , val in kwargs .items ())
412- return sendv (* args )
411+ args .extend (_make_line (key , val ) for key , val in kwargs .items ())
412+ return sendv (* args )
413413
414414def stream (identifier , priority = LOG_DEBUG , level_prefix = False ):
415- r"""Return a file object wrapping a stream to journal.
415+ r"""Return a file object wrapping a stream to journal.
416416
417- Log messages written to this file as simple newline sepearted
418- text strings are written to the journal.
417+ Log messages written to this file as simple newline sepearted text
418+ strings are written to the journal.
419419
420- The file will be line buffered, so messages are actually sent
421- after a newline character is written.
420+ The file will be line buffered, so messages are actually sent
421+ after a newline character is written.
422422
423- >>> from systemd import journal
424- >>> stream = journal.stream('myapp')
425- >>> res = stream.write('message...\n')
423+ >>> from systemd import journal
424+ >>> stream = journal.stream('myapp')
425+ >>> res = stream.write('message...\n')
426426
427- will produce the following message in the journal::
427+ will produce the following message in the journal::
428428
429- PRIORITY=7
430- SYSLOG_IDENTIFIER=myapp
431- MESSAGE=message...
429+ PRIORITY=7
430+ SYSLOG_IDENTIFIER=myapp
431+ MESSAGE=message...
432432
433- Using the interface with print might be more convinient:
433+ Using the interface with print might be more convinient:
434434
435- >>> from __future__ import print_function
436- >>> print('message...', file=stream) # doctest: +SKIP
435+ >>> from __future__ import print_function
436+ >>> print('message...', file=stream) # doctest: +SKIP
437437
438- priority is the syslog priority, one of `LOG_EMERG`,
439- `LOG_ALERT`, `LOG_CRIT`, `LOG_ERR`, `LOG_WARNING`,
440- `LOG_NOTICE`, `LOG_INFO`, `LOG_DEBUG`.
438+ priority is the syslog priority, one of `LOG_EMERG`,
439+ `LOG_ALERT`, `LOG_CRIT`, `LOG_ERR`, `LOG_WARNING`,
440+ `LOG_NOTICE`, `LOG_INFO`, `LOG_DEBUG`.
441441
442- level_prefix is a boolean. If true, kernel-style log priority
443- level prefixes (such as '<1>') are interpreted. See
444- sd-daemon(3) for more information.
445- """
442+ level_prefix is a boolean. If true, kernel-style log priority
443+ level prefixes (such as '<1>') are interpreted. See
444+ sd-daemon(3) for more information.
445+ """
446446
447- fd = stream_fd (identifier , priority , level_prefix )
448- return _os .fdopen (fd , 'w' , 1 )
447+ fd = stream_fd (identifier , priority , level_prefix )
448+ return _os .fdopen (fd , 'w' , 1 )
449449
450450class JournalHandler (_logging .Handler ):
451- """Journal handler class for the Python logging framework.
451+ """Journal handler class for the Python logging framework.
452452
453- Please see the Python logging module documentation for an
454- overview: http://docs.python.org/library/logging.html.
453+ Please see the Python logging module documentation for an
454+ overview: http://docs.python.org/library/logging.html.
455455
456- To create a custom logger whose messages go only to journal:
456+ To create a custom logger whose messages go only to journal:
457457
458- >>> import logging
459- >>> log = logging.getLogger('custom_logger_name')
460- >>> log.propagate = False
461- >>> log.addHandler(JournalHandler())
462- >>> log.warn("Some message: %s", 'detail')
458+ >>> import logging
459+ >>> log = logging.getLogger('custom_logger_name')
460+ >>> log.propagate = False
461+ >>> log.addHandler(JournalHandler())
462+ >>> log.warn("Some message: %s", 'detail')
463463
464- Note that by default, message levels `INFO` and `DEBUG` are
465- ignored by the logging framework. To enable those log levels:
464+ Note that by default, message levels `INFO` and `DEBUG` are
465+ ignored by the logging framework. To enable those log levels:
466466
467- >>> log.setLevel(logging.DEBUG)
467+ >>> log.setLevel(logging.DEBUG)
468468
469- To redirect all logging messages to journal regardless of where
470- they come from, attach it to the root logger:
469+ To redirect all logging messages to journal regardless of where
470+ they come from, attach it to the root logger:
471471
472- >>> logging.root.addHandler(JournalHandler())
472+ >>> logging.root.addHandler(JournalHandler())
473473
474- For more complex configurations when using `dictConfig` or
475- `fileConfig`, specify `systemd.journal.JournalHandler` as the
476- handler class. Only standard handler configuration options
477- are supported: `level`, `formatter`, `filters`.
474+ For more complex configurations when using `dictConfig` or
475+ `fileConfig`, specify `systemd.journal.JournalHandler` as the
476+ handler class. Only standard handler configuration options
477+ are supported: `level`, `formatter`, `filters`.
478478
479- To attach journal MESSAGE_ID, an extra field is supported:
479+ To attach journal MESSAGE_ID, an extra field is supported:
480480
481- >>> import uuid
482- >>> mid = uuid.UUID('0123456789ABCDEF0123456789ABCDEF')
483- >>> log.warn("Message with ID", extra={'MESSAGE_ID': mid})
481+ >>> import uuid
482+ >>> mid = uuid.UUID('0123456789ABCDEF0123456789ABCDEF')
483+ >>> log.warn("Message with ID", extra={'MESSAGE_ID': mid})
484484
485- Fields to be attached to all messages sent through this
486- handler can be specified as keyword arguments. This probably
487- makes sense only for SYSLOG_IDENTIFIER and similar fields
488- which are constant for the whole program:
485+ Fields to be attached to all messages sent through this handler
486+ can be specified as keyword arguments. This probably makes sense
487+ only for SYSLOG_IDENTIFIER and similar fields which are constant
488+ for the whole program:
489489
490- >>> JournalHandler(SYSLOG_IDENTIFIER='my-cool-app')
491- <systemd.journal.JournalHandler object at ...>
490+ >>> JournalHandler(SYSLOG_IDENTIFIER='my-cool-app')
491+ <systemd.journal.JournalHandler object at ...>
492492
493- The following journal fields will be sent:
494- `MESSAGE`, `PRIORITY`, `THREAD_NAME`, `CODE_FILE`, `CODE_LINE`,
495- `CODE_FUNC`, `LOGGER` (name as supplied to getLogger call),
496- `MESSAGE_ID` (optional, see above), `SYSLOG_IDENTIFIER` (defaults
497- to sys.argv[0]).
498- """
493+ The following journal fields will be sent: `MESSAGE`, `PRIORITY`,
494+ `THREAD_NAME`, `CODE_FILE`, `CODE_LINE`, `CODE_FUNC`, `LOGGER`
495+ (name as supplied to getLogger call), `MESSAGE_ID` (optional, see
496+ above), `SYSLOG_IDENTIFIER` (defaults to sys.argv[0]).
497+ """
498+
499+ def __init__ (self , level = _logging .NOTSET , ** kwargs ):
500+ super (JournalHandler , self ).__init__ (level )
501+
502+ for name in kwargs :
503+ if not _valid_field_name (name ):
504+ raise ValueError ('Invalid field name: ' + name )
505+ if 'SYSLOG_IDENTIFIER' not in kwargs :
506+ kwargs ['SYSLOG_IDENTIFIER' ] = _sys .argv [0 ]
507+ self ._extra = kwargs
508+
509+ def emit (self , record ):
510+ """Write record as journal event.
499511
500- def __init__ (self , level = _logging .NOTSET , ** kwargs ):
501- super (JournalHandler , self ).__init__ (level )
502-
503- for name in kwargs :
504- if not _valid_field_name (name ):
505- raise ValueError ('Invalid field name: ' + name )
506- if 'SYSLOG_IDENTIFIER' not in kwargs :
507- kwargs ['SYSLOG_IDENTIFIER' ] = _sys .argv [0 ]
508- self ._extra = kwargs
509-
510- def emit (self , record ):
511- """Write record as journal event.
512-
513- MESSAGE is taken from the message provided by the
514- user, and PRIORITY, LOGGER, THREAD_NAME,
515- CODE_{FILE,LINE,FUNC} fields are appended
516- automatically. In addition, record.MESSAGE_ID will be
517- used if present.
518- """
519- try :
520- msg = self .format (record )
521- pri = self .mapPriority (record .levelno )
522- mid = getattr (record , 'MESSAGE_ID' , None )
523- send (msg ,
524- MESSAGE_ID = mid ,
525- PRIORITY = format (pri ),
526- LOGGER = record .name ,
527- THREAD_NAME = record .threadName ,
528- CODE_FILE = record .pathname ,
529- CODE_LINE = record .lineno ,
530- CODE_FUNC = record .funcName ,
531- ** self ._extra )
532- except Exception :
533- self .handleError (record )
534-
535- @staticmethod
536- def mapPriority (levelno ):
537- """Map logging levels to journald priorities.
538-
539- Since Python log level numbers are "sparse", we have
540- to map numbers in between the standard levels too.
541- """
542- if levelno <= _logging .DEBUG :
543- return LOG_DEBUG
544- elif levelno <= _logging .INFO :
545- return LOG_INFO
546- elif levelno <= _logging .WARNING :
547- return LOG_WARNING
548- elif levelno <= _logging .ERROR :
549- return LOG_ERR
550- elif levelno <= _logging .CRITICAL :
551- return LOG_CRIT
552- else :
553- return LOG_ALERT
512+ MESSAGE is taken from the message provided by the user, and
513+ PRIORITY, LOGGER, THREAD_NAME, CODE_{FILE,LINE,FUNC} fields
514+ are appended automatically. In addition, record.MESSAGE_ID
515+ will be used if present.
516+ """
517+ try :
518+ msg = self .format (record )
519+ pri = self .mapPriority (record .levelno )
520+ mid = getattr (record , 'MESSAGE_ID' , None )
521+ send (msg ,
522+ MESSAGE_ID = mid ,
523+ PRIORITY = format (pri ),
524+ LOGGER = record .name ,
525+ THREAD_NAME = record .threadName ,
526+ CODE_FILE = record .pathname ,
527+ CODE_LINE = record .lineno ,
528+ CODE_FUNC = record .funcName ,
529+ ** self ._extra )
530+ except Exception :
531+ self .handleError (record )
532+
533+ @staticmethod
534+ def mapPriority (levelno ):
535+ """Map logging levels to journald priorities.
536+
537+ Since Python log level numbers are "sparse", we have to map
538+ numbers in between the standard levels too.
539+ """
540+ if levelno <= _logging .DEBUG :
541+ return LOG_DEBUG
542+ elif levelno <= _logging .INFO :
543+ return LOG_INFO
544+ elif levelno <= _logging .WARNING :
545+ return LOG_WARNING
546+ elif levelno <= _logging .ERROR :
547+ return LOG_ERR
548+ elif levelno <= _logging .CRITICAL :
549+ return LOG_CRIT
550+ else :
551+ return LOG_ALERT
0 commit comments