aria.ops.adapter_logging

 1#  Copyright 2023 VMware, Inc.
 2#  SPDX-License-Identifier: Apache-2.0
 3import logging
 4import os
 5from configparser import ConfigParser
 6from logging.handlers import RotatingFileHandler
 7from typing import Optional
 8
 9log_handler: Optional[RotatingFileHandler] = None
10
11
12def setup_logging(filename: str, file_count: int = 5, max_size: int = 0) -> None:
13    """
14    :param filename The name of the file to log to
15    :param file_count The total number of files to retain. Defaults to 5.
16    :param max_size The maximum size in bytes of each file before the file
17                    automatically rotates to a new one. Defaults to '0', which will
18                    do no automatic rotation. Requires calling the 'rotate()' function
19                    manually to ensure logs do not become too large.
20    """
21    try:
22        global log_handler
23        log_handler = RotatingFileHandler(
24            os.path.join(os.sep, "var", "log", filename),
25            maxBytes=max_size,
26            backupCount=file_count,
27        )
28        logging.basicConfig(
29            format="%(asctime)s,%(msecs)d %(name)s %(levelname)s %(message)s",
30            datefmt="%Y-%m-%d %H:%M:%S",
31            level=_get_default_log_level(),
32            handlers=[log_handler],
33        )
34        _set_log_levels()
35    except Exception:
36        logging.basicConfig(level=logging.CRITICAL + 1)
37
38
39def _get_default_log_level(default_level: int = logging.INFO) -> int:
40    default_level_name = logging.getLevelName(default_level)
41    log_config_file = os.path.join(os.sep, "var", "log", "loglevels.cfg")
42    config = ConfigParser()
43    if os.path.isfile(log_config_file):
44        config.read(log_config_file)
45    modified = False
46    if "adapter" not in config["DEFAULT"]:
47        modified = True
48        config["DEFAULT"].update({"adapter": default_level_name})
49    if "adapter" not in config:
50        modified = True
51        config["adapter"] = {
52            "__main__": default_level_name,
53        }
54    if modified:
55        with open(log_config_file, "w") as config_file:
56            config.write(config_file)
57    try:
58        return int(
59            logging.getLevelName(config["DEFAULT"].get("adapter", default_level_name))
60        )
61    except ValueError:
62        return default_level
63
64
65def _set_log_levels() -> None:
66    log_config_file = os.path.join(os.sep, "var", "log", "loglevels.cfg")
67    config = ConfigParser()
68    config.read(log_config_file)
69    for logger in config["adapter"]:
70        logging.getLogger(logger).setLevel(config["adapter"][logger])
71
72
73def getLogger(name: str) -> logging.Logger:
74    # convenience function to avoid having to import logging and adapter_logging
75    return logging.getLogger(name)
76
77
78def rotate() -> None:
79    """
80    Rotates the current adapter logs to their backups (e.g., `adapter.log` to
81    `adapter.log.1`) and starts logging to the new adapter.log file.
82    :return: None
83    """
84    if log_handler:
85        log_handler.doRollover()
def setup_logging(filename: str, file_count: int = 5, max_size: int = 0) -> None:
13def setup_logging(filename: str, file_count: int = 5, max_size: int = 0) -> None:
14    """
15    :param filename The name of the file to log to
16    :param file_count The total number of files to retain. Defaults to 5.
17    :param max_size The maximum size in bytes of each file before the file
18                    automatically rotates to a new one. Defaults to '0', which will
19                    do no automatic rotation. Requires calling the 'rotate()' function
20                    manually to ensure logs do not become too large.
21    """
22    try:
23        global log_handler
24        log_handler = RotatingFileHandler(
25            os.path.join(os.sep, "var", "log", filename),
26            maxBytes=max_size,
27            backupCount=file_count,
28        )
29        logging.basicConfig(
30            format="%(asctime)s,%(msecs)d %(name)s %(levelname)s %(message)s",
31            datefmt="%Y-%m-%d %H:%M:%S",
32            level=_get_default_log_level(),
33            handlers=[log_handler],
34        )
35        _set_log_levels()
36    except Exception:
37        logging.basicConfig(level=logging.CRITICAL + 1)

:param filename The name of the file to log to :param file_count The total number of files to retain. Defaults to 5. :param max_size The maximum size in bytes of each file before the file automatically rotates to a new one. Defaults to '0', which will do no automatic rotation. Requires calling the 'rotate()' function manually to ensure logs do not become too large.

def getLogger(name: str) -> logging.Logger:
74def getLogger(name: str) -> logging.Logger:
75    # convenience function to avoid having to import logging and adapter_logging
76    return logging.getLogger(name)
def rotate() -> None:
79def rotate() -> None:
80    """
81    Rotates the current adapter logs to their backups (e.g., `adapter.log` to
82    `adapter.log.1`) and starts logging to the new adapter.log file.
83    :return: None
84    """
85    if log_handler:
86        log_handler.doRollover()

Rotates the current adapter logs to their backups (e.g., adapter.log to adapter.log.1) and starts logging to the new adapter.log file.

Returns

None