Debian Codegraph @

daiquiri/handlers.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2 # Licensed under the Apache License, Version 2.0 (the "License"); you may
3 # not use this file except in compliance with the License. You may obtain
4 # a copy of the License at
5 #
6 # http://www.apache.org/licenses/LICENSE-2.0
7 #
8 # Unless required by applicable law or agreed to in writing, software
9 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
10 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
11 # License for the specific language governing permissions and limitations
12 # under the License.
13
14 import logging
15 import logging.config
16 import logging.handlers
17 import typing
18
19 try:
20 from systemd import journal
21 except ImportError:
22 journal = None
23
24
25 try:
26 import syslog
27 except ImportError:
28 syslog = None # type: ignore[assignment]
29
30
31 from daiquiri import types
32
33 # This is a copy of the numerical constants from syslog.h. The
34 # definition of these goes back at least 20 years, and is specifically
35 # 3 bits in a packed field, so these aren't likely to ever need
36 # changing.
37 SYSLOG_MAP = {
38 "CRITICAL": 2,
39 "ERROR": 3,
40 "WARNING": 4,
41 "WARN": 4,
42 "INFO": 6,
43 "DEBUG": 7,
44 }
45
46
47 class SyslogHandler(logging.Handler):
48 """Syslog based handler. Only available on UNIX-like platforms."""
49
50 def __init__(
51 self, program_name: str, facility: typing.Optional[int] = None
52 ) -> None:
53 # Default values always get evaluated, for which reason we avoid
54 # using 'syslog' directly, which may not be available.
55 facility = facility if facility is not None else syslog.LOG_USER
56 if not syslog:
57 raise RuntimeError("Syslog not available on this platform")
58 super(SyslogHandler, self).__init__()
59 syslog.openlog(program_name, 0, facility)
60
61 def emit(self, record: logging.LogRecord) -> None:
62 priority = SYSLOG_MAP.get(record.levelname, 7)
63 message = self.format(record)
64 syslog.syslog(priority, message)
65
66
67 class JournalHandler(logging.Handler):
68 """Journald based handler. Only available on platforms using systemd."""
69
70 program_name: str
71
72 def __init__(self, program_name: str) -> None:
73 if not journal:
74 raise RuntimeError("Systemd bindings do not exist")
75 super(JournalHandler, self).__init__()
76 self.program_name = program_name
77
78 def emit(self, record: logging.LogRecord) -> None:
79 priority = SYSLOG_MAP.get(record.levelname, 7)
80 message = self.format(record)
81
82 extras = {
83 "CODE_FILE": record.pathname,
84 "CODE_LINE": record.lineno,
85 "CODE_FUNC": record.funcName,
86 "THREAD_NAME": record.threadName,
87 "PROCESS_NAME": record.processName,
88 "LOGGER_NAME": record.name,
89 "LOGGER_LEVEL": record.levelname,
90 "SYSLOG_IDENTIFIER": self.program_name,
91 "PRIORITY": priority,
92 }
93
94 if record.exc_text:
95 extras["EXCEPTION_TEXT"] = record.exc_text
96
97 if record.exc_info:
98 extras["EXCEPTION_INFO"] = record.exc_info
99
100 if hasattr(record, "_daiquiri_extra_keys"):
101 record = typing.cast(types.ExtrasLogRecord, record)
102 for k in record._daiquiri_extra_keys:
103 if k != "_daiquiri_extra_keys":
104 extras[k.upper()] = getattr(record, k)
105
106 journal.send(message, **extras)
107
108
109 if typing.TYPE_CHECKING:
110 _TTYDetectorStreamHandlerBase = logging.StreamHandler[typing.Any]
111 else:
112 _TTYDetectorStreamHandlerBase = logging.StreamHandler
113
114
115 class TTYDetectorStreamHandler(_TTYDetectorStreamHandlerBase):
116 """Stream handler that adds a hint in the record if the stream is a TTY."""
117
118 def format(self, record: logging.LogRecord) -> str:
119 record = typing.cast(types.TTYDetectionLogRecord, record)
120 if hasattr(self.stream, "isatty"):
121 try:
122 record._stream_is_a_tty = self.stream.isatty()
123 except ValueError:
124 # Stream has been closed, usually during interpretor shutdown
125 record._stream_is_a_tty = False
126 else:
127 record._stream_is_a_tty = False
128 s = super(TTYDetectorStreamHandler, self).format(record)
129 del record._stream_is_a_tty
130 return s
131
132
133 class PlainTextSocketHandler(logging.handlers.SocketHandler):
134 """Socket handler that uses format and encode the record."""
135
136 def __init__(self, hostname: str, port: int, encoding: str = "utf-8") -> None:
137 self.encoding = encoding
138 super(PlainTextSocketHandler, self).__init__(hostname, port)
139
140 def makePickle(self, record: logging.LogRecord) -> bytes:
141 return self.format(record).encode(self.encoding) + b"\n"
142
143
144 class PlainTextDatagramHandler(logging.handlers.DatagramHandler):
145 """Socket handler that uses format and encode the record."""
146
147 def __init__(self, hostname: str, port: int, encoding: str = "utf-8") -> None:
148 self.encoding = encoding
149 super(PlainTextDatagramHandler, self).__init__(hostname, port)
150
151 def makePickle(self, record: logging.LogRecord) -> bytes:
152 return self.format(record).encode(self.encoding) + b"\n"