- First , add local log4net.dll to reference
- In project—>Properties—>AssemblyInfo.cs , add this line
1 |
<span class="na">[assembly: log4net.Config.XmlConfigurator(Watch = true)]</span> |
- change App.config to :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
<?xml version="1.0" encoding="utf-8"?> <configuration> <configSections> <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" /> </configSections> <startup> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6" /> </startup> <log4net> <appender name="ConsoleAppender" type="log4net.Appender.ColoredConsoleAppender"> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%date %level [%thread] %logger{1} %username - %message%newline" /> </layout> <mapping> <level value="WARN" /> <foreColor value="Yellow, HighIntensity" /> </mapping> <mapping> <level value="ERROR" /> <foreColor value="Red, HighIntensity" /> </mapping> </appender> <appender name="RollingFile" type="log4net.Appender.RollingFileAppender"> <file value="./logs/log.log" /> <rollingStyle value="Date" /> <appendToFile value="true" /> <lockingModel type="log4net.Appender.FileAppender+MinimalLock" /> <datePattern value="yyyyMMdd" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%date %level [%thread] %logger{1} - %message%newline" /> </layout> </appender> <root> <level value="INFO" /> <appender-ref ref="ConsoleAppender" /> <appender-ref ref="RollingFile" /> </root> </log4net> </configuration> |
- in Program.cs , use log4net like this :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
using System; using System.Security.Principal; using log4net; namespace MyApp { internal class Program { private static readonly ILog Logger = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); private static void Main(string[] args) { Logger.InfoFormat("Running as {0}", WindowsIdentity.GetCurrent().Name); Logger.Error("This will appear in red in the console and still be written to file!"); } } } |
- learn from : http://spencerooni.github.io/2016/05/06/simple-log4net-setup.html
- If do not need log display on console program command line , comment the part of ” ConsoleAppender”