Skip to content

Commit d9c1cff

Browse files
authored
fix: use the log timestamp when ingesting to loki (#15)
1 parent 6942818 commit d9c1cff

File tree

2 files changed

+9
-6
lines changed

2 files changed

+9
-6
lines changed

logging_loki/emitter.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,8 @@ def __init__(self,
4646
props_to_labels: Optional[list[str]] = None,
4747
level_tag: Optional[str] = const.level_tag,
4848
logger_tag: Optional[str] = const.logger_tag,
49-
verify: Union[bool, str] = True
49+
verify: Union[bool, str] = True,
50+
replace_timestamp: Optional[bool] = False,
5051
):
5152
"""
5253
Create new Loki emitter.
@@ -75,6 +76,8 @@ def __init__(self,
7576
self.logger_tag: str = logger_tag
7677
# verify param to be past to requests, can be a bool (to enable/disable SSL verification) or a path to a CA bundle
7778
self.verify = verify
79+
# Flag to control if the log timestamp should be replaced with the current time
80+
self.replace_timestamp = replace_timestamp
7881

7982
self._session: Optional[requests.Session] = None
8083
self._lock = threading.Lock()
@@ -147,8 +150,7 @@ def build_tags(self, record: logging.LogRecord, line: str) -> Dict[str, Any]:
147150
def build_payload(self, record: logging.LogRecord, line: str) -> dict:
148151
"""Build JSON payload with a log entry."""
149152
labels = self.build_tags(record, line)
150-
ns = 1e9
151-
ts = str(int(time.time() * ns))
153+
ts = str(time.time_ns()) if self.replace_timestamp else str(int(record.created * 1e9))
152154

153155
line = json.dumps(record, default=lambda obj: obj.__dict__) if self.as_json else line
154156

logging_loki/handlers.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -71,7 +71,8 @@ def __init__(
7171
props_to_labels: Optional[list[str]] = None,
7272
level_tag: Optional[str] = const.level_tag,
7373
logger_tag: Optional[str] = const.logger_tag,
74-
verify: Union[bool, str] = True
74+
verify: Union[bool, str] = True,
75+
replace_timestamp: Optional[bool] = False,
7576
):
7677
"""
7778
Create new Loki logging handler.
@@ -86,10 +87,10 @@ def __init__(
8687
level_tag: Label name indicating logging level.
8788
logger_tag: Label name indicating logger name.
8889
verify: Either a boolean, in which case it controls whether we verify the server's TLS certificate, or a string, in which case it must be a path to a CA bundle to use.
89-
90+
replace_timestamp: If enabled, the timestamp in the log line will be replaced with `time.time_ns()`. Be careful when using this option with `batching` enabled, as the logs will be sent in batches, and the timestamp will be the time of the batch, not the time of the log.
9091
"""
9192
super().__init__()
92-
self.emitter = LokiEmitter(url, tags, headers, auth, as_json, props_to_labels, level_tag, logger_tag, verify)
93+
self.emitter = LokiEmitter(url, tags, headers, auth, as_json, props_to_labels, level_tag, logger_tag, verify, replace_timestamp=replace_timestamp)
9394

9495
def handleError(self, exc: Exception): # noqa: N802
9596
"""Close emitter and let default handler take actions on error."""

0 commit comments

Comments
 (0)