#!/usr/bin/env python2
# coding=utf-8

"""
config logger
"""

from __future__ import (absolute_import, division, print_function,
                        unicode_literals, with_statement)

import os.path
import logging

from logging.config import fileConfig
from pkg_resources import resource_filename


def load_logger_config():
    """if /var/log/{{name}} exist, load default logger.conf.

    otherwise, try to create it directly.
    if that fails, try to create it with sudo.
    if that fails, use basic logger config.

    """
    logdir = "/var/log/{{name}}/"
    if os.path.exists(logdir):
        fileConfig(resource_filename("{{name}}", "logger.conf"))
        return

    try:
        os.makedirs(logdir)
        fileConfig(resource_filename("{{name}}", "logger.conf"))
        return
    except OSError as _:
        pass

    import subprocess
    exit_code = subprocess.call(["sudo", "mkdir", "-p", logdir])
    if exit_code == 0:
        fileConfig(resource_filename("{{name}}", "logger.conf"))
        return

    TESTING = os.getenv("PYTEST") == "1"
    level = logging.DEBUG if TESTING else logging.INFO
    logging.basicConfig(
        format='%(asctime)s [%(module)s] %(levelname)-8s %(message)s',
        level=level)
    logging.info("Create log dir %s failed. Using basic config, level=%s",
                 logdir, "DEBUG" if TESTING else "INFO")


logging.captureWarnings(True)
load_logger_config()
