Skip to content

Commit d4699ce

Browse files
committed
Log to both stdout and file in k8s cluster
1 parent 83fd410 commit d4699ce

1 file changed

Lines changed: 14 additions & 2 deletions

File tree

src/config.py

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import os, json, logging
1+
import os, json, logging, sys
22
from dotenv import load_dotenv
33
from urllib import parse
44
load_dotenv()
@@ -32,6 +32,18 @@ def __init__(self, environment="Development"):
3232
The level parameter now accepts a string representation of the level such as ‘INFO’ as an alternative to the integer constants such as INFO.
3333
"""
3434
logging.getLogger("httpx").setLevel(logging.WARNING)
35-
logging.basicConfig(filename='/var/log/pythonrestapi/log', filemode='w', format='%(asctime)s %(levelname)-8s %(message)s', level=self.LOGLEVEL, datefmt='%Y-%m-%d %H:%M:%S')
35+
"""
36+
https://realpython.com/python-modulo-string-formatting/#fine-tune-your-output-with-conversion-flags
37+
- Justification of values that are shorter than the specified field width
38+
The Hyphen-Minus Flag (-)
39+
When a formatted value is shorter than the specified field width, it’s usually right-justified in the field. The hyphen-minus (-) flag causes the value to be left-justified in the specified field instead.
40+
"""
41+
if config["ENVIRONMENT"] == "production":
42+
logging.basicConfig(handlers=[
43+
logging.FileHandler(filename='/var/log/pythonrestapi/log', mode='w'),
44+
logging.StreamHandler(sys.stdout)
45+
], format='%(asctime)s %(levelname)-8s %(message)s', level=self.LOGLEVEL, datefmt='%Y-%m-%d %H:%M:%S')
46+
else:
47+
logging.basicConfig(filename='/var/log/pythonrestapi/log', filemode='w', format='%(asctime)s %(levelname)-8s %(message)s', level=self.LOGLEVEL, datefmt='%Y-%m-%d %H:%M:%S')
3648

3749
config = Config()

0 commit comments

Comments
 (0)