Debian Codegraph @

daiquiri/output.py

raw symbols SCIP
1 # Licensed under the Apache License, Version 2.0 (the "License"); you may
2 # not use this file except in compliance with the License. You may obtain
3 # a copy of the License at
4 #
5 # http://www.apache.org/licenses/LICENSE-2.0
6 #
7 # Unless required by applicable law or agreed to in writing, software
8 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
9 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
10 # License for the specific language governing permissions and limitations
11 # under the License.
12 import datetime
13 import inspect
14 import logging
15 import logging.handlers
16 import os
17 import sys
18 import typing
19
20 try:
21 import syslog
22 except ImportError:
23 syslog = None # type: ignore[assignment]
24
25 from daiquiri import formatter
26 from daiquiri import handlers
27
28
29 def get_program_name() -> str:
30 """Return the name of the running program."""
31 return os.path.basename(inspect.stack()[-1][1])
32
33
34 class Output:
35 """Generic log output."""
36
37 def __init__(
38 self,
39 handler: logging.Handler,
40 formatter: logging.Formatter = formatter.TEXT_FORMATTER,
41 level: typing.Optional[int] = None,
42 ):
43 self.handler = handler
44 self.handler.setFormatter(formatter)
45 if level is not None:
46 self.handler.setLevel(level)
47
48 def add_to_logger(self, logger: logging.Logger) -> None:
49 """Add this output to a logger."""
50 logger.addHandler(self.handler)
51
52
53 def _get_log_file_path(
54 logfile: typing.Optional[str] = None,
55 logdir: typing.Optional[str] = None,
56 program_name: typing.Optional[str] = None,
57 logfile_suffix: str = ".log",
58 ) -> str:
59 ret_path = None
60
61 if not logdir:
62 ret_path = logfile
63
64 if not ret_path and logfile and logdir:
65 ret_path = os.path.join(logdir, logfile)
66
67 if not ret_path and logdir:
68 program_name = program_name or get_program_name()
69 ret_path = os.path.join(logdir, program_name) + logfile_suffix
70
71 if not ret_path:
72 raise ValueError("Unable to determine log file destination")
73
74 return ret_path
75
76
77 class File(Output):
78 """Ouput to a file."""
79
80 def __init__(
81 self,
82 filename: typing.Optional[str] = None,
83 directory: typing.Optional[str] = None,
84 suffix: str = ".log",
85 program_name: typing.Optional[str] = None,
86 formatter: logging.Formatter = formatter.TEXT_FORMATTER,
87 level: typing.Optional[int] = None,
88 ):
89 """Log file output.
90
91 :param filename: The log file path to write to. If directory is also
92 specified, both will be combined.
93
94 :param directory: The log directory to write to. If no filename is
95 specified, the program name and suffix will be used
96 to contruct the full path relative to the directory.
97
98 :param suffix: The log file name suffix. This will be only used if no
99 filename has been provided.
100
101 :param program_name: Program name. Autodetected by default.
102
103 """
104 logpath = _get_log_file_path(filename, directory, program_name, suffix)
105 handler = logging.handlers.WatchedFileHandler(logpath)
106 super(File, self).__init__(handler, formatter, level)
107
108
109 class RotatingFile(Output):
110 """Output to a file, rotating after a certain size."""
111
112 handler: logging.handlers.RotatingFileHandler
113
114 def __init__(
115 self,
116 filename: typing.Optional[str] = None,
117 directory: typing.Optional[str] = None,
118 suffix: str = ".log",
119 program_name: typing.Optional[str] = None,
120 formatter: logging.Formatter = formatter.TEXT_FORMATTER,
121 level: typing.Optional[int] = None,
122 max_size_bytes: int = 0,
123 backup_count: int = 0,
124 ):
125 """Rotating log file output.
126
127 :param filename: The log file path to write to. If directory is also
128 specified, both will be combined.
129
130 :param directory: The log directory to write to. If no filename is
131 specified, the program name and suffix will be used
132 to contruct the full path relative to the directory.
133
134 :param suffix: The log file name suffix. This will be only used if no
135 filename has been provided.
136
137 :param program_name: Program name. Autodetected by default.
138
139 :param max_size_bytes: Allow the file to rollover at a predetermined
140 size.
141
142 :param backup_count: The maximum number of files to rotate logging
143 output between.
144
145 """
146 logpath = _get_log_file_path(filename, directory, program_name, suffix)
147 handler = logging.handlers.RotatingFileHandler(
148 logpath, maxBytes=max_size_bytes, backupCount=backup_count
149 )
150 super(RotatingFile, self).__init__(handler, formatter, level)
151
152 def do_rollover(self) -> None:
153 """Manually forces a log file rotation."""
154 return self.handler.doRollover()
155
156
157 class TimedRotatingFile(Output):
158 """Rotating log file output, triggered by a fixed interval."""
159
160 handler: logging.handlers.TimedRotatingFileHandler
161
162 def __init__(
163 self,
164 filename: typing.Optional[str] = None,
165 directory: typing.Optional[str] = None,
166 suffix: str = ".log",
167 program_name: typing.Optional[str] = None,
168 formatter: logging.Formatter = formatter.TEXT_FORMATTER,
169 level: typing.Optional[int] = None,
170 interval: typing.Union[float, int, datetime.timedelta] = datetime.timedelta(
171 hours=24
172 ),
173 backup_count: int = 0,
174 ):
175 """Rotating log file output, triggered by a fixed interval.
176
177 :param filename: The log file path to write to. If directory is also
178 specified, both will be combined.
179
180 :param directory: The log directory to write to. If no filename is
181 specified, the program name and suffix will be used
182 to contruct the full path relative to the directory.
183
184 :param suffix: The log file name suffix. This will be only used if no
185 filename has been provided.
186
187 :param program_name: Program name. Autodetected by default.
188
189 :param interval: datetime.timedelta instance representing how often a
190 new log file should be created.
191
192 :param backup_count: The maximum number of files to rotate logging
193 output between.
194 """
195 logpath = _get_log_file_path(filename, directory, program_name, suffix)
196 handler = logging.handlers.TimedRotatingFileHandler(
197 logpath,
198 when="S",
199 interval=int(self._timedelta_to_seconds(interval)),
200 backupCount=backup_count,
201 )
202 super(TimedRotatingFile, self).__init__(handler, formatter, level)
203
204 def do_rollover(self) -> None:
205 """Manually forces a log file rotation."""
206 return self.handler.doRollover()
207
208 @staticmethod
209 def _timedelta_to_seconds(
210 td: typing.Union[float, int, datetime.timedelta],
211 ) -> float:
212 """Convert a datetime.timedelta object into a seconds interval.
213
214 :param td: datetime.timedelta
215 :return: time in seconds
216 :rtype: int
217 """
218 if isinstance(td, (int, float)):
219 td = datetime.timedelta(seconds=td)
220 return td.total_seconds()
221
222
223 class Stream(Output):
224 """Generic stream output."""
225
226 def __init__(
227 self,
228 stream: typing.TextIO = sys.stderr,
229 formatter: logging.Formatter = formatter.TEXT_FORMATTER,
230 level: typing.Optional[int] = None,
231 ) -> None:
232 super(Stream, self).__init__(
233 handlers.TTYDetectorStreamHandler(stream), formatter, level
234 )
235
236
237 STDERR = Stream()
238 STDOUT = Stream(sys.stdout)
239
240
241 class Journal(Output):
242 def __init__(
243 self,
244 program_name: typing.Optional[str] = None,
245 formatter: logging.Formatter = formatter.TEXT_FORMATTER,
246 level: typing.Optional[int] = None,
247 ) -> None:
248 program_name = program_name or get_program_name()
249 super(Journal, self).__init__(
250 handlers.JournalHandler(program_name), formatter, level
251 )
252
253
254 class Syslog(Output):
255 def __init__(
256 self,
257 program_name: typing.Optional[str] = None,
258 facility: str = "user",
259 formatter: logging.Formatter = formatter.TEXT_FORMATTER,
260 level: typing.Optional[int] = None,
261 ) -> None:
262 if syslog is None:
263 # FIXME(jd) raise something more specific
264 raise RuntimeError("syslog is not available on this platform")
265 super(Syslog, self).__init__(
266 handlers.SyslogHandler(
267 program_name=program_name or get_program_name(),
268 facility=self._find_facility(facility),
269 ),
270 formatter,
271 level,
272 )
273
274 @staticmethod
275 def _find_facility(facility: str) -> int:
276 # NOTE(jd): Check the validity of facilities at run time as they differ
277 # depending on the OS and Python version being used.
278 valid_facilities = [
279 f
280 for f in [
281 "LOG_KERN",
282 "LOG_USER",
283 "LOG_MAIL",
284 "LOG_DAEMON",
285 "LOG_AUTH",
286 "LOG_SYSLOG",
287 "LOG_LPR",
288 "LOG_NEWS",
289 "LOG_UUCP",
290 "LOG_CRON",
291 "LOG_AUTHPRIV",
292 "LOG_FTP",
293 "LOG_LOCAL0",
294 "LOG_LOCAL1",
295 "LOG_LOCAL2",
296 "LOG_LOCAL3",
297 "LOG_LOCAL4",
298 "LOG_LOCAL5",
299 "LOG_LOCAL6",
300 "LOG_LOCAL7",
301 ]
302 if getattr(syslog, f, None)
303 ]
304
305 facility = facility.upper()
306
307 if not facility.startswith("LOG_"):
308 facility = "LOG_" + facility
309
310 if facility not in valid_facilities:
311 raise TypeError(
312 "syslog facility must be one of: %s"
313 % ", ".join("'%s'" % fac for fac in valid_facilities)
314 )
315
316 return int(getattr(syslog, facility))
317
318
319 class Datadog(Output):
320 def __init__(
321 self,
322 hostname: str = "127.0.0.1",
323 port: int = 10518,
324 formatter: logging.Formatter = formatter.DATADOG_FORMATTER,
325 level: typing.Optional[int] = None,
326 handler_class: typing.Type[
327 logging.handlers.SocketHandler
328 ] = handlers.PlainTextSocketHandler,
329 ):
330 super(Datadog, self).__init__(
331 handler_class(hostname, port),
332 formatter=formatter,
333 level=level,
334 )
335
336
337 # FIXME(jd): Is this useful? Remove it?
338 preconfigured: typing.Dict[str, typing.Union[Stream, Output]] = {
339 "stderr": STDERR,
340 "stdout": STDOUT,
341 }
342
343 if syslog is not None:
344 preconfigured["syslog"] = Syslog()
345
346 if handlers.journal is not None: # type: ignore[attr-defined]
347 preconfigured["journal"] = Journal()