Skip to content

Commit

Permalink
Use logging config from kuksa-python-sdk
Browse files Browse the repository at this point in the history
Will require an updated kuksa-client to work
  • Loading branch information
erikbosch committed May 14, 2024
1 parent 973fe30 commit 98e2c9e
Show file tree
Hide file tree
Showing 5 changed files with 9 additions and 98 deletions.
4 changes: 1 addition & 3 deletions config/dbc_feeder.ini
Original file line number Diff line number Diff line change
Expand Up @@ -53,9 +53,7 @@ tls = False
# token=../kuksa-databroker/jwt/provide-all.token
# The example below works if you have cloned kuksa-common in parallel to kuksa-can-provider
# token=../kuksa-common/jwt/provide-all.token
# For KUKSA.val Server the default behavior is to use the token provided as part of kuksa-client
# So you only need to specify a different token if you want to use a different token
# Possibly like below
# For KUKSA.val Server you can specify token like below
# token=../kuksa.val/kuksa_certificates/jwt/super-admin.json.token

# Definitions on what directions to support.
Expand Down
95 changes: 4 additions & 91 deletions dbcfeeder.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,8 @@
from dbcfeederlib import clientwrapper
from dbcfeederlib import elm2canbridge

from kuksa_client.kuksa_logger import KuksaLogger # type: ignore

log = logging.getLogger("dbcfeeder")

CONFIG_SECTION_CAN = "can"
Expand All @@ -74,51 +76,6 @@ class ServerType(str, enum.Enum):
KUKSA_DATABROKER = 'kuksa_databroker'


def init_logging(loglevel):
"""Set up console logger"""
# create console handler and set level to debug. This just means that it can show DEBUG messages.
# What actually is shown is controlled by logging configuration
console_logger = logging.StreamHandler()
console_logger.setLevel(logging.DEBUG)

# create formatter
if sys.stdout.isatty():
formatter = ColorFormatter()
else:
formatter = logging.Formatter(
fmt="%(asctime)s %(levelname)s %(name)s: %(message)s"
)

# add formatter to console_logger
console_logger.setFormatter(formatter)

# add console_logger as a global handler
root_logger = logging.getLogger()
root_logger.setLevel(loglevel)
root_logger.addHandler(console_logger)


class ColorFormatter(logging.Formatter):
"""Color formatter that can be used for terminals"""
FORMAT = "{time} {{loglevel}} {logger} {msg}".format(
time="\x1b[2m%(asctime)s\x1b[0m", # grey
logger="\x1b[2m%(name)s:\x1b[0m", # grey
msg="%(message)s",
)
FORMATS = {
logging.DEBUG: FORMAT.format(loglevel="\x1b[34mDEBUG\x1b[0m"), # blue
logging.INFO: FORMAT.format(loglevel="\x1b[32mINFO\x1b[0m"), # green
logging.WARNING: FORMAT.format(loglevel="\x1b[33mWARNING\x1b[0m"), # yellow
logging.ERROR: FORMAT.format(loglevel="\x1b[31mERROR\x1b[0m"), # red
logging.CRITICAL: FORMAT.format(loglevel="\x1b[31mCRITICAL\x1b[0m"), # red
}

def format(self, record):
log_fmt = self.FORMATS.get(record.levelno)
formatter = logging.Formatter(log_fmt)
return formatter.format(record)


class Feeder:
"""
The feeder is responsible for setting up a queue.
Expand Down Expand Up @@ -646,43 +603,6 @@ def signal_handler(signal_received, *_):
return 0


def parse_env_log(env_log, default=logging.INFO):
def parse_level(specified_level, default=default):
if isinstance(specified_level, str):
if specified_level.lower() in [
"debug",
"info",
"warn",
"warning",
"error",
"critical",
]:
return specified_level.upper()
raise ValueError(f"could not parse '{specified_level}' as a log level")
return default

parsed_loglevels = {}

if env_log is not None:
log_specs = env_log.split(",")
for log_spec in log_specs:
spec_parts = log_spec.split("=")
if len(spec_parts) == 1:
# This is a root level spec
if "root" in parsed_loglevels:
raise ValueError("multiple root loglevels specified")
parsed_loglevels["root"] = parse_level(spec_parts[0])
if len(spec_parts) == 2:
logger_name = spec_parts[0]
logger_level = spec_parts[1]
parsed_loglevels[logger_name] = parse_level(logger_level)

if "root" not in parsed_loglevels:
parsed_loglevels["root"] = default

return parsed_loglevels


if __name__ == "__main__":
# Example
#
Expand All @@ -698,17 +618,10 @@ def parse_level(specified_level, default=default):
# kuksa_client (If you want to get additional information from kuksa-client python library)
#

loglevels = parse_env_log(os.environ.get("LOG_LEVEL"))

# set root loglevel etc
init_logging(loglevels["root"])
kuksa_logger = KuksaLogger()
kuksa_logger.init_logging()

# helper for debugging in vs code from project root
# os.chdir(os.path.dirname(__file__))

# set loglevels for other loggers
for logger, level in loglevels.items():
if logger != "root":
logging.getLogger(logger).setLevel(level)

sys.exit(main(sys.argv))
2 changes: 1 addition & 1 deletion dbcfeederlib/serverclientwrapper.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ def start(self):

self._kuksa = KuksaClientThread(self._client_config)
self._kuksa.start()
self._kuksa.authorize()
self._kuksa.authorize(token_or_tokenfile=self._token_path)

def is_connected(self) -> bool:
# This one is quite unreliable, see https://github.com/eclipse/kuksa.val/issues/523
Expand Down
2 changes: 1 addition & 1 deletion requirements.in
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ cantools ~= 38.0
pyyaml ~= 6.0
can-j1939 ~= 2.0
py_expression_eval ~= 0.3
kuksa-client ~= 0.4.2
kuksa-client ~= 0.4.3
types-PyYAML ~= 6.0
types-protobuf ~= 4.21

Expand Down
4 changes: 2 additions & 2 deletions requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ iniconfig==2.0.0
# via pytest
jsonpath-ng==1.6.1
# via kuksa-client
kuksa-client==0.4.2
kuksa-client==0.4.3
# via -r requirements.in
msgpack==1.0.8
# via python-can
Expand All @@ -50,7 +50,7 @@ protobuf==5.26.1
# via grpcio-tools
py-expression-eval==0.3.14
# via -r requirements.in
pygments==2.17.2
pygments==2.18.0
# via kuksa-client
pyperclip==1.8.2
# via cmd2
Expand Down

0 comments on commit 98e2c9e

Please sign in to comment.