Completed
Pull Request — master (#963)
by
unknown
01:02
created

glances_logger()   B

Complexity

Conditions 4

Size

Total Lines 27

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
dl 0
loc 27
rs 8.5806
c 1
b 0
f 0
1
# -*- coding: utf-8 -*-
2
#
3
# This file is part of Glances.
4
#
5
# Copyright (C) 2015 Nicolargo <[email protected]>
6
#
7
# Glances is free software; you can redistribute it and/or modify
8
# it under the terms of the GNU Lesser General Public License as published by
9
# the Free Software Foundation, either version 3 of the License, or
10
# (at your option) any later version.
11
#
12
# Glances is distributed in the hope that it will be useful,
13
# but WITHOUT ANY WARRANTY; without even the implied warranty of
14
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15
# GNU Lesser General Public License for more details.
16
#
17
# You should have received a copy of the GNU Lesser General Public License
18
# along with this program. If not, see <http://www.gnu.org/licenses/>.
19
20
"""Custom logger class."""
21
22
import logging
23
import os
24
import tempfile
25
import json
26
from logging.config import dictConfig
27
28
# Define the logging configuration
29
LOGGING_CFG = {
30
    "version": 1,
31
    "disable_existing_loggers": "False",
32
    "root": {
33
        "level": "INFO",
34
        "handlers": ["file", "console"]
35
    },
36
    "formatters": {
37
        "standard": {
38
            "format": "%(asctime)s -- %(levelname)s -- %(message)s"
39
        },
40
        "short": {
41
            "format": "%(levelname)s: %(message)s"
42
        },
43
        "free": {
44
            "format": "%(message)s"
45
        }
46
    },
47
    "handlers": {
48
        "file": {
49
            "level": "DEBUG",
50
            "class": "logging.handlers.RotatingFileHandler",
51
            "formatter": "standard",
52
            'filename': os.path.join(tempfile.gettempdir(), 'glances.log')
53
        },
54
        "console": {
55
            "level": "CRITICAL",
56
            "class": "logging.StreamHandler",
57
            "formatter": "free"
58
        }
59
    },
60
    "loggers": {
61
        "debug": {
62
            "handlers": ["file", "console"],
63
            "level": "DEBUG"
64
        },
65
        "verbose": {
66
            "handlers": ["file", "console"],
67
            "level": "INFO"
68
        },
69
        "standard": {
70
            "handlers": ["file"],
71
            "level": "INFO"
72
        },
73
        "requests": {
74
            "handlers": ["file", "console"],
75
            "level": "ERROR"
76
        },
77
        "elasticsearch": {
78
            "handlers": ["file", "console"],
79
            "level": "ERROR"
80
        },
81
        "elasticsearch.trace": {
82
            "handlers": ["file", "console"],
83
            "level": "ERROR"
84
        }
85
    }
86
}
87
88
89
def tempfile_name():
90
    """Return the tempfile name (full path)."""
91
    ret = os.path.join(tempfile.gettempdir(), 'glances.log')
92
    if os.access(ret, os.F_OK) and not os.access(ret, os.W_OK):
93
        print("WARNING: Couldn't write to log file {} (Permission denied)".format(ret))
94
        ret = tempfile.mkstemp(prefix='glances', suffix='.log', text=True)
95
        print("Create a new log file: {}".format(ret[1]))
96
        return ret[1]
97
98
    return ret
99
100
101
def glances_logger(env_key='LOG_CFG'):
102
    """Build and return the logger.
103
104
    env_key define the env var where a path to a specific JSON logger
105
            could be defined
106
107
    :return: logger -- Logger instance
108
    """
109
    _logger = logging.getLogger()
110
111
    # Overwrite the default logger file
112
    LOGGING_CFG['handlers']['file']['filename'] = tempfile_name()
113
114
    # By default, use the LOGGING_CFG lgger configuration
115
    config = LOGGING_CFG
116
117
    # Check if a specific configuration is available
118
    user_file = os.getenv(env_key, None)
119
    if user_file and os.path.exists(user_file):
120
        # A user file as been defined. Use it...
121
        with open(user_file, 'rt') as f:
122
            config = json.load(f)
123
124
    # Load the configuration
125
    dictConfig(config)
126
127
    return _logger
128
129
logger = glances_logger()
130