syslog.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. # this cffi version was rewritten based on the
  2. # ctypes implementation: Victor Stinner, 2008-05-08
  3. """
  4. This module provides an interface to the Unix syslog library routines.
  5. Refer to the Unix manual pages for a detailed description of the
  6. syslog facility.
  7. """
  8. import sys
  9. if sys.platform == 'win32':
  10. raise ImportError("No syslog on Windows")
  11. try: from __pypy__ import builtinify
  12. except ImportError: builtinify = lambda f: f
  13. from _syslog_cffi import ffi, lib
  14. _S_log_open = False
  15. _S_ident_o = None
  16. def _get_argv():
  17. try:
  18. import sys
  19. script = sys.argv[0]
  20. if isinstance(script, str):
  21. return script[script.rfind('/')+1:] or None
  22. except Exception:
  23. pass
  24. return None
  25. @builtinify
  26. def openlog(ident=None, logoption=0, facility=lib.LOG_USER):
  27. global _S_ident_o, _S_log_open
  28. if ident is None:
  29. ident = _get_argv()
  30. if ident is None:
  31. _S_ident_o = ffi.NULL
  32. else:
  33. if not isinstance(ident, str):
  34. msg = "openlog() argument 1 must be a str, not {!r}"
  35. raise TypeError(msg.format(type(ident).__name__))
  36. ident = ident.encode(sys.getdefaultencoding())
  37. _S_ident_o = ffi.new("char[]", ident) # keepalive
  38. lib.openlog(_S_ident_o, logoption, facility)
  39. _S_log_open = True
  40. @builtinify
  41. def syslog(arg1, arg2=None):
  42. if arg2 is not None:
  43. priority, message = arg1, arg2
  44. else:
  45. priority, message = LOG_INFO, arg1
  46. # if log is not opened, open it now
  47. if not _S_log_open:
  48. openlog()
  49. if not isinstance(message, str):
  50. raise TypeError("syslog() message must be a str, not {!r}".format(
  51. type(message).__name__))
  52. message = message.encode(sys.getdefaultencoding())
  53. lib.syslog(priority, b"%s", message)
  54. @builtinify
  55. def closelog():
  56. global _S_log_open, S_ident_o
  57. if _S_log_open:
  58. lib.closelog()
  59. _S_log_open = False
  60. _S_ident_o = None
  61. @builtinify
  62. def setlogmask(mask):
  63. return lib.setlogmask(mask)
  64. @builtinify
  65. def LOG_MASK(pri):
  66. return (1 << pri)
  67. @builtinify
  68. def LOG_UPTO(pri):
  69. return (1 << (pri + 1)) - 1
  70. __all__ = []
  71. for name in dir(lib):
  72. if name.startswith('LOG_'):
  73. value = getattr(lib, name)
  74. if value != -919919:
  75. globals()[name] = value
  76. __all__.append(name)
  77. __all__ = tuple(__all__) + (
  78. 'openlog', 'syslog', 'closelog', 'setlogmask',
  79. 'LOG_MASK', 'LOG_UPTO')