Add log level configuration option

This commit is contained in:
Dmitrii Andreev
2024-01-07 17:14:14 +03:00
parent fa18939c3e
commit d2d487d1ed
2 changed files with 32 additions and 16 deletions

View File

@@ -16,6 +16,7 @@ DEFAULTS = {
'check_interval': 60,
'timeout_connect': 10,
'timeout_read': 30,
'log_level': 'info'
}
def parse_arguments():
@@ -29,6 +30,7 @@ def parse_arguments():
parser.add_argument('--check-interval', type=int, help='Interval to check the stream in seconds')
parser.add_argument('--timeout-connect', type=int, help='Timeout for connecting to the stream in seconds')
parser.add_argument('--timeout-read', type=int, help='Read timeout in seconds')
parser.add_argument('--log-level', help='Log level')
return vars(parser.parse_args())
def load_configuration():
@@ -43,7 +45,8 @@ def load_configuration():
'output_directory': cmd_args['output_directory'] or os.getenv('OUTPUT_DIRECTORY') or DEFAULTS['output_directory'],
'check_interval': cmd_args['check_interval'] or os.getenv('CHECK_INTERVAL') or DEFAULTS['check_interval'],
'timeout_connect': cmd_args['timeout_connect'] or os.getenv('TIMEOUT_CONNECT') or DEFAULTS['timeout_connect'],
'timeout_read': cmd_args['timeout_read'] or os.getenv('TIMEOUT_READ') or DEFAULTS['timeout_read']
'timeout_read': cmd_args['timeout_read'] or os.getenv('TIMEOUT_READ') or DEFAULTS['timeout_read'],
'log_level': cmd_args['log_level'] or os.getenv('LOG_LEVEL') or DEFAULTS['log_level']
}
# Converting string paths to absolute paths

View File

@@ -2,22 +2,35 @@
import json
import sys
from datetime import datetime
from config import load_configuration
# Log levels
DEBUG = "DEBUG"
INFO = "INFO"
WARNING = "WARNING"
ERROR = "ERROR"
FATAL = "FATAL"
LOG_LEVELS = {
"DEBUG": 10,
"INFO": 20,
"WARNING": 30,
"ERROR": 40,
"FATAL": 50
}
def log_event(event, details, level=INFO):
def log_event(event, details, level="INFO"):
"""Log an event to stdout in JSON format"""
log_entry = {
"timestamp": datetime.utcnow().isoformat(),
"event": event,
"level": level,
"details": details
}
json_log_entry = json.dumps(log_entry)
print(json_log_entry, file=sys.stdout)
sys.stdout.flush() # Immediately flush the log entry
config = load_configuration()
config_level_name = config.log_level.upper()
if config_level_name not in LOG_LEVELS:
raise ValueError(f"Invalid log level {config_level_name} in configuration")
config_level_number = LOG_LEVELS[config_level_name]
event_log_level = LOG_LEVELS.get(level.upper(), 20) # Defaults to INFO if level is invalid
if event_log_level >= config_level_number:
log_entry = {
"timestamp": datetime.utcnow().isoformat(),
"event": event,
"level": level.upper(),
"details": details
}
json_log_entry = json.dumps(log_entry)
print(json_log_entry, file=sys.stdout)
sys.stdout.flush() # Immediately flush the log entry