Skip to content

Commit

Permalink
log_context per log to prevent bugs with threading
Browse files Browse the repository at this point in the history
  • Loading branch information
mdmatthias committed May 8, 2024
1 parent 05e1a14 commit 16db23f
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 19 deletions.
35 changes: 17 additions & 18 deletions logging_loki/loki_context_logger.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,32 +5,31 @@
class LokiContextLogger:
def __init__(self, logger: LokiLogger):
self.logger = logger
self.log_context = LogContext()

def _log(self, level, message, code=None, exc_info=None):
self.log_context.set_message(message)
def _log(self, level, message, code=None, log_context: LogContext | None = LogContext(), exc_info=None):
log_context.set_message(message)
tags = {"message_code": code}
tags.update(self.log_context.get_tags())
tags.update(log_context.get_tags())
log_func = getattr(self.logger, level)
if level == "exception":
log_func(self.log_context.to_string(), tags, exc_info=exc_info)
log_func(log_context.to_string(), tags, exc_info=exc_info)
else:
log_func(self.log_context.to_string(), tags)
log_func(log_context.to_string(), tags)

def debug(self, message, code=None):
self._log('debug', message, code)
def debug(self, message, code=None, log_context=None):
self._log('debug', message, code, log_context)

def info(self, message, code=None):
self._log('info', message, code)
def info(self, message, code=None, log_context=None):
self._log('info', message, code, log_context)

def warning(self, message, code=None):
self._log('warning', message, code)
def warning(self, message, code=None, log_context=None):
self._log('warning', message, code, log_context)

def error(self, message, code=None):
self._log('error', message, code)
def error(self, message, code=None, log_context=None):
self._log('error', message, code, log_context)

def critical(self, message, code=None):
self._log('critical', message, code)
def critical(self, message, code=None, log_context=None):
self._log('critical', message, code, log_context)

def exception(self, message, exc_info=None, code=None):
self._log('exception', message, code, exc_info)
def exception(self, message, exc_info=None, code=None, log_context=None):
self._log('exception', message, code, log_context, exc_info)
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ build-backend = "setuptools.build_meta"

[project]
name = "inuits-python-logging-loki"
version = "1.2.1"
version = "1.3.0"
description = "Python logging handler for Grafana Loki."
readme = "README.md"
authors = [{ name = "Inuits", email = "[email protected]" }, {name="Andrey Maslov", email="[email protected]"}]
Expand Down

0 comments on commit 16db23f

Please sign in to comment.