-2

I'm trying to create a logging package for my python scripts, allowing me to log my errors on an ELK server. The problem is that I can't create an instance of my Logging class to get all my logs present in the scripts.

In my package file I set up a handler that will allow me to retrieve all the events from my scripts. The problem is that I can't use my log messages only through class Logging. I am forced to use the python logging package in each of my modules when the call is already made in my package.

PACKAGE LOGS

import logging
class Logging:
    def __init__(self, module, scope, title):
        self.module = module
        self.scope = scope
        self.title = title

    def format_logs(self):
        # Configuration Logging
        logging.getLogger(__name__)
        logging.basicConfig(filename=FILE, format='%(asctime)s :: %(levelname)s :: %(message)s', datefmt='%m/%d/%Y %I:%M:%S', level=logging.DEBUG)

        # Setting up the listening file
        logging.FileHandler(FILE)

EXAMPLE SCRIPTS

from packages.pkg_logs import Logging
import logging
def __init__(self, url):
    self.url = url
    self.init_log = Logging(self.url, SCRIPT, TITLE)
    self.set_handler = self.init_log.format_logs()
    logging.info("Starting script : %s on : %s" % (TITLE, url))

Waiting for your feedback for solutions.

Arkistarvh Kltzuonstev
  • 6,824
  • 7
  • 26
  • 56
p0lux
  • 39
  • 1
  • 7

1 Answers1

0

You have to return the logger instance from your custom Log Manager.

Example:

log_mananger.py

class Logger:

    def __init__(filename):
        # set logging format
        logging.basicConfig()
        self.logger = logging.getLogger(filename=filename, format='set your custom format')
        # set up listening file
        self.logger.env=FILE

    def get_logger():
        return self.logger

script.py

from log_manager import Logger
logger = Logger().get_logger()
logger.info("message")

This should work fine.

In addition to this, if you want to log to the same file from different parts of your project, you can make the LogManager a singleton class to return a singleton object and log in the same file.

bumblebee
  • 1,811
  • 12
  • 19
  • Thank you very much for your feedback, it works perfectly! I have another problem, in my scripts I have a database instance and I would like to log the connection, however despite the instantiation nothing is logged in my database package. – p0lux Jun 17 '19 at 14:35
  • As I mentioned in the answer, you need to create the logger instance and use it for logging in your database code. Can you please share your code? – bumblebee Jun 18 '19 at 03:45