def setup_logging(username=None):
    """Setup logging module.

    Args:
        username: str, optional, current login name
    """
    global MSULOGENABLED
    global MSUDEBUGLOGENABLED

    if (logging.root.handlers and
        logging.root.handlers[0].__class__ is FleetingFileHandler):
        return
        
    if  munki.pref('MSUDebugLogEnabled'):
        MSUDEBUGLOGENABLED = True

    if munki.pref('MSULogEnabled'):
        MSULOGENABLED = True

    if not MSULOGENABLED:
        return

    if username is None:
        username = os.getlogin() or 'UID%d' % os.getuid()

    if not os.path.exists(MSULOGDIR):
        try:
            os.mkdir(MSULOGDIR, 01777)
        except OSError, err:
            logging.error('mkdir(%s): %s', MSULOGDIR, str(err))
            return

    if not os.path.isdir(MSULOGDIR):
        logging.error('%s is not a directory', MSULOGDIR)
        return

    # freshen permissions, if possible.
    try:
        os.chmod(MSULOGDIR, 01777)
    except OSError:
        pass

    # find a safe log file to write to for this user
    filename = os.path.join(MSULOGDIR, MSULOGFILE % username)
    attempt = 0
    ours = False

    while attempt < 10:
        try:
            fref = os.open(filename, os.O_RDWR|os.O_CREAT|os.O_NOFOLLOW, 0600)
            st = os.fstat(fref)
            ours = stat.S_ISREG(st.st_mode) and st.st_uid == os.getuid()
            os.close(fref)
            if ours:
                break
        except (OSError, IOError):
            pass  # permission denied, symlink, ...

        # avoid creating many separate log files by using one static suffix
        # as the first alternative.  if unsuccessful, switch to totally
        # randomly suffixed files.
        if attempt == 0:
            random.seed(hash(username))
        elif attempt == 1:
            random.seed()

        filename = os.path.join(
            MSULOGDIR, MSULOGFILE % (
                '%s_%d' % (username, random.randint(0, 2**32))))

        attempt += 1

    if not ours:
        logging.error('No logging is possible')
        return

    # setup log handler

    log_format = '%(created)f %(levelname)s ' + username + ' : %(message)s'
    ffh = None

    try:
        ffh = FleetingFileHandler(filename)
    except IOError, err:
        logging.error('Error opening log file %s: %s', filename, str(err))

    ffh.setFormatter(logging.Formatter(log_format, None))
    logging.root.addHandler(ffh)
    logging.getLogger().setLevel(logging.INFO)
dataset/ETHPy150Open munki/munki/code/apps/Managed Software Center/Managed Software Center/msclog.py/setup_logging/original