#!/usr/bin/python3
#
# @@copyright (c) Copyright ESO 2019 All Rights Reserved
# ESO (eso.org) is an Intergovernmental Organisation, and therefore special legal conditions apply.
#
"""Sample application demonstrates loading of log configuration from json file"""
# pylint: disable=C0103

import sys
import os
import logging
import time
from elt.log import CiiLogManager, CiiLogMessageBuilder, CiiLogAudience

_LOG_FILE_NAME = "abc_778_def.log"

# Config file, must produce dict configuration schema (for logging) when parsed with json.
# Enables post mortem buffer ("cii_log_buffer" key) and defines logger "my-logger" with
# file handler and "cii" message format.
_CONFIG_FILE_CONTENT = """
{
    "version": 1,
    "cii_log_buffer": {
        "enabled": true,
        "ttl_ms": 60000
    },
    "handlers": {
        "my-file-handler": {
            "class": "logging.FileHandler",
            "formatter": "cii",
            "filename" : "%s"
        }
    },
    "loggers": {
        "my-logger": {
            "level": "INFO",
            "handlers": ["my-file-handler"]
         }
    }
}
""" % (_LOG_FILE_NAME,)

def _prepare_config_file(filename):
    """
    Prepare configuration file
    @param filename name of the file to write configuration to
    """
    with open(filename, 'w') as f:
        f.write(_CONFIG_FILE_CONTENT)

def raising_func():
    """
    Example method that does some logging then raises an exception
    """
    builder = CiiLogMessageBuilder().with_user_log_id('RAISING_FUNC_ID')
    logger = logging.getLogger("my-logger")
    logger.error(builder.with_message("This message appears on the console, logsink and log file").
                 build())
    # Just pass plain message (no additional fields)
    logger.debug("This message will also be dumped postmortem")
    raise RuntimeError("Lets See What Happens")

def main():
    """
    main function
    """
    log_config_filename = 'log_config.json'
    _prepare_config_file(log_config_filename)
    # Intialize logging from configuration file
    # This enables root logger with console and log sink file handler.
    # Default root logger level is ERROR
    # Additional loggers/handlers are defined in config file
    CiiLogManager.configure(log_config_filename)
    try:
        # Use CiiLogMessage builder to format additional fields
        builder = CiiLogMessageBuilder().with_user_log_id('MAIN_ID'). \
                  with_audience(CiiLogAudience.DEVELOPER)
        os.unlink(log_config_filename)
        # One can use logging API to obtain logger
        logger = logging.getLogger("my-logger")
        logger.info(builder.with_message("Message appears in the log file").build())
        logger.debug(builder.with_message("This message will be dumped postmortem").build())
        raising_func()
        return 0
    # pylint: disable=W0703
    except Exception as e:
        # Execute postmortem dump
        # Dump exception to the root logger
        logger.exception('EXCEPTION in main: %s --- EXECUTING POSTMORTEM DUMP', e)
        # Dump captured log records, that were previously ignored by the handlers
        print('WILL FLUSH POSTMORTEM BUFFER...LOG MESSAGES THAT FOLLOW WERE CAPTURED BEFORE')
        time.sleep(1)
        CiiLogManager.flush_postmortem_buffer()
        return 5

if __name__ == '__main__':
    sys.exit(main())
