فهرست منبع

log文件更新

houweichen 2 ماه پیش
والد
کامیت
6e8066b2e1

+ 34 - 0
src/Wicture.DbRESTFul/Log/LoggerManager.cs

@@ -0,0 +1,34 @@
+using NLog;
+using System;
+using System.Diagnostics;
+using System.Runtime.CompilerServices;
+
+namespace Wicture.DbRESTFul
+{
+    public static class LoggerManager
+    {
+        public static ILogger Logger { get; private set; }
+
+        static LoggerManager()
+        {
+            Logger = LogManager.GetLogger("DbRESTFul");
+        }
+
+        public static Stopwatch StartWatch([CallerMemberName] string targetName = "")
+        {
+            Logger.Debug($"`{targetName}`: Start watching at: {DateTime.Now}");
+            return Stopwatch.StartNew();
+        }
+
+        public static void LogWatch(Stopwatch sw, string message, [CallerMemberName] string targetName = "")
+        {
+            Logger.Debug($"`{targetName}`: {message} at: {DateTime.Now}, toke: {sw.ElapsedMilliseconds}ms");
+        }
+
+        public static void EndWatch(Stopwatch sw, [CallerMemberName] string targetName = "")
+        {
+            Logger.Debug($"`{targetName}`: End watching at: {DateTime.Now}, toke: {sw.ElapsedMilliseconds}ms");
+            sw.Stop();
+        }
+    }
+}

+ 75 - 0
src/Wicture.DbRESTFul/Log/NLog/DefaultNLogConfigProvider.cs

@@ -0,0 +1,75 @@
+using NLog;
+using NLog.Config;
+using NLog.Targets;
+using System;
+using System.IO;
+using System.Reflection;
+
+namespace Wicture.DbRESTFul.Log.NLog
+{
+    public class DefaultNLogConfigProvider : INLogConfigProvider
+    {
+        public LoggingConfiguration Provide()
+        {
+            // Step 1. Create configuration object 
+            var config = new LoggingConfiguration();
+
+            // Step 2. Create targets
+            var consoleTarget = new ColoredConsoleTarget("console")
+            {
+                Layout = @"${date:format=HH\:mm\:ss} ${level} ${message} ${exception}"
+            };
+            config.AddTarget(consoleTarget);
+
+            var fileTarget = new FileTarget("verbose")
+            {
+                FileName = "${basedir}/log/${shortdate}-verbose.log",
+                Layout = "${longdate} ${level} ${message}  ${exception}"
+            };
+            config.AddTarget(fileTarget);
+
+            var errorTarget = GetDBLogger("error");
+            config.AddTarget(errorTarget);
+
+            // Step 3. Define rules
+            config.AddRuleForOneLevel(LogLevel.Error, errorTarget); // only errors to file
+            config.AddRuleForAllLevels(fileTarget); // all to console
+            config.AddRuleForAllLevels(consoleTarget); // all to console
+
+            return config;
+        }
+
+        // https://nlog-project.org/config/?tab=layout-renderers
+        private DatabaseTarget GetDBLogger(string dbName)
+        {
+            var path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "log");
+            if (!Directory.Exists(path)) Directory.CreateDirectory(path);
+
+            var target = new DatabaseTarget(dbName)
+            {
+                DBProvider = "System.Data.SQLite.SQLiteConnection, System.Data.SQLite",
+                ConnectionString = "Data Source=${basedir}/log/error.db;",
+                DBDatabase = "Log",
+                CommandText = "INSERT into Log(timestamp, logger, hostname, properties, stacktrace, message, exception) values(@timestamp, @logger, @hostname, @properties, @stacktrace, @message, @exception);",
+            };
+            target.Parameters.Add(new DatabaseParameterInfo { Name = "@timestamp", Layout = "${longdate}" });
+            target.Parameters.Add(new DatabaseParameterInfo { Name = "@logger", Layout = "${logger}" });
+            target.Parameters.Add(new DatabaseParameterInfo { Name = "@hostname", Layout = "${hostname}" });
+            target.Parameters.Add(new DatabaseParameterInfo { Name = "@properties", Layout = "${all-event-properties:separator=|}" });
+            target.Parameters.Add(new DatabaseParameterInfo { Name = "@stacktrace", Layout = "${callsite:includeNamespace=False:fileName=True}" });
+            target.Parameters.Add(new DatabaseParameterInfo { Name = "@message", Layout = "${message}" });
+            target.Parameters.Add(new DatabaseParameterInfo { Name = "@exception", Layout = "${exception:tostring}" });
+
+            target.InstallConnectionString = target.ConnectionString;
+            target.InstallDdlCommands.Add(new DatabaseCommandInfo
+            {
+                CommandType = System.Data.CommandType.Text,
+                Text = @"CREATE TABLE  if not exists Log (timestamp TEXT, logger TEXT, hostname TEXT, properties TEXT, stacktrace TEXT, message TEXT, exception TEXT) "
+            });
+
+            target.Install(new InstallationContext(Console.Out));
+
+            return target;
+        }
+    }
+}

+ 8 - 0
src/Wicture.DbRESTFul/Log/NLog/INLogConfigProvider.cs

@@ -0,0 +1,8 @@
+using NLog.Config;
+
+namespace Wicture.DbRESTFul.Log.NLog
+{
+    public interface INLogConfigProvider: IProvider<LoggingConfiguration>
+    {
+    }
+}

+ 34 - 0
src/Wicture.DbRESTFul/Log/nlog.config

@@ -0,0 +1,34 @@
+<?xml version="1.0" encoding="utf-8" ?>
+<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
+      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+      autoReload="true"
+      internalLogLevel="Info"
+      internalLogFile="c:\temp\internal-nlog.txt">
+
+  <!-- enable asp.net core layout renderers -->
+  <extensions>
+    <add assembly="NLog.Web.AspNetCore"/>
+  </extensions>
+
+  <!-- the targets to write to -->
+  <targets>
+    <target name="console" xsi:type="Console"
+          layout="${longdate}|${level:uppercase=true}|${logger}|${message}"
+          error="true"
+          detectConsoleAvailable="true" />
+
+    <!-- write logs to file  -->
+    <target xsi:type="File" name="allfile" fileName="logs/${shortdate}.log"
+            layout="${longdate}|${event-properties:item=EventId_Id}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}" />
+  </targets>
+
+  <!-- rules to map from logger name to target -->
+  <rules>
+    <!--All logs, including from Microsoft-->
+    <logger name="*" minlevel="Info" writeTo="allfile" />
+    <!--All logs, including from Microsoft-->
+    <logger name="*" minlevel="Trace" writeTo="console" />
+    <!--Skip non-critical Microsoft logs and so log only own logs-->
+    <logger name="Microsoft.*" maxlevel="Info" final="true" />
+  </rules>
+</nlog>