-
Notifications
You must be signed in to change notification settings - Fork 7
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: Syslog handler and formatter for the metricq_command
- Loading branch information
Showing
2 changed files
with
65 additions
and
5 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,30 @@ | ||
import logging | ||
import socket | ||
import time | ||
from logging.handlers import SysLogHandler | ||
|
||
|
||
class SyslogFormatter(logging.Formatter): | ||
def __init__(self, *args, name: str = "metricq", **kwargs): # type: ignore | ||
super().__init__(*args, **kwargs) | ||
self.program = name | ||
|
||
def format(self, record: logging.LogRecord) -> str: | ||
timestamp = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(record.created)) | ||
hostname = socket.gethostname() | ||
pid = record.process | ||
program = self.program | ||
# Custom Formatter based on rfc3164 | ||
# Format the header as "<PRI> TIMESTAMP HOSTNAME PROGRAM[PID]: MESSAGE" | ||
# <PRI> is already beeing set by the SysLogHanlder, we only need to add the rest | ||
syslog_header = f"{timestamp} {hostname} {program}[{pid}]: " | ||
message = super().format(record) | ||
return syslog_header + message | ||
|
||
|
||
def get_syslog_handler(address: str) -> SysLogHandler: | ||
if ":" in address: | ||
ip, port = address.split(":") | ||
return SysLogHandler(address=(ip, int(port))) | ||
else: | ||
return SysLogHandler(address=address) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters