import os as __os, datetime as __datetime, pytz as __pytz
import sys as __sys, codecs as __codecs

def write(source, tag, table, message):
    now = __datetime.datetime.now(tz=__pytz.timezone('Asia/Taipei'))
    
    now = str(int(now.strftime("%Y%m%d%H%M")) - 191100000000)
    
    date = __os.path.join("log", now[0:3], now[3:5])
    # Create log folder if it't exists.
    if not __os.path.exists(date):
        __os.makedirs(date)
    # Record SQL operator per day.
    with __codecs.open(__os.path.join(date, now[5:7] + '.log'), "a", "utf-8") as f:
        f.write(u"[" + source + "][" + now[7:9] + ":" + now[9:11] + "][" + tag + "][" + table + "]:\n" + message + "\n")
    
#     try:
#         __sys.stdout = __codecs.getwriter("utf-8")(__sys.stdout.detach())
#     except:
#         tag = "ERROR"
    
    print(u"[" + source + "][" + now[7:9] + ":" + now[9:11] + "][" + table + "]:" + tag)
