﻿using System;
using System.IO;
using UnityEngine;

public class CustomLogHandler : MonoBehaviour
{
    public string logFile = "log.txt";
    private string rootDirectory = @"Assets/StreamingAssets";
    private string filepath;
    void Awake()
    {
        Application.logMessageReceived += Application_logMessageReceived;

#if UNITY_EDITOR
        filepath = string.Format(rootDirectory + @"/{0}", logFile);
        if(Directory.Exists(rootDirectory)==false)
        {
            Directory.CreateDirectory(rootDirectory);
        }       
#else
        // check if file exists in Application.persistentDataPath
        filepath = string.Format("{0}/{1}", Application.persistentDataPath, logFile);
#endif
    }

    private void Application_logMessageReceived(string condition, string stackTrace, LogType type)
    {
        var level = type.ToString();
        var time = DateTime.Now.ToShortTimeString();
        var newLine = Environment.NewLine;

        var log = string.Format("{0}:[{1}]:{2}{3}"
            , level,time, condition, newLine);

        try
        {
            File.AppendAllText(filepath, log);
        }
        catch (Exception ex)
        {
            var msg = ex.Message;
        }
    }

    

}
