Singleton

```python
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import logging
import os 
import sys
from functools import wraps
from datetime import datetime
from pytz import timezone
from pathlib import Path
from dataclasses import dataclass



"""
LOGGING LEVEL PRIORITY
CRITICAL   50
ERROR      40
WARNING    30
INFO       20
DEBUG      10
NOTSET     0
"""

PARIS_TIME_ZONE = "Europe/Paris"
TIME_FORMAT = "%Y-%m-%d %H:%M:%S"
LOG_FORMAT = '%(asctime)s|%(levelname)s|%(message)s'
LOG_FORMAT = '%(asctime)s|{}.py|%(levelname)s|%(message)s'
TODAY = datetime.now().strftime("%Y%m%d")

# def Singleton(cls):
#     instance = {}
#     @wraps(cls)
#     def get_instance(*args,**kwargs):
#         if cls not in instance:
#             instance[cls] = cls(*args,**kwargs)
#         return instance[cls]
#     return get_instance

class CustomizeLogger(logging.Logger):
    _instance = None

    def __init__(self, name):
        super().__init__(name)
        formatter = logging.Formatter(LOG_FORMAT.format(name), TIME_FORMAT)
        stream_handler,file_handler= logging.StreamHandler(),logging.FileHandler(f"./logs/{TODAY}.log")
        stream_handler.setFormatter(formatter)
        file_handler.setFormatter(formatter)

        self.addHandler(stream_handler)
        self.addHandler(file_handler)

    def __new__(cls,name):
        # If the instance doesn't exist, create it
        if not cls._instance:
            cls._instance = super().__new__(cls)
        # Return the instance
        return cls._instance

    @staticmethod
    def datetime2Utc(dt:datetime, timeformat:TIME_FORMAT)->str:
        """Receive a datetime object and return utc time with string format"""
        return dt.astimezone(timezone('utc')).strftime(timeformat)

    @staticmethod
    def datetime2Paris(dt:datetime, timeformat:str=TIME_FORMAT)->str:
        """Receive a datetime object and return Paris time with string format"""
        return dt.astimezone(timezone(PARIS_TIME_ZONE)).strftime(timeformat)

if __name__ == '__main__':

    logger = CustomizeLogger(Path(__file__).stem)
    logger1 = CustomizeLogger(Path(__file__).stem)
    print(id(logger)==id(logger1))
    logger.debug("This is a debug message.")
    logger.info("This is an info message.")
```

Last updated