PowerToys/Wox.Infrastructure/Logger/Log.cs

90 lines
2.7 KiB
C#
Raw Normal View History

using System.Diagnostics;
using System.IO;
using NLog;
using NLog.Config;
using NLog.Targets;
2016-04-28 06:00:59 +08:00
using Wox.Infrastructure.Exception;
2013-12-20 19:38:10 +08:00
2014-09-19 16:57:48 +08:00
namespace Wox.Infrastructure.Logger
2013-12-20 19:38:10 +08:00
{
public static class Log
2013-12-20 19:38:10 +08:00
{
static Log()
{
var directoryName = "Logs";
var path = Path.Combine(Wox.DataPath, directoryName);
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
2013-12-20 19:38:10 +08:00
var configuration = new LoggingConfiguration();
var target = new FileTarget();
configuration.AddTarget("file", target);
target.FileName = "${specialfolder:folder=ApplicationData}/" + Wox.Name + "/" + directoryName + "/${shortdate}.log";
var rule = new LoggingRule("*", LogLevel.Info, target);
configuration.LoggingRules.Add(rule);
LogManager.Configuration = configuration;
}
private static string CallerType()
{
var stackTrace = new StackTrace();
var stackFrames = stackTrace.GetFrames().RequireNonNull();
var callingFrame = stackFrames[2];
var method = callingFrame.GetMethod();
var type = $"{method.DeclaringType.RequireNonNull().FullName}.{method.Name}";
return type;
}
2015-11-09 09:32:33 +08:00
public static void Error(System.Exception e)
2015-01-11 21:52:30 +08:00
{
var type = CallerType();
var logger = LogManager.GetLogger(type);
#if DEBUG
throw e;
#else
2015-11-11 08:42:49 +08:00
while (e.InnerException != null)
{
logger.Error(e.Message);
logger.Error(e.StackTrace);
e = e.InnerException;
}
#endif
2015-01-11 21:52:30 +08:00
}
2014-03-23 17:43:46 +08:00
public static void Debug(string msg)
{
var type = CallerType();
var logger = LogManager.GetLogger(type);
System.Diagnostics.Debug.WriteLine($"DEBUG: {msg}");
2015-01-20 22:33:45 +08:00
logger.Debug(msg);
2014-03-23 17:43:46 +08:00
}
public static void Info(string msg)
{
var type = CallerType();
var logger = LogManager.GetLogger(type);
System.Diagnostics.Debug.WriteLine($"INFO: {msg}");
2015-01-20 22:33:45 +08:00
logger.Info(msg);
2014-03-23 17:43:46 +08:00
}
public static void Warn(string msg)
{
var type = CallerType();
var logger = LogManager.GetLogger(type);
System.Diagnostics.Debug.WriteLine($"WARN: {msg}");
2015-01-20 22:33:45 +08:00
logger.Warn(msg);
2014-03-23 17:43:46 +08:00
}
2015-11-09 09:32:33 +08:00
public static void Fatal(System.Exception e)
2014-03-23 17:43:46 +08:00
{
var type = CallerType();
var logger = LogManager.GetLogger(type);
#if DEBUG
throw e;
#else
logger.Fatal(ExceptionFormatter.FormatExcpetion(e));
#endif
2014-03-23 17:43:46 +08:00
}
2013-12-20 19:38:10 +08:00
}
}