Newer
Older
LensAdjustmentTool / Infrastructure / AppLogger.cs
using System;
using System.Diagnostics;
using System.IO;
using System.Text;

namespace LensAdjustmentTool.Infrastructure
{
    public sealed class AppLogger : IDisposable
    {
        private readonly object _sync = new object();
        private readonly StreamWriter _writer;

        public string LogFilePath { get; }

        public AppLogger()
        {
            string logDir = Path.Combine(
                Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
                "LensAdjustmentTool",
                "Logs");

            Directory.CreateDirectory(logDir);
            LogFilePath = Path.Combine(logDir, $"LensAdjustmentTool_{DateTime.Now:yyyyMMdd}.log");
            _writer = new StreamWriter(LogFilePath, true, new UTF8Encoding(false))
            {
                AutoFlush = true
            };
        }

        public void Info(string message) => Write("INFO", message);
        public void Warn(string message) => Write("WARN", message);
        public void Error(string message, Exception ex = null)
        {
            Write("ERROR", ex == null ? message : message + Environment.NewLine + ex);
        }

        private void Write(string level, string message)
        {
            string line = $"{DateTime.Now:yyyy-MM-dd HH:mm:ss.fff} [{level}] {message}";
            lock (_sync)
            {
                _writer.WriteLine(line);
            }
            Trace.WriteLine(line);
        }

        public void Dispose()
        {
            lock (_sync)
            {
                _writer.Dispose();
            }
        }
    }
}