1#!/usr/bin/env python3
2#
3# Copyright (c) 2021 Intel Corporation
4# Copyright (c) 2024 Nordic Semiconductor ASA
5#
6# SPDX-License-Identifier: Apache-2.0
7
8"""
9Parser library for Dictionary-based Logging
10
11This library along with dictionary_parser converts the
12input binary data to the log using log database.
13"""
14
15import logging
16
17import dictionary_parser
18from dictionary_parser.log_database import LogDatabase
19
20
21def get_log_parser(dbfile, logger):
22    """Get the log parser for the given database.
23
24    In addition to creating the parser, the function prints general information about the parser.
25    """
26    database = LogDatabase.read_json_database(dbfile)
27
28    if database is None:
29        logger.error("ERROR: Cannot open database file:  exiting...")
30        raise ValueError(f"Cannot open database file: {dbfile}")
31    log_parser = dictionary_parser.get_parser(database)
32
33    if log_parser is not None:
34        logger.debug("# Build ID: %s", database.get_build_id())
35        logger.debug("# Target: %s, %d-bit", database.get_arch(), database.get_tgt_bits())
36        if database.is_tgt_little_endian():
37            logger.debug("# Endianness: Little")
38        else:
39            logger.debug("# Endianness: Big")
40    else:
41        logger.error("ERROR: Cannot find a suitable parser matching database version!")
42        raise ValueError("Cannot create parser.")
43
44    return log_parser
45
46
47def parser(logdata, log_parser, logger):
48    """function of serial parser"""
49
50    if not isinstance(logger, logging.Logger):
51        raise ValueError("Invalid logger instance. Please configure the logger!")
52
53    if logdata is None:
54        logger.error("ERROR: cannot read log from file:  exiting...")
55        raise ValueError("Cannot read log data.")
56
57    ret = log_parser.parse_log_data(logdata)
58    return ret
59