def add_filehandler(level, fmt, filename, mode, backup_count, limit, when):
    """Add a file handler to the global logger."""
    kwargs = {}
 
    # If the filename is not set, use the default filename
    if filename is None:
        filename = getattr(sys.modules['__main__'], '__file__', 'log.py')
        filename = os.path.basename(filename.replace('.py', '.log'))
        filename = os.path.join('/tmp', filename)

    if not os.path.exists(os.path.dirname(filename)):
        os.mkdir(os.path.dirname(filename))

    kwargs['filename'] = filename
 
    # Choose the filehandler based on the passed arguments
    if backup_count == 0:  # Use FileHandler
        cls = logging.FileHandler
        kwargs['mode'] = mode
    elif when is None:  # Use RotatingFileHandler
        cls = logging.handlers.RotatingFileHandler
        kwargs['maxBytes'] = limit
        kwargs['backupCount'] = backup_count
        kwargs['mode'] = mode
    else:  # Use TimedRotatingFileHandler
        cls = logging.handlers.TimedRotatingFileHandler
        kwargs['when'] = when
        kwargs['interval'] = limit
        kwargs['backupCount'] = backup_count
 
    return add_handler(cls, level, fmt, False, **kwargs)
Add a file handler to the global logger.