'How to format a log record inside ```emit``` function instead of creating a formatter object?
I wrote a custom logging handler to send a log record to a http point.
class CustomHttpHandler(logging.Handler):
def __init__(self, url: str):
# url is the endpoint to send log
self.url = url
self.session = requests.Session()
def emit(self, record):
self.session.post(self.url, data=record)
import logging
from handler import CustomHttpHandler
logger = logging.getLogger(__name__)
formatter = logging.Formatter(json.dumps({
'time': '%(asctime)s',
message': '%(message)s'
}))
handler = CustomHandler("http://myurl")
logger.addHandler(chandler)
logger.setFormatter(formatter)
Is there any way that I can format a log record inside emit
function instead of creating formatter object and pass it with setFormatter
function?
Solution 1:[1]
I don't see a problem using setFormatter, you just need to use it in your emit
function like so
def emit(self, record):
print(self.format(record))
Also note that you can apply your formater only to this specific handler if you want:
handler.setFormatter(formatter)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | m.nachury |