import os
import logging

_format = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'

def config_logger(log_level=logging.INFO):
  logging.basicConfig(format=_format, level=log_level)


# # def log_to_file(logger_name=None, log_level=logging.DEBUG, log_filename='tensorflow.log'):
def log_to_file(logger_name=None, log_filename='tensorflow.log'):
    # Ensure the directory for the log file exists
    if not os.path.exists(os.path.dirname(log_filename)):
        os.makedirs(os.path.dirname(log_filename))
    
    # Get the logger, either by name or the root logger
    if logger_name is not None:
        logger = logging.getLogger(logger_name)
    else:
        logger = logging.getLogger()
    
    logger.setLevel(logging.DEBUG)  # Set the overall logging level
    
    # Create a file handler
    fh = logging.FileHandler(log_filename)
    fh.setLevel(logging.INFO)
    
    # Create a console handler
    console_handler = logging.StreamHandler()
    console_handler.setLevel(logging.INFO)  # Set the logging level for the console handler
    
    # Create a formatter and set it for the handlers
    formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    fh.setFormatter(formatter)
    console_handler.setFormatter(formatter)
    
    # Clear any existing handlers
    if not logger.handlers:
        logger.addHandler(fh)
        logger.addHandler(console_handler)
    else:
        # Check and add handlers if they are not already added
        if not any(isinstance(handler, logging.FileHandler) for handler in logger.handlers):
            logger.addHandler(fh)
        if not any(isinstance(handler, logging.StreamHandler) for handler in logger.handlers):
            logger.addHandler(console_handler)
    return logger


def log_versions():
  import torch
  import subprocess

  logging.info('--------------- Versions ---------------')
  logging.info('git branch: ' + str(subprocess.check_output(['git', 'branch']).strip()))
  logging.info('git hash: ' + str(subprocess.check_output(['git', 'rev-parse', 'HEAD']).strip()))
  logging.info('Torch: ' + str(torch.__version__))
  logging.info('----------------------------------------')
