[私人小抄] Nlog 記錄到MSSQL

Nlog 記錄到MSSQL 可以使用 

參考文章 Create custom Target , How to write a custom target

    [Target("SqlServerTarget")]
    public class SqlServerTarget: TargetWithLayout
    {
        private static string strConnection = ConfigurationManager.ConnectionStrings["Connection"].ConnectionString;
        protected override void Write(LogEventInfo logEvent)
        {            
            using (var conn = new SqlConnection(strConnection))
            {
                LogRepository<NLogInfo> logRepo = new LogRepository<NLogInfo>(conn);

                logRepo.UpSert(new NLogInfo
                {
                    //LogId = logEvent.SequenceID,
                    ActivityId = Guid.NewGuid(),
                    Origin = logEvent.LoggerName,
                    Level = logEvent.Level.Name,
                    Message = logEvent.Message,
                    Detail = logEvent.StackTrace.ToString(),
                    Date = DateTime.Now,
                    Machinename =
                        !logEvent.HasProperties ? null :
                         logEvent.Properties.ContainsKey("Machinename") ? logEvent.Properties["Machinename"].ToString() : string.Empty
                });
            }

            base.Write(logEvent);
        }
    }

參考文章 Create custom Target

 

如果內容有誤請多鞭策謝謝