logger.py 989 Bytes
Newer Older
Izalia Mae's avatar
Izalia Mae committed
1
2
3
import logging
import os

Izalia Mae's avatar
Izalia Mae committed
4
5
from pathlib import Path

Izalia Mae's avatar
Izalia Mae committed
6
7
8
9
10
11
12
13
14
15
16
17
18

## Add the verbose logging level
def verbose(message, *args, **kwargs):
	if not logging.root.isEnabledFor(logging.VERBOSE):
		return

	logging.log(logging.VERBOSE, message, *args, **kwargs)

setattr(logging, 'verbose', verbose)
setattr(logging, 'VERBOSE', 15)
logging.addLevelName(15, 'VERBOSE')


Izalia Mae's avatar
Izalia Mae committed
19
## Get log level and file from environment if possible
Izalia Mae's avatar
Izalia Mae committed
20
21
env_log_level = os.environ.get('LOG_LEVEL', 'INFO').upper()

Izalia Mae's avatar
Izalia Mae committed
22
23
24
25
26
27
try:
	env_log_file = Path(os.environ.get('LOG_FILE')).expanduser().resolve()

except TypeError:
	env_log_file = None

Izalia Mae's avatar
Izalia Mae committed
28
29
30
31
32
33
34
35
36
37

## Make sure the level from the environment is valid
try:
	log_level = getattr(logging, env_log_level)

except AttributeError:
	log_level = logging.INFO


## Set logging config
Izalia Mae's avatar
Izalia Mae committed
38
39
40
41
42
handlers = [logging.StreamHandler()]

if env_log_file:
	handlers.append(logging.FileHandler(env_log_file))

Izalia Mae's avatar
Izalia Mae committed
43
44
45
logging.basicConfig(
	level = log_level,
	format = "[%(asctime)s] %(levelname)s: %(message)s",
Izalia Mae's avatar
Izalia Mae committed
46
	handlers = handlers
Izalia Mae's avatar
Izalia Mae committed
47
)