1.vs2017创建控制台运用程序
2.NuGet程序包安装:log4net
3.Program.cs
using log4net.Config; using System; using System.Collections.Generic; using System.Configuration; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace Long4Sql { class Program { // 参考文章:https://blog.csdn.net/chinacsharper/article/details/17791449 static void Main(string[] args) { Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); Console.WriteLine("程序Start!"); Logger.LoggerMsg(Loglevel.Info, $"程序Start:{DateTime.Now.ToShortDateString().ToString()}/{DateTime.Now.TimeOfDay.ToString()}"); Thread.Sleep(5000); var strPaths = ConfigurationManager.AppSettings["dirPath"]; List<FileInfo> lst = new List<FileInfo>(); List<FileInfo> lstfiles = GetFiles(strPaths, ".jpg", ref lst); DirectoryInfo info = new DirectoryInfo(strPaths); try { foreach (FileInfo item in lstfiles) { Logger.LoggerMsg(Loglevel.Info, item.ToString());// 输入到数据库 Console.WriteLine(item); // 输出到控制台 } } catch (Exception ex) { Logger.LoggerMsg(Loglevel.Error, ex.ToString()); } Console.WriteLine("当前获取到的文件总数:{0}", GetFilesCount(info)); Console.WriteLine("执行完成"); Logger.LoggerMsg(Loglevel.Info, $"程序Stop:{DateTime.Now.ToShortDateString().ToString()}/{DateTime.Now.TimeOfDay.ToString()}"); Console.WriteLine("程序STOP!"); Console.ReadKey(); } #region 获取指定文件夹下的指定后缀文件后缀(包括获取子文件下的) /// <summary> /// 获取指定文件夹下的指定后缀文件后缀(包括获取子文件下的) /// </summary> /// <param name="path">文件夹路径</param> /// <param name="ExtName">文件后缀</param> /// <param name="lst"></param> /// <returns></returns> public static List<FileInfo> GetFiles(string path, string ExtName, ref List<FileInfo> lst) { try { //List<FileInfo> lst = new List<FileInfo>(); string[] dir = Directory.GetDirectories(path);// 文件夹列表 DirectoryInfo directoryInfo = new DirectoryInfo(path); FileInfo[] files = directoryInfo.GetFiles(); if (files.Length != 0 || dir.Length != 0) // 当前目录文件或文件夹不能为空 { foreach (FileInfo f in files) { if (ExtName.ToLower().IndexOf(f.Extension.ToLower()) >= 0) { lst.Add(f); } } foreach (string d in dir) { GetFiles(d, ExtName, ref lst); } } return lst; } catch (Exception ex) { throw ex; } } #endregion #region 获取文件总数 public static int GetFilesCount(DirectoryInfo directoryInfo) { int totalFile = 0; totalFile += directoryInfo.GetFiles().Length; foreach (DirectoryInfo f in directoryInfo.GetDirectories()) { totalFile += GetFilesCount(f); } return totalFile; } #endregion } }
4.Logger.cs
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; namespace Long4Sql { public class Logger { /// <summary> /// 记录对应级别的日志信息 /// </summary> /// <param name="loglevel"></param> /// <param name="msg"></param> public static void LoggerMsg(Loglevel loglevel, string msg) { log4net.ILog log = GetLogger(); switch (loglevel) { case Loglevel.Debug: log.Debug(msg); break; case Loglevel.Info: log.Info(msg); break; case Loglevel.Warn: log.Warn(msg); break; case Loglevel.Error: log.Error(msg); break; case Loglevel.Fatal: log.Fatal(msg); break; default: break; } } /// <summary> /// 获取日志对象 /// </summary> /// <returns></returns> public static log4net.ILog GetLogger() { //MethodBase.GetCurrentMethod().DeclaringType 返回:命名空间名+类名 return log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); } } /// <summary> /// 日志级别 /// </summary> public enum Loglevel { Debug, Info, Warn, Error, Fatal, } }
5.log4net.config(使用时记得修改属性->如果较新则复制)
<?xml version="1.0" encoding="utf-8" ?> <configuration> <!--添加log4net自定义节点--> <configSections> <section name="log4net" type="System.Configuration.IgnoreSectionHandler"/> </configSections> <log4net> <!--文件形式存放--> <appender name="FileAppender" type="log4net.Appender.FileAppender"> <!--文件路径--> <file value="Log\log-file.txt"/> <!--是否追加--> <appendToFile value="true"/> <!--显示格式--> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="[%date] [%thread] [%-5level] [%logger] [%property{NDC}] - %message%newline"/> </layout> </appender> <!--SqlServer形式--> <!--log4net日志配置:http://logging.apache.org/log4net/release/config-examples.html --> <appender name="AdoNetAppender_SqlServer" type="log4net.Appender.AdoNetAppender"> <!--日志缓存写入条数 设置为0时只要有一条就立刻写到数据库--> <bufferSize value="0" /> <connectionType value="System.Data.SqlClient.SqlConnection, System.Data, Version=2.0.0.0, Culture=Neutral, PublicKeyToken=b77a5c561934e089" /> <connectionString value="Data Source=DESKTOP-JFK9IB;Initial Catalog=Images;Integrated Security=True" /> <commandText value="INSERT INTO Log ([Date],[Thread],[Level],[Logger],[Message],[Exception]) VALUES (@log_date, @thread, @log_level, @logger, @message, @exception)" /> <parameter> <parameterName value="@log_date" /> <dbType value="DateTime" /> <layout type="log4net.Layout.RawTimeStampLayout" /> </parameter> <parameter> <parameterName value="@thread" /> <dbType value="String" /> <size value="255" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%thread" /> </layout> </parameter> <parameter> <parameterName value="@log_level" /> <dbType value="String" /> <size value="50" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%level" /> </layout> </parameter> <parameter> <parameterName value="@logger" /> <dbType value="String" /> <size value="255" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%logger" /> </layout> </parameter> <parameter> <parameterName value="@message" /> <dbType value="String" /> <size value="4000" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%message" /> </layout> </parameter> <parameter> <parameterName value="@exception" /> <dbType value="String" /> <size value="2000" /> <layout type="log4net.Layout.ExceptionLayout" /> </parameter> </appender> <!--Access数据库--> <appender name="AdoNetAppender_Access" type="log4net.Appender.AdoNetAppender"> <connectionString value="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Documents and Settings\Administrator\桌面\test.mdb;User Id=;Password=;" /> <commandText value="INSERT INTO Log ([Date],[Thread],[Level],[Logger],[Message]) VALUES (@log_date, @thread, @log_level, @logger, @message)" /> <parameter> <parameterName value="@log_date" /> <dbType value="String" /> <size value="255" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%date" /> </layout> </parameter> <parameter> <parameterName value="@thread" /> <dbType value="String" /> <size value="255" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%thread" /> </layout> </parameter> <parameter> <parameterName value="@log_level" /> <dbType value="String" /> <size value="50" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%level" /> </layout> </parameter> <parameter> <parameterName value="@logger" /> <dbType value="String" /> <size value="255" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%logger" /> </layout> </parameter> <parameter> <parameterName value="@message" /> <dbType value="String" /> <size value="1024" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%message" /> </layout> </parameter> </appender> <!--Oracle形式--> <appender name="AdoNetAppender_Oracle" type="log4net.Appender.AdoNetAppender"> <!--数据库连接类型--> <connectionType value="System.Data.OracleClient.OracleConnection, System.Data.OracleClient, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" /> <!--数据库连接字符串--> <connectionString value="data source=orcl;User ID=damis;Password=damis" /> <!--数据库执行语句--> <commandText value="INSERT INTO Log (Datetime,Thread,Log_Level,Logger,Message) VALUES (:log_date, :thread, :log_level, :logger, :message)" /> <!--缓冲区大小--> <bufferSize value="128" /> <!--数据库表字段参数--> <parameter> <parameterName value=":log_date" /> <dbType value="DateTime" /> <layout type="log4net.Layout.RawTimeStampLayout" /> </parameter> <parameter> <parameterName value=":thread" /> <dbType value="String" /> <size value="255" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%thread" /> </layout> </parameter> <parameter> <parameterName value=":log_level" /> <dbType value="String" /> <size value="50" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%level" /> </layout> </parameter> <parameter> <parameterName value=":logger" /> <dbType value="String" /> <size value="255" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%logger" /> </layout> </parameter> <parameter> <parameterName value=":message" /> <dbType value="String" /> <size value="4000" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%message" /> </layout> </parameter> </appender> <!--配置日志的目标存储形式--> <root> <!--文件形式--> <appender-ref ref="FileAppender"/> <!--SqlServer形式--> <appender-ref ref="AdoNetAppender_SqlServer"/> <!--Oracle形式--> <appender-ref ref="AdoNetAppender_Oracle"/> <!--Access形式--> <appender-ref ref="AdoNetAppender_Access"/> </root> </log4net> </configuration>
6.sql
CREATE TABLE [dbo].[Log] ( [Id] [int] IDENTITY (1, 1) NOT NULL, [Date] [datetime] NOT NULL, [Thread] [varchar] (255) NOT NULL, [Level] [varchar] (50) NOT NULL, [Logger] [varchar] (255) NOT NULL, [Message] [varchar] (4000) NOT NULL, [Exception] [varchar] (2000) NULL )