在C#中将日志存入数据库可以通过多种方式实现,以下是几种常见的方法:
1、安装NLog:通过NuGet包管理器安装NLog程序集。
2、配置NLog:打开Nlog.config
文件,在target
节点中增加对数据库的配置,例如使用SQL Server 2008时,可以这样配置:
<target type="Database" name="database" connectionstring="Data Source=.;Initial Catalog=ReportServerTempDB;Integrated Security=True"> <commandText> insert into MyLog ([CreateDate], [Origin], [LogLevel], [Message], [StackTrace]) values (@createDate, @origin, @logLevel, @message, @stackTrace); </commandText> <parameter name="@createDate" layout="${longdate}"/> <parameter name="@origin" layout="${callsite}"/> <parameter name="@logLevel" layout="${level}"/> <parameter name="@message" layout="${message}"/> <parameter name="@stackTrace" layout="${stacktrace}"/> </target>
在rules
节点中增加日志记录规则,比如将所有级别的日志都写入数据库:
<rules> <logger name="*" writeTo="database"/> </rules>
3、代码中使用NLog记录日志:在C#代码中,通过Logger
类记录日志,这些日志会自动按照配置存入数据库。
private static Logger logger = LogManager.GetCurrentClassLogger(); static void Main(string[] args) { logger.Fatal("发生致命错误"); }
1、创建数据库表:首先在数据库中创建一个用于存储日志的表,例如mail_web_log
表,包含字段如nId
(主键,自增)、dtDate
(日期时间)、sThread
(线程名)、sLevel
(日志级别)、sLogger
(日志来源)、sMessage
)、sException
(异常信息)等。
2、编写代码实现日志写入:可以使用System.Data.SqlClient
命名空间下的类来实现与SQL Server数据库的交互,将日志信息插入到数据库表中,以下是一个示例代码:
using System; using System.Data.SqlClient; class Program { static void Main(string[] args) { LogHelper.Write(new LogModel(LogLevel.Info, "ControllerName", "ActionName", "LogMessage")); } } public enum LogLevel { Info, Warning, Error, Fatal } public class LogModel { public LogLevel Level { get; set; } public string Controller { get; set; } public string Action { get; set; } public string Message { get; set; } } public class LogHelper { private static readonly string connectionString = "your connection string"; private static readonly object locker = new object(); public static void Write(LogModel content) { lock (locker) { using (SqlConnection conn = new SqlConnection(connectionString)) { conn.Open(); string sql = "INSERT INTO mail_web_log (dtDate, sThread, sLevel, sLogger, sMessage, sException) VALUES (@dtDate, @sThread, @sLevel, @sLogger, @sMessage, @sException)"; using (SqlCommand cmd = new SqlCommand(sql, conn)) { cmd.Parameters.AddWithValue("@dtDate", DateTime.Now); cmd.Parameters.AddWithValue("@sThread", content.Controller + "." + content.Action); cmd.Parameters.AddWithValue("@sLevel", content.Level.ToString()); cmd.Parameters.AddWithValue("@sLogger", "YourLoggerName"); cmd.Parameters.AddWithValue("@sMessage", content.Message); cmd.Parameters.AddWithValue("@sException", null); cmd.ExecuteNonQuery(); } } } } }
使用Log4Net记录日志到数据库(适用于AspNetCore项目需自行写插件的情况)
1、创建LogModel类和LogDAL类:LogModel
类用于映射数据库表结构,LogDAL
类用于将日志对象入库操作。
public class LogModel { public int nId { get; set; } public DateTime dtDate { get; set; } public string sThread { get; set; } public string sLevel { get; set; } public string sLogger { get; set; } public string sMessage { get; set; } public string sException { get; set; } } public class LogDAL { private static readonly string connectionString = "your connection string"; public static void InputDb(LogModel log) { using (SqlConnection conn = new SqlConnection(connectionString)) { conn.Open(); string sql = "INSERT INTO mail_web_log (dtDate, sThread, sLevel, sLogger, sMessage, sException) VALUES (@dtDate, @sThread, @sLevel, @sLogger, @sMessage, @sException)"; using (SqlCommand cmd = new SqlCommand(sql, conn)) { cmd.Parameters.AddWithValue("@dtDate", log.dtDate); cmd.Parameters.AddWithValue("@sThread", log.sThread); cmd.Parameters.AddWithValue("@sLevel", log.sLevel); cmd.Parameters.AddWithValue("@sLogger", log.sLogger); cmd.Parameters.AddWithValue("@sMessage", log.sMessage); cmd.Parameters.AddWithValue("@sException", log.sException); cmd.ExecuteNonQuery(); } } } }
2、创建LogHelper类:使用单例模式和队列来处理日志写入任务。
public class LogHelper { private Queue<Action> _queue; private Thread _loggingThread; private ManualResetEvent _hasNew; private static readonly LogHelper _logger = new LogHelper(); private LogHelper() { _queue = new Queue<Action>(); _hasNew = new ManualResetEvent(false); _loggingThread = new Thread(Process); _loggingThread.IsBackground = true; _loggingThread.Start(); } private void Process() { while (true) { _hasNew.WaitOne(); _hasNew.Reset(); Thread.Sleep(100); Queue<Action> queueCopy; lock (_queue) { queueCopy = new Queue<Action>(_queue); _queue.Clear(); } foreach (var action in queueCopy) { action(); } } } private void WriteLog(LogModel content) { lock (_queue) { _queue.Enqueue(() => LogDAL.InputDb(content)); } _hasNew.Set(); } public static void Write(LogModel content) { Task.Run(() => GetInstance().WriteLog(content)); } public static LogHelper GetInstance() { return _logger; } }
3、使用LogHelper记录日志:在需要记录日志的地方,调用LogHelper.Write
方法传入LogModel
对象即可。
LogHelper.Write(new LogModel { dtDate = DateTime.Now, sThread = "ControllerName.ActionName", sLevel = "Info", sLogger = "YourLoggerName", sMessage = "LogMessage" });