public static void SetupUdp() { var layout = new log4net.Layout.PatternLayout(); //var appender = new TcpAppender(5140, IPAddress.Loopback) { Layout = layout}; var appender = new UdpAppender { Layout = layout, RemoteAddress = IPAddress.Loopback, RemotePort = 5142 }; layout.ActivateOptions(); appender.ActivateOptions(); var layout2 = new log4net.Layout.PatternLayout(); //var appender = new TcpAppender(5140, IPAddress.Loopback) { Layout = layout}; var appender2 = new UdpAppender { Layout = layout2, RemoteAddress = IPAddress.Loopback, RemotePort = 5142 }; layout2.ActivateOptions(); appender2.ActivateOptions(); var layout3 = new log4net.Layout.PatternLayout(); //var appender = new TcpAppender(5140, IPAddress.Loopback) { Layout = layout}; var appender3 = new UdpAppender { Layout = layout3, RemoteAddress = IPAddress.Loopback, RemotePort = 5142 }; layout3.ActivateOptions(); appender3.ActivateOptions(); log4net.Config.BasicConfigurator.Configure(appender, appender2, appender3); }
private IAppender CreateSiteAppender() { OrchardFileAppender appender = new OrchardFileAppender(); appender.Name = GetAppenderName(); appender.File = GetAppenderFileName(); appender.AppendToFile = true; // Allow extended character sets appender.Encoding = Encoding.UTF8; // Immediately flush on error to avoid data loss appender.ImmediateFlush = true; // Filename will also depend on date appender.StaticLogFileName = false; appender.RollingStyle = RollingFileAppender.RollingMode.Date; appender.DatePattern = $"{LaserAuditTrailHelper.GetAppenderDatePattern()}'.{LaserAuditTrailHelper.GetAppenderFileExtension()}'"; // Prevent Orchard from displaying locking debug messages appender.LockingModel = new FileAppender.MinimalLock(); // Filters var stringMatchFilter = new log4net.Filter.StringMatchFilter(); stringMatchFilter.StringToMatch = _logMatchString; appender.AddFilter(stringMatchFilter); appender.AddFilter(new log4net.Filter.DenyAllFilter()); // Log Layout var layout = new log4net.Layout.PatternLayout( @"%date %logger - %P{Tenant} - %level% [ExecutionId=%P{ExecutionId}]%newline[%P{Url}]%newline%message%newline " ); layout.ActivateOptions(); appender.Layout = layout; appender.ActivateOptions(); return(appender); }
private static void SetUpFileLogger() { string filePattern = "%date %-15.15thread %-5level: %message%newline"; log4net.Layout.ILayout layout; log4net.Layout.PatternLayout normalTextLayout = new log4net.Layout.PatternLayout(filePattern); normalTextLayout.ActivateOptions(); layout = normalTextLayout; log4net.Appender.FileAppender fileAppender = new log4net.Appender.FileAppender(); fileAppender.AppendToFile = false; fileAppender.Encoding = Encoding.UTF8; fileAppender.File = Paths.LogPath; fileAppender.ImmediateFlush = true; fileAppender.Layout = layout; fileAppender.LockingModel = new log4net.Appender.FileAppender.ExclusiveLock(); fileAppender.Name = "File appender"; fileAppender.Threshold = log4net.Core.Level.Debug; fileAppender.ActivateOptions(); // A slight bit of hackery in order to programatically set more than one appender (which isn't supported by BasicConfigurator) log4net.Repository.Hierarchy.Logger root = ((log4net.Repository.Hierarchy.Hierarchy)log4net.LogManager.GetRepository()).Root; root.AddAppender(fileAppender); root.Repository.Configured = true; }
/// <summary> /// constructor that initialize logger name, file name and log level /// </summary> public CLogger(string sLoggerName, string sFilename, int iLogLevel) { ILog oLogger = LogManager.GetLogger(sLoggerName); string sLogFileName = string.Empty; sLogFileName = GetLogFileName(sFilename); m_oFPLogger = (log4net.Repository.Hierarchy.Logger)oLogger.Logger; log4net.Appender.RollingFileAppender oFPAppender = new RollingFileAppender(); oFPAppender.File = sLogFileName; oFPAppender.MaxSizeRollBackups = 100; oFPAppender.MaximumFileSize = "1MB"; oFPAppender.RollingStyle = RollingFileAppender.RollingMode.Size; oFPAppender.StaticLogFileName = true; oFPAppender.AppendToFile = true; log4net.Layout.PatternLayout layout = new log4net.Layout.PatternLayout(); layout.ConversionPattern = "%d %-5p - %m%n%exception"; layout.ActivateOptions(); oFPAppender.Layout = layout; oFPAppender.ActivateOptions(); /** Programmatically configuration will not work it it is not set true**/ m_oFPLogger.Hierarchy.Configured = true; try { m_oFPLogger.AddAppender(oFPAppender); } catch (Exception ex) { throw new Exception("Failed to Add Appender", ex); } m_oFPLogger.Hierarchy.Root.Level = m_oFPLogger.Hierarchy.LevelMap[GetLogLevel(iLogLevel)]; oLogger = null; }
public static void InitLog(string completeLogFile, bool externalConsole) { _filePath = completeLogFile; var hierarchy = (log4net.Repository.Hierarchy.Hierarchy)LogManager.GetRepository(); hierarchy.Root.RemoveAllAppenders(); var pl = new log4net.Layout.PatternLayout { ConversionPattern = DefaultConversionPatern }; pl.ActivateOptions(); var fileAppender = new log4net.Appender.FileAppender { AppendToFile = true, LockingModel = new log4net.Appender.FileAppender.MinimalLock(), File = _filePath, Layout = pl }; fileAppender.ActivateOptions(); log4net.Config.BasicConfigurator.Configure(fileAppender); _logger = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); if (externalConsole) { AddLogToConsole(false); } }
//configure log4Net via code instead of xml public static void InitLog(string completeLogFile) { _filePath = completeLogFile; var hierarchy = (log4net.Repository.Hierarchy.Hierarchy)LogManager.GetRepository(); hierarchy.Root.RemoveAllAppenders(); var pl = new log4net.Layout.PatternLayout { ConversionPattern = DefaultConversionPatern }; pl.ActivateOptions(); var fileAppender = new RollingFileAppender() { AppendToFile = true, LockingModel = new FileAppender.MinimalLock(), File = _filePath, Layout = pl, }; fileAppender.MaxFileSize = 10 * 1024 * 1024; fileAppender.RollingStyle = RollingFileAppender.RollingMode.Size; fileAppender.MaxSizeRollBackups = 5; fileAppender.ActivateOptions(); BasicConfigurator.Configure(fileAppender); _logger = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); }
public void Configure() { if (_configured) return; lock (LockObject) { if (_configured) return; var logger = (Hierarchy) LogManager.CreateRepository(RepositoryName); logger.Root.RemoveAllAppenders(); logger.Root.Level = GetLevel(); var layout = new log4net.Layout.PatternLayout { ConversionPattern = "%date [%thread] %-5level %logger [%property] - %message%newline" }; layout.ActivateOptions(); var fileAppender = new FileAppender { AppendToFile = true, LockingModel = new FileAppender.MinimalLock(), File = _configuration.InternalLogLocation, Layout = layout, ImmediateFlush = true }; fileAppender.ActivateOptions(); BasicConfigurator.Configure(logger, fileAppender); _configured = true; } }
public static void InitLog(string completeLogFile, bool externalConsole) { _filePath = completeLogFile; var hierarchy = (log4net.Repository.Hierarchy.Hierarchy)LogManager.GetRepository(); hierarchy.Root.RemoveAllAppenders(); var pl = new log4net.Layout.PatternLayout { ConversionPattern = DefaultConversionPatern }; pl.ActivateOptions(); var fileAppender = new log4net.Appender.FileAppender { AppendToFile = true, LockingModel = new log4net.Appender.FileAppender.MinimalLock(), File = _filePath, Layout = pl }; fileAppender.ActivateOptions(); log4net.Config.BasicConfigurator.Configure(fileAppender); _logger = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); if (externalConsole) { AddLogToConsole(false); } }
public Log4NetLogFactory(LogFileSettings settings) { var patternLayout = new log4net.Layout.PatternLayout( "%date [%thread] %level %logger - %message%newline"); patternLayout.ActivateOptions(); RollingFileAppender appender = new RollingFileAppender { Name = "rolling-appender", File = Path.Combine(settings.DirectoryPath, settings.NamePrefix + ".log"), AppendToFile = true, MaxSizeRollBackups = 10, RollingStyle = RollingFileAppender.RollingMode.Date, Layout = patternLayout, LockingModel = new FileAppender.MinimalLock() }; appender.ActivateOptions(); log4net.Config.BasicConfigurator.Configure(appender); Hierarchy h = (Hierarchy)LogManager.GetRepository(); Logger rootLogger = h.Root; rootLogger.Level = h.LevelMap[ConvertLogLevel(settings.Level).ToString().ToUpper()]; }
/// <summary> /// Create File appender, This appender is responsible to write stream of data when invoked, in /// our case, this appender is handeled my the Bufferappender /// </summary> /// <param name="cacheName">Name of the file appender</param> /// <param name="fileName">Filename to which is to write logs</param> /// <returns>returns the created appender</returns> private static log4net.Appender.IAppender CreateRollingFileAppender(string cacheName, string fileName) { log4net.Appender.RollingFileAppender appender = new log4net.Appender.RollingFileAppender(); appender.Name = "RollingFileAppender" + cacheName; appender.File = fileName; //doesnt matter since all files are created with a new name appender.AppendToFile = false; appender.RollingStyle = RollingFileAppender.RollingMode.Size; appender.MaximumFileSize = "5MB"; appender.MaxSizeRollBackups = -1; //Threshold is maintained by the logger rather than the appenders appender.Threshold = log4net.Core.Level.All; log4net.Layout.PatternLayout layout = new log4net.Layout.PatternLayout(); //DateSpace == 23 || appdomain == 25 || Longest thread.Name == 34 || Leve max length == 5 || layout.ConversionPattern = "%-27date{ISO8601}" + "\t%-45.42appdomain" + "\t%-35logger" + "\t%-42thread" + "\t%-9level" + "\t%message" + "%newline"; layout.Header = "TIMESTAMP \tAPPDOMAIN \tLOGGERNAME \tTHREADNAME \tLEVEL \tMESSAGE\r\n"; layout.Footer = "END \n"; layout.ActivateOptions(); appender.Layout = layout; appender.ActivateOptions(); return(appender); }
public Log4NetLogFactory(LogFileSettings settings) { var patternLayout = new log4net.Layout.PatternLayout( "%date [%thread] %level %logger - %message%newline"); patternLayout.ActivateOptions(); RollingFileAppender appender = new RollingFileAppender { Name = "rolling-appender", File = Path.Combine(settings.DirectoryPath, settings.NamePrefix + ".log"), AppendToFile = true, MaxSizeRollBackups = 10, RollingStyle = RollingFileAppender.RollingMode.Date, Layout = patternLayout, LockingModel = new FileAppender.MinimalLock() }; appender.ActivateOptions(); log4net.Config.BasicConfigurator.Configure(appender); Hierarchy h = (Hierarchy)LogManager.GetRepository(); Logger rootLogger = h.Root; rootLogger.Level = h.LevelMap[ConvertLogLevel(settings.Level).ToString().ToUpper()]; }
public void AddAppender(string appenderName, ILogger wLogger) { if (!ConfigurationManager.AppSettings.AllKeys.Contains("BackupPath")) { throw new Exception("Parameter 'BackupPath' is mandatory"); } string filename = ConfigurationManager.AppSettings["BackupPath"].ToString() + "\\" + appenderName + ".sql"; log4net.Repository.Hierarchy.Logger l = (log4net.Repository.Hierarchy.Logger)wLogger; log4net.Appender.IAppender hasAppender = l.GetAppender(appenderName); if (hasAppender == null) { log4net.Appender.RollingFileAppender appender = new log4net.Appender.RollingFileAppender(); appender.DatePattern = "yyyyMMdd"; appender.RollingStyle = log4net.Appender.RollingFileAppender.RollingMode.Date; appender.AppendToFile = true; appender.File = filename; appender.StaticLogFileName = true; appender.Name = appenderName; log4net.Layout.PatternLayout layout = new log4net.Layout.PatternLayout(); layout.ConversionPattern = "%date [%thread] %-5level %logger - %message%newline"; layout.ActivateOptions(); appender.Layout = layout; appender.ActivateOptions(); l.AddAppender(appender); } }
/// <summary> /// Create File appender, This appender is responsible to write stream of data when invoked, in /// our case, this appender is handeled my the Bufferappender /// </summary> /// <param name="cacheName">Name of the file appender</param> /// <param name="fileName">Filename to which is to write logs</param> /// <returns>returns the created appender</returns> private log4net.Appender.IAppender CreateRollingFileAppender(string fileName) { log4net.Appender.RollingFileAppender appender = new log4net.Appender.RollingFileAppender(); appender.Name = "RollingFileAppender" + _loggerName; appender.File = fileName; //doesnt matter since all files are created with a new name appender.AppendToFile = true; appender.RollingStyle = RollingFileAppender.RollingMode.Size; appender.MaximumFileSize = "5MB"; appender.MaxSizeRollBackups = -1; appender.Threshold = log4net.Core.Level.All; log4net.Layout.PatternLayout layout = new log4net.Layout.PatternLayout(); layout.ConversionPattern = "%-27date{ISO8601}" + "\t%-45.42appdomain" + "\t%-43logger" + "\t%-42thread" + "\t%-9level" + "\t%message" + "%newline"; layout.Header = "TIMESTAMP \tAPPDOMAIN \tLOGGERNAME \tTHREADNAME \tLEVEL \tMESSAGE\r\n"; layout.Footer = "END \n"; layout.ActivateOptions(); appender.Layout = layout; appender.ActivateOptions(); return(appender); }
/// <summary> /// Adds the email logging appender. /// </summary> public static void ConfigureEmailLoggingAppender() { var hier = (log4net.Repository.Hierarchy.Hierarchy)LogManager.GetRepository(); if (hier == null) return; var appender = (SmtpAppender)hier.Root.GetAppender("SmtpAppender") ?? new SmtpAppender(); appender.Name = "SmtpAppender"; appender.From = HostSettingManager.Get(HostSettingNames.HostEmailAddress, string.Empty); appender.To = HostSettingManager.Get(HostSettingNames.ErrorLoggingEmailAddress, string.Empty); appender.Subject = "BugNET Error"; appender.SmtpHost = HostSettingManager.SmtpServer; appender.Priority = System.Net.Mail.MailPriority.High; appender.Threshold = log4net.Core.Level.Error; appender.BufferSize = 0; //create patternlayout var patternLayout = new log4net.Layout.PatternLayout("%newline%date [%thread] %-5level %logger [%property{NDC}] - %message%newline%newline%newline"); patternLayout.ActivateOptions(); appender.Layout = patternLayout; appender.ActivateOptions(); //add appender to root logger hier.Root.AddAppender(appender); }
public static void SetupTcp() { var layout = new log4net.Layout.PatternLayout(); var appender = new TcpAppender { RemotePort = 5140, Layout = layout }; layout.ActivateOptions(); appender.ActivateOptions(); var layout2 = new log4net.Layout.PatternLayout(); var appender2 = new TcpAppender { RemotePort = 5140, Layout = layout2 }; layout2.ActivateOptions(); appender2.ActivateOptions(); var layout3 = new log4net.Layout.PatternLayout(); var appender3 = new TcpAppender { RemotePort = 5140, Layout = layout3 }; layout3.ActivateOptions(); appender3.ActivateOptions(); log4net.Config.BasicConfigurator.Configure(appender, appender2, appender3); }
public SplunkHttpEventCollectorTests() { // Step 1. Create repository object Hierarchy hierarchy = (Hierarchy)LogManager.GetRepository(); // Step 2. Create appender var splunkHttpEventCollector = new SplunkHttpEventCollector(); // Step 3. Set appender properties splunkHttpEventCollector.ServerUrl = "http://localhost:8088"; splunkHttpEventCollector.Token = "7856e3dd-b7d2-4b8f-b88e-61146264b727"; splunkHttpEventCollector.RetriesOnError = 0; log4net.Layout.PatternLayout patternLayout = new log4net.Layout.PatternLayout { ConversionPattern = "%message" }; patternLayout.ActivateOptions(); splunkHttpEventCollector.Layout = patternLayout; splunkHttpEventCollector.ActivateOptions(); // Step 4. Add appender to logger hierarchy.Root.AddAppender(splunkHttpEventCollector); hierarchy.Threshold = Level.All; hierarchy.Configured = true; // Step 5. Create logger _logger = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); }
/// <summary> /// Configures the logging subsystem. /// </summary> private static void ConfigureLogging() { var layout = new log4net.Layout.PatternLayout(LogPattern); layout.ActivateOptions(); // Create a list of appenders var appenders = new List <AppenderSkeleton>(); var consoleAppender = new ManagedColoredConsoleAppender() { Layout = layout, Threshold = Level.Debug, Target = "Console.Out" }; consoleAppender.AddMapping(new ManagedColoredConsoleAppender.LevelColors() { Level = Level.Info, ForeColor = ConsoleColor.Gray }); consoleAppender.AddMapping(new ManagedColoredConsoleAppender.LevelColors() { Level = Level.Debug, ForeColor = ConsoleColor.Green }); consoleAppender.AddMapping(new ManagedColoredConsoleAppender.LevelColors() { Level = Level.Warn, ForeColor = ConsoleColor.DarkYellow }); consoleAppender.AddMapping(new ManagedColoredConsoleAppender.LevelColors() { Level = Level.Error, ForeColor = ConsoleColor.Red }); appenders.Add(consoleAppender); // Configure the appenders in the list based on the build. foreach (var appender in appenders) { appender.AddFilter(new log4net.Filter.LevelRangeFilter() { #if DEBUG LevelMin = Level.Debug, #else LevelMin = Level.Info, #endif LevelMax = Level.Fatal }); appender.ActivateOptions(); } // Finally, perform the log configuration log4net.Config.BasicConfigurator.Configure(appenders.ToArray()); }
private static void initializeLogging() { var thisFilename = Path.GetFileNameWithoutExtension(Assembly.GetExecutingAssembly().CodeBase); var logFilename = Path.Combine(Path.GetTempPath(), Path.ChangeExtension(thisFilename, "txt")); var layout = new log4net.Layout.PatternLayout("%d [%t]%-5p %c [%x] - %m%n"); layout.ActivateOptions(); log4net.Config.BasicConfigurator.Configure( new log4net.Appender.FileAppender( layout, logFilename)); }
// static constructor for log4net static PqsqlConnectionPool() { log4net.Layout.PatternLayout layout = new log4net.Layout.PatternLayout("%date{ISO8601} [%thread] %-5level %logger - %message%newline"); log4net.Appender.RollingFileAppender appender = new log4net.Appender.RollingFileAppender { File = "c:\\windows\\temp\\pqsql_connection_pool.log", Layout = layout }; layout.ActivateOptions(); appender.ActivateOptions(); log4net.Config.BasicConfigurator.Configure(appender); mLogger = log4net.LogManager.GetLogger(typeof(PqsqlConnectionPool)); }
protected void BeginStartupInformationLog() { _currentLayout = LogManager.GetRepository().GetAppenders().OfType <log4net.Appender.RollingFileAppender>().First().Layout; var appenders = LogManager.GetRepository().GetAppenders(); foreach (var rollingFileAppender in appenders.OfType <log4net.Appender.RollingFileAppender>()) { var layout = new log4net.Layout.PatternLayout("%message%newline"); rollingFileAppender.Layout = layout; layout.ActivateOptions(); } }
private static void initializeLogging() { var thisFilename = Path.GetFileNameWithoutExtension(Assembly.GetExecutingAssembly().CodeBase); var logFilename = Path.Combine(Path.GetTempPath(), Path.ChangeExtension(thisFilename, "txt")); var layout = new log4net.Layout.PatternLayout("%d [%t]%-5p %c [%x] - %m%n"); layout.ActivateOptions(); log4net.Config.BasicConfigurator.Configure( new log4net.Appender.FileAppender( layout, logFilename)); }
void StartLogging() { //Setup log4net for the current domain log4net.Appender.RollingFileAppender appender = new log4net.Appender.RollingFileAppender(); log4net.Layout.PatternLayout layout = new log4net.Layout.PatternLayout("%date [%thread] %-5level %logger - %message%newline"); appender.Layout = layout; appender.File = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"log\servicebrowser.log"); appender.AppendToFile = true; appender.RollingStyle = log4net.Appender.RollingFileAppender.RollingMode.Date; appender.DatePattern = "yyyyMMdd"; layout.ActivateOptions(); appender.ActivateOptions(); log4net.Config.BasicConfigurator.Configure(appender); }
/// <summary> /// /// </summary> private void ConfigureLogger() { var repos = LogManager.GetAllRepositories(); ILoggerRepository repo = null; foreach (var r in repos) { if (r.Name == Run.RunName) { repo = r; } } if (repo == null) { repo = LogManager.CreateRepository(Run.RunName); } var logger = repo.GetLogger(Run.RunName); var ilogger = repo.GetLogger(Run.RunName); var appender = new log4net.Appender.RollingFileAppender(); appender.Name = "RollingFileAppender"; appender.File = Path.Combine(Run.RunDirectory, "XTMF.Console.log"); appender.StaticLogFileName = true; appender.AppendToFile = false; appender.RollingStyle = log4net.Appender.RollingFileAppender.RollingMode.Once; appender.MaxSizeRollBackups = 10; appender.MaximumFileSize = "10MB"; appender.PreserveLogFileNameExtension = true; var layout = new log4net.Layout.PatternLayout() { ConversionPattern = "%date %-5level %logger - %message%newline" }; appender.Layout = layout; layout.ActivateOptions(); _consoleAppener = new ConsoleOutputAppender() { Layout = layout }; //Let log4net configure itself based on the values provided appender.ActivateOptions(); log4net.Config.BasicConfigurator.Configure(repo, appender, _consoleAppener); iLog = LogManager.GetLogger(Run.RunName, Run.RunName); }
private void ConstruirLog() { var loggerName = typeof(Log).FullName; var logger = (log4net.Repository.Hierarchy.Logger)LogManager.GetRepository().GetLogger(loggerName); //Add the default log appender if none exist if (logger.Appenders.Count == 0) { var ruta = _aplicacionNombre; string directoryName = String.Format(@"{0}\", ruta); //If the directory doesn't exist then create it if (!Directory.Exists(directoryName)) { Directory.CreateDirectory(directoryName); } var fileName = Path.Combine(directoryName, "log-"); //Create the rolling file appender var appender = new RollingFileAppender { Name = "RollingFileAppender", File = fileName, StaticLogFileName = false, AppendToFile = true, CountDirection = -1, DatePattern = "yyyyMMdd'.txt'", RollingStyle = RollingFileAppender.RollingMode.Date, MaxSizeRollBackups = 0, MaximumFileSize = "7MB" }; //Configure the layout of the trace message write var layout = new log4net.Layout.PatternLayout { ConversionPattern = "[%-5p] | [%date] | [%P{Method}] | [%P{Class}] | [%m]%n" }; appender.Layout = layout; layout.ActivateOptions(); //Let log4net configure itself based on the values provided appender.ActivateOptions(); log4net.Config.BasicConfigurator.Configure(appender); } _logger = LogManager.GetLogger(loggerName); }
public void NamedPatternConverterWithPrecision1ShouldStripLeadingStuffIfPresent() { StringAppender stringAppender = new StringAppender(); log4net.Layout.PatternLayout layout = new log4net.Layout.PatternLayout(); layout.AddConverter("message-as-name", typeof(MessageAsNamePatternConverter)); layout.ConversionPattern = "%message-as-name{1}"; layout.ActivateOptions(); stringAppender.Layout = layout; ILoggerRepository rep = LogManager.CreateRepository(Guid.NewGuid().ToString()); BasicConfigurator.Configure(rep, stringAppender); ILog log1 = LogManager.GetLogger(rep.Name, "TestAddingCustomPattern"); log1.Info("NoDots"); Assert.AreEqual("NoDots", stringAppender.GetString(), "%message-as-name not registered"); stringAppender.Reset(); log1.Info("One.Dot"); Assert.AreEqual("Dot", stringAppender.GetString(), "%message-as-name not registered"); stringAppender.Reset(); log1.Info("Tw.o.Dots"); Assert.AreEqual("Dots", stringAppender.GetString(), "%message-as-name not registered"); stringAppender.Reset(); //This behaviour differs from the log4net source. log1.Info("TrailingDot."); Assert.AreEqual("TrailingDot", stringAppender.GetString(), "%message-as-name not registered"); stringAppender.Reset(); log1.Info(".LeadingDot"); Assert.AreEqual("LeadingDot", stringAppender.GetString(), "%message-as-name not registered"); stringAppender.Reset(); // empty string and other evil combinations as tests for of-by-one mistakes in index calculations log1.Info(string.Empty); Assert.AreEqual(string.Empty, stringAppender.GetString(), "%message-as-name not registered"); stringAppender.Reset(); log1.Info("x"); Assert.AreEqual("x", stringAppender.GetString(), "%message-as-name not registered"); stringAppender.Reset(); log1.Info("."); Assert.AreEqual(".", stringAppender.GetString(), "%message-as-name not registered"); stringAppender.Reset(); }
public static void Configure() { if (isConfigured) return; var loggerName = "SBDIL"; var logger = (log4net.Repository.Hierarchy.Logger)log4net.LogManager.GetRepository().GetLogger(loggerName); var ilogger = log4net.LogManager.GetRepository().GetLogger(loggerName); //Add the default log appender if none exist if(logger.Appenders.Count == 0) { var directoryName = "C:\\BarkLogs"; //If the directory doesn't exist then create it if(!Directory.Exists(directoryName)) Directory.CreateDirectory(directoryName); var fileName = Path.Combine(directoryName, DateTime.Now.ToString("yyyyMMddTHHmmss") + ".txt"); //Create the rolling file appender var appender = new log4net.Appender.RollingFileAppender(); appender.Name = "RollingFileAppender"; appender.File = fileName; appender.StaticLogFileName = true; appender.AppendToFile = false; appender.RollingStyle = log4net.Appender.RollingFileAppender.RollingMode.Size; appender.MaxSizeRollBackups = 10; appender.MaximumFileSize = "10MB"; appender.PreserveLogFileNameExtension = true; //Configure the layout of the trace message write var layout = new log4net.Layout.PatternLayout() { ConversionPattern = "%date{MM/dd/yyyy hh:mm:ss.fff} - %message%newline" }; appender.Layout = layout; layout.ActivateOptions(); //Let log4net configure itself based on the values provided appender.ActivateOptions(); log4net.Config.BasicConfigurator.Configure(appender); } iLog = LogManager.GetLogger(loggerName); isConfigured = true; }
public static ILog CreateFileLogger(String name, String path) { ///LevelRangeFilter log4net.Filter.LevelRangeFilter levfilter = new log4net.Filter.LevelRangeFilter(); levfilter.LevelMax = log4net.Core.Level.Fatal; levfilter.LevelMin = log4net.Core.Level.Error; levfilter.ActivateOptions(); //Appender1 log4net.Appender.FileAppender appender1 = new log4net.Appender.FileAppender(); appender1.AppendToFile = true; appender1.File = path + name + ".log"; appender1.ImmediateFlush = true; appender1.LockingModel = new log4net.Appender.FileAppender.MinimalLock(); appender1.Name = name + "FileAppender"; appender1.AddFilter(levfilter); //Appender2 //log4net.Appender.ConsoleAppender appender2 = new log4net.Appender.ConsoleAppender(); //appender2.Name = name + "ConsoleAppender"; //appender2.AddFilter(levfilter); log4net.Layout.PatternLayout layout = new log4net.Layout.PatternLayout("%date [%thread] %-5level - %message%newline"); layout.ActivateOptions(); appender1.Layout = layout; appender1.ActivateOptions(); //appender2.Layout = layout; //appender2.ActivateOptions(); //log4net.Repository.ILoggerRepository repository = null; //log4net.Repository.ILoggerRepository[] repositories = log4net.LogManager.GetAllRepositories(); //if (repositories != null) // repository = repositories.FirstOrDefault(x => x.Name == "DynamicRepository"); //if (repository == null) // repository = log4net.LogManager.CreateRepository("DynamicRepository"); log4net.Config.BasicConfigurator.Configure(appender1); //log4net.Config.BasicConfigurator.Configure(repository, appender1); //log4net.Config.BasicConfigurator.Configure(repository, appender2); //((log4net.Repository.Hierarchy.Hierarchy)repository).Root.Level = log4net.Core.Level.Info; ((log4net.Repository.Hierarchy.Hierarchy)log4net.LogManager.GetRepository()).Root.AddAppender(appender1); ILog logger = log4net.LogManager.GetLogger(name); return(logger); }
public static void SetConfig(string root) { log4net.Appender.FileAppender fAppender = new log4net.Appender.FileAppender(); log4net.Layout.PatternLayout layout = new log4net.Layout.PatternLayout { ConversionPattern = "[%date] %thread -- %-5level -- %logger [%M] -- %message%newline" }; layout.ActivateOptions(); fAppender.File = System.IO.Path.Combine(root, @"Log\HRUT.log"); fAppender.Layout = layout; fAppender.AppendToFile = true; fAppender.ActivateOptions(); log4net.Config.BasicConfigurator.Configure(fAppender); }
public static void SetupFileAppender(string name, string fileName, Level threshold) { FileAppender appender = (FileAppender)FindAppender(name); //appender.Name = name; appender.File = fileName; appender.AppendToFile = true; appender.Threshold = threshold; log4net.Layout.PatternLayout layout = new log4net.Layout.PatternLayout(); layout.ConversionPattern = "%date [%thread] %-5level %logger - %message%newline"; layout.ActivateOptions(); appender.Layout = layout; appender.ActivateOptions(); }
/// <summary> /// Create File appender, This appender is responsible to write stream of data when invoked, in /// our case, this appender is handeled my the Bufferappender /// </summary> /// <param name="cacheName">Name of the file appender</param> /// <param name="fileName">Filename to which is to write logs</param> /// <returns>returns the created appender</returns> private log4net.Appender.IAppender CreateRollingFileAppender(string fileName, bool apiLogs, bool eventLogs) { log4net.Appender.RollingFileAppender appender = new log4net.Appender.RollingFileAppender(); appender.Name = "RollingFileAppender" + _loggerName; appender.File = fileName; //doesnt matter since all files are created with a new name appender.AppendToFile = true; appender.RollingStyle = RollingFileAppender.RollingMode.Size; appender.MaximumFileSize = "5MB"; appender.MaxSizeRollBackups = -1; appender.Threshold = log4net.Core.Level.All; log4net.Layout.PatternLayout layout = new log4net.Layout.PatternLayout(); if (!apiLogs && !eventLogs) { layout.ConversionPattern = "%-27date{ISO8601}" + "\t%-45.42appdomain" + "\t%-43logger" + "\t%-42thread" + "\t%-9level" + "\t%message" + "%newline"; layout.Header = "TIMESTAMP \tAPPDOMAIN \tLOGGERNAME \tTHREADNAME \tLEVEL \tMESSAGE\r\n"; } else if (apiLogs) { appender.Name = LoggerNames.APILogs.ToString().ToLower() + "_" + appender.Name; layout.ConversionPattern = "%message" + "%newline"; layout.Header = "TIMESTAMP \t\t SERVER CLIENTIP ProcessID \tExecutionTime \tMethod \t\t\tParameters Exception\r\n"; } else if (eventLogs) { layout.ConversionPattern = "%message" + "%newline"; appender.LockingModel = new log4net.Appender.FileAppender.MinimalLock(); if (!File.Exists(fileName)) { layout.Header = "TIMESTAMP SOURCE EVENTID LEVEL MESSAGE\r\n"; } } layout.Footer = "END \n"; layout.ActivateOptions(); appender.Layout = layout; appender.ActivateOptions(); return(appender); }
/// <summary> /// This method is used to create the appender /// </summary> /// <param name="fileName"></param> /// <param name="appenderName"></param> /// <returns></returns> private log4net.Appender.FileAppender CreateAppender(string fileName, string appenderName) { //log4net.Appender.FileAppender fileAppender = new log4net.Appender.FileAppender(); log4net.Appender.RollingFileAppender fileAppender = new log4net.Appender.RollingFileAppender(); log4net.Layout.PatternLayout patternLayOut = new log4net.Layout.PatternLayout(); patternLayOut.Header = ""; //System.Environment.NewLine + "---Starts Here---" + System.Environment.NewLine; patternLayOut.Footer = ""; // patternLayOut.ConversionPattern = "%d %m%n"; //patternLayOut.ConversionPattern = ""; patternLayOut.ActivateOptions(); string path = AppDomain.CurrentDomain.BaseDirectory + @"\Log"; //System.Windows.Forms.Application.StartupPath + @"\Log"; System.IO.DirectoryInfo info = new DirectoryInfo(path); if (!info.Exists) { info.Create(); } string[] file = fileName.Split('\\'); fileAppender.Layout = patternLayOut; fileAppender.AppendToFile = true; fileAppender.MaximumFileSize = Parameter.LOGGING_FILE_SIZE.Trim().Equals("") ? DefaultMaximumFileSize : Parameter.LOGGING_FILE_SIZE; fileAppender.MaxSizeRollBackups = 10; fileAppender.StaticLogFileName = true; fileAppender.RollingStyle = log4net.Appender.RollingFileAppender.RollingMode.Size; //fileAppender.DatePattern = ".yyyyMMdd'.log'"; //fileAppender.File = path + "\\" + file[file.Length - 1].Split('.')[0]; fileAppender.File = path + "\\" + file[file.Length - 1]; fileAppender.Name = appenderName; fileAppender.LockingModel = new log4net.Appender.FileAppender.MinimalLock(); fileAppender.ActivateOptions(); return(fileAppender); }
public static void AddLogToConsole(bool basicConfig) { AllocConsole(); var appender = new log4net.Appender.ConsoleAppender(); var layout = new log4net.Layout.PatternLayout { ConversionPattern = DefaultConversionPatern, Header = "Time;Level;Description;" }; layout.ActivateOptions(); appender.Layout = layout; appender.ActivateOptions(); if (basicConfig) log4net.Config.BasicConfigurator.Configure(appender); else ((log4net.Repository.Hierarchy.Hierarchy)LogManager.GetRepository()).Root.AddAppender(appender); }
public void NamedPatternConverterWithPrecision1ShouldStripLeadingStuffIfPresent() { StringAppender stringAppender = new StringAppender(); log4net.Layout.PatternLayout layout = new log4net.Layout.PatternLayout(); layout.AddConverter("message-as-name", typeof(MessageAsNamePatternConverter)); layout.ConversionPattern = "%message-as-name{1}"; layout.ActivateOptions(); stringAppender.Layout = layout; ILoggerRepository rep = LogManager.CreateRepository(Guid.NewGuid().ToString()); BasicConfigurator.Configure(rep, stringAppender); ILog log1 = LogManager.GetLogger(rep.Name, "TestAddingCustomPattern"); log1.Info("NoDots"); Assert.AreEqual("NoDots", stringAppender.GetString(), "%message-as-name not registered"); stringAppender.Reset(); log1.Info("One.Dot"); Assert.AreEqual("Dot", stringAppender.GetString(), "%message-as-name not registered"); stringAppender.Reset(); log1.Info("Tw.o.Dots"); Assert.AreEqual("Dots", stringAppender.GetString(), "%message-as-name not registered"); stringAppender.Reset(); //This behaviour differs from the log4net source. log1.Info("TrailingDot."); Assert.AreEqual("TrailingDot", stringAppender.GetString(), "%message-as-name not registered"); stringAppender.Reset(); log1.Info(".LeadingDot"); Assert.AreEqual("LeadingDot", stringAppender.GetString(), "%message-as-name not registered"); stringAppender.Reset(); // empty string and other evil combinations as tests for of-by-one mistakes in index calculations log1.Info(string.Empty); Assert.AreEqual(string.Empty, stringAppender.GetString(), "%message-as-name not registered"); stringAppender.Reset(); log1.Info("x"); Assert.AreEqual("x", stringAppender.GetString(), "%message-as-name not registered"); stringAppender.Reset(); log1.Info("."); Assert.AreEqual(".", stringAppender.GetString(), "%message-as-name not registered"); stringAppender.Reset(); }
/// <summary> /// Adds the email logging appender. /// </summary> public static void ConfigureEmailLoggingAppender() { var hier = (log4net.Repository.Hierarchy.Hierarchy)LogManager.GetRepository(); if (hier == null) { return; } var appender = (SmtpAppender)hier.Root.GetAppender("SmtpAppender") ?? new SmtpAppender(); appender.Name = "SmtpAppender"; appender.From = HostSettingManager.Get(HostSettingNames.HostEmailAddress, string.Empty); appender.To = HostSettingManager.Get(HostSettingNames.ErrorLoggingEmailAddress, string.Empty); appender.Subject = "BugNET Error"; appender.SmtpHost = HostSettingManager.SmtpServer; appender.Port = int.Parse(HostSettingManager.Get(HostSettingNames.SMTPPort)); appender.Authentication = SmtpAppender.SmtpAuthentication.None; appender.Username = string.Empty; appender.Password = string.Empty; appender.EnableSsl = Boolean.Parse(HostSettingManager.Get(HostSettingNames.SMTPUseSSL)); if (Convert.ToBoolean(HostSettingManager.Get(HostSettingNames.SMTPAuthentication))) { appender.Authentication = SmtpAppender.SmtpAuthentication.Basic; appender.Username = String.Format("{0}\\{1}", HostSettingManager.Get(HostSettingNames.SMTPDomain, string.Empty), HostSettingManager.Get(HostSettingNames.SMTPUsername, string.Empty)); appender.Password = HostSettingManager.Get(HostSettingNames.SMTPPassword, string.Empty); } appender.Priority = System.Net.Mail.MailPriority.High; appender.Threshold = log4net.Core.Level.Error; appender.BufferSize = 0; //create patternlayout var patternLayout = new log4net.Layout.PatternLayout("%newline%date [%thread] %-5level %logger [%property{NDC}] - %message%newline%newline%newline"); patternLayout.ActivateOptions(); appender.Layout = patternLayout; appender.ActivateOptions(); //add appender to root logger hier.Root.AddAppender(appender); }
public static void ConfigLogging() { FileAppender fileAppender = new FileAppender(); fileAppender.AppendToFile = true; fileAppender.LockingModel = new FileAppender.MinimalLock(); fileAppender.File = Params.logFile; log4net.Layout.PatternLayout pl = new log4net.Layout.PatternLayout(); //d:timestamp t:thread p:level c:Class name m:message n:new line //pl.ConversionPattern = "%d [%2%t] %-5p [%-10c] %m%n"; pl.ConversionPattern = "%d %-5p [%-10c] %m%n"; pl.ActivateOptions(); fileAppender.Layout = pl; fileAppender.ActivateOptions(); log4net.Config.BasicConfigurator.Configure(fileAppender); }
public static log4net.Appender.IAppender CreateFileAppender(string name, string fileName) { log4net.Appender.FileAppender appender = new log4net.Appender.FileAppender(); appender.Name = name; appender.File = fileName; appender.AppendToFile = true; log4net.Layout.PatternLayout layout = new log4net.Layout.PatternLayout(); //layout.ConversionPattern = "%d [%t] %-5p %c [%x] - %m%n"; layout.ActivateOptions(); appender.Layout = layout; appender.ActivateOptions(); return(appender); }
// Create a new file appender public static log4net.Appender.IAppender CreateFileAppender(string name, string fileName) { log4net.Appender.FileAppender appender = new log4net.Appender.FileAppender(); appender.Name = name; appender.File = fileName; appender.AppendToFile = true; log4net.Layout.PatternLayout layout = new log4net.Layout.PatternLayout(); layout.ConversionPattern = "%d [%t] %-5p %c [%x] - %m%n"; layout.ActivateOptions(); appender.Layout = layout; appender.ActivateOptions(); return appender; }
private static ILog getDefaultLogger(String name) { ILog r = LogManager.GetCurrentLoggers().SingleOrDefault(x => x.Logger.Name == name); if (r != null) { return(r); } Hierarchy hierarchy = (Hierarchy)r; log4net.Appender.ColoredConsoleAppender appender = new log4net.Appender.ColoredConsoleAppender(); appender.Name = name; log4net.Layout.PatternLayout layout = new log4net.Layout.PatternLayout(); layout.ConversionPattern = "%-4timestamp [%thread] %-5level %logger %ndc - %message%newline"; layout.ActivateOptions(); appender.Layout = layout; log4net.Filter.LevelRangeFilter filter = new log4net.Filter.LevelRangeFilter(); filter.LevelMax = log4net.Core.Level.Fatal; filter.LevelMin = log4net.Core.Level.Debug; appender.AddFilter(filter); appender.ActivateOptions(); hierarchy.Root.AddAppender(appender); hierarchy.Root.Level = log4net.Core.Level.All; hierarchy.Configured = true; DummyLogger dummyILogger = new DummyLogger(name); dummyILogger.Hierarchy = hierarchy; dummyILogger.Level = log4net.Core.Level.All; dummyILogger.AddAppender(appender); return(new log4net.Core.LogImpl(dummyILogger));; }
private static void AddConsoleAppender() { log4net.Layout.PatternLayout layout = new log4net.Layout.PatternLayout { ConversionPattern = "%message%newline" }; layout.ActivateOptions(); var appender = new log4net.Appender.ManagedColoredConsoleAppender() { Threshold = Level.All }; appender.Name = "Console"; appender.Layout = layout; appender.ActivateOptions(); var l = (log4net.Repository.Hierarchy.Logger)log.Logger; l.AddAppender(appender); l.Repository.Configured = true; }
private IAppender CreateRollingFileAppender(string name, string fileName) { log4net.Appender.RollingFileAppender appender = new RollingFileAppender(); appender.Name = name; appender.File = fileName; appender.AppendToFile = true; appender.LockingModel = new FileAppender.MinimalLock(); //appender.ImmediateFlush = true; appender.RollingStyle = RollingFileAppender.RollingMode.Date; appender.StaticLogFileName = true; log4net.Layout.PatternLayout layout = new log4net.Layout.PatternLayout(); layout.ConversionPattern = "%d [%t] %-5p %c [%x] - %m%n"; layout.ActivateOptions(); appender.Encoding = Encoding.UTF8; appender.Layout = layout; appender.ActivateOptions(); return(appender); }
public static void AddLogToConsole(bool basicConfig) { AllocConsole(); var appender = new log4net.Appender.ConsoleAppender(); var layout = new log4net.Layout.PatternLayout { ConversionPattern = DefaultConversionPatern, Header = "Time;Level;Description;" }; layout.ActivateOptions(); appender.Layout = layout; appender.ActivateOptions(); if (basicConfig) { log4net.Config.BasicConfigurator.Configure(appender); } else { ((log4net.Repository.Hierarchy.Hierarchy)LogManager.GetRepository()).Root.AddAppender(appender); } }
private static RollingFileAppender GetNewFileApender() { var appender = new RollingFileAppender { Name = "Ecoscan.Log", File = "Log.txt", AppendToFile = true, MaxSizeRollBackups = 10, MaximumFileSize = "10MB", StaticLogFileName = true, RollingStyle = RollingFileAppender.RollingMode.Size, DatePattern = "yyyy.MM.dd" }; var layout = new log4net.Layout.PatternLayout("%d %p %m%n"); appender.Layout = layout; layout.ActivateOptions(); appender.ActivateOptions(); return(appender); }
public static void InitializeLog4Net() { var layout = new log4net.Layout.PatternLayout() { ConversionPattern = "时间:%d %n级别:%level %n类名:%c%n文件:%F 第%L行%n日志内容:%m%n-----------------------------------------%n%n" }; var appender = new log4net.Appender.RollingFileAppender() { AppendToFile = true, LockingModel = new log4net.Appender.FileAppender.MinimalLock(), StaticLogFileName = false, File = System.Configuration.ConfigurationManager.AppSettings["LogFolder"] + "log_PingAn_", RollingStyle = log4net.Appender.RollingFileAppender.RollingMode.Date, DatePattern = "yyyy-MM-dd\".log\"", Layout = layout }; layout.ActivateOptions(); appender.ActivateOptions(); log4net.Config.BasicConfigurator.Configure(appender); //log4net.Config.XmlConfigurator.Configure(); }
private static void ReconfigureLog() { var hier = log4net.LogManager.GetRepository() as Hierarchy; if (hier != null) { // Get appender var jungoAppender = (RollingFileAppender)hier.GetAppenders() .FirstOrDefault( appender => appender.Name.Equals("JungoAppender", StringComparison.InvariantCultureIgnoreCase)); if (jungoAppender != null) { var config = ConfigLoader.Get<JungoLoggerLog4NetConfig>(); _configuredDelimiter = config.Delimiter; _logLevelsIncluded = config.LogLevelsIncluded; var delimiter = _configuredDelimiter == JungoLoggerLog4NetDelimiter.Comma ? "," : "\t"; var header = new StringBuilder("datetime"); var logFormatBuilder = new StringBuilder("{0}"); foreach (var column in config.Columns) { var colNum = -1; switch (column.FieldName) { case "Order": colNum = 1; break; case "LogType": colNum = 2; break; case "RequestType": colNum = 3; break; case "TimeElapsed": colNum = 4; break; case "Host": colNum = 5; break; case "Uri": colNum = 6; break; case "RequestPayload": colNum = 7; break; case "HttpStatus": colNum = 8; break; case "DataFlow": colNum = 9; break; case "ResponsePayload": colNum = 10; break; case "Error": colNum = 11; break; case "SessionId": colNum = 12; break; case "RequestId": colNum = 13; break; case "DrRequestId": colNum = 14; break; case "ResponsePayloadFirst1000": colNum = 15; break; case "ResponsePayloadCompressed": colNum = 16; break; case "ServerTrace": colNum = 17; break; } if (colNum < 0) continue; header.Append(String.Format("{0}{1}", delimiter, column.Heading)); logFormatBuilder.Append(String.Format("{0}{{{1}}}", delimiter, colNum)); } header.Append("\n\r"); if (config.Columns.Count() < 17) { for (var i = config.Columns.Count(); i < 17; i++) logFormatBuilder.Append(delimiter); } _logFormat = logFormatBuilder.ToString(); var layout = new log4net.Layout.PatternLayout { Header = header.ToString(), ConversionPattern = "%message%newline" }; layout.ActivateOptions(); jungoAppender.Layout = layout; jungoAppender.ActivateOptions(); } } _log = log4net.LogManager.GetLogger("JungoLogger"); }
/// <summary> /// Adds the email logging appender. /// </summary> public static void ConfigureEmailLoggingAppender() { var hier = (log4net.Repository.Hierarchy.Hierarchy)LogManager.GetRepository(); if (hier == null) return; var appender = (SmtpAppender)hier.Root.GetAppender("SmtpAppender") ?? new SmtpAppender(); appender.Name = "SmtpAppender"; appender.From = HostSettingManager.Get(HostSettingNames.HostEmailAddress, string.Empty); appender.To = HostSettingManager.Get(HostSettingNames.ErrorLoggingEmailAddress, string.Empty); appender.Subject = "BugNET Error"; appender.SmtpHost = HostSettingManager.SmtpServer; appender.Port = int.Parse(HostSettingManager.Get(HostSettingNames.SMTPPort)); appender.Authentication = SmtpAppender.SmtpAuthentication.None; appender.Username = string.Empty; appender.Password = string.Empty; appender.EnableSsl = Boolean.Parse(HostSettingManager.Get(HostSettingNames.SMTPUseSSL)); if (Convert.ToBoolean(HostSettingManager.Get(HostSettingNames.SMTPAuthentication))) { appender.Authentication = SmtpAppender.SmtpAuthentication.Basic; appender.Username = String.Format("{0}\\{1}", HostSettingManager.Get(HostSettingNames.SMTPDomain, string.Empty), HostSettingManager.Get(HostSettingNames.SMTPUsername, string.Empty)); appender.Password = HostSettingManager.Get(HostSettingNames.SMTPPassword, string.Empty); } appender.Priority = System.Net.Mail.MailPriority.High; appender.Threshold = log4net.Core.Level.Error; appender.BufferSize = 0; //create patternlayout var patternLayout = new log4net.Layout.PatternLayout("%newline%date [%thread] %-5level %logger [%property{NDC}] - %message%newline%newline%newline"); patternLayout.ActivateOptions(); appender.Layout = patternLayout; appender.ActivateOptions(); //add appender to root logger hier.Root.AddAppender(appender); }
/// <summary> /// This method is used to create the appender /// </summary> /// <param name="fileName"></param> /// <param name="appenderName"></param> /// <returns></returns> private log4net.Appender.FileAppender CreateAppender(string fileName, string appenderName) { //log4net.Appender.FileAppender fileAppender = new log4net.Appender.FileAppender(); log4net.Appender.RollingFileAppender fileAppender = new log4net.Appender.RollingFileAppender(); log4net.Layout.PatternLayout patternLayOut = new log4net.Layout.PatternLayout(); patternLayOut.Header = ""; //System.Environment.NewLine + "---Starts Here---" + System.Environment.NewLine; patternLayOut.Footer = ""; // patternLayOut.ConversionPattern = "%d %m%n"; //patternLayOut.ConversionPattern = ""; patternLayOut.ActivateOptions(); string path = AppDomain.CurrentDomain.BaseDirectory + @"\Log" ; System.IO.DirectoryInfo info = new DirectoryInfo(path); if (!info.Exists) { info.Create(); } string[] file = fileName.Split('\\'); fileAppender.Layout = patternLayOut; fileAppender.AppendToFile = true; fileAppender.MaximumFileSize = Parameter.LOGGING_FILE_SIZE.Trim().Equals("") ? DefaultMaximumFileSize : Parameter.LOGGING_FILE_SIZE; fileAppender.MaxSizeRollBackups = 10; fileAppender.StaticLogFileName = true; fileAppender.RollingStyle = log4net.Appender.RollingFileAppender.RollingMode.Size; //fileAppender.File = path + "\\" + file[file.Length - 1]; fileAppender.File = path + "\\" + fileName; fileAppender.Name = appenderName; fileAppender.LockingModel = new log4net.Appender.FileAppender.MinimalLock(); fileAppender.ActivateOptions(); return fileAppender; }
/// <summary> /// Creates a file appender for FTP transaction logging /// </summary> /// <param name="logFileName">Log file name for the appender to use</param> /// <returns>A configured file appender</returns> private static log4net.Appender.RollingFileAppender CreateFtpLogfileAppender(string logFileName) { var ReturnAppender = new log4net.Appender.RollingFileAppender(); ReturnAppender.Name = "RollingFileAppender"; //m_FileDate = DateTime.Now.ToString("MM-dd-yyyy"); //m_BaseFileName = logFileName; ReturnAppender.File = "FTPLog_"; ReturnAppender.AppendToFile = true; ReturnAppender.RollingStyle = log4net.Appender.RollingFileAppender.RollingMode.Date; ReturnAppender.DatePattern = "yyyyMMdd"; var Layout = new log4net.Layout.PatternLayout(); Layout.ConversionPattern = "%message%newline"; Layout.ActivateOptions(); ReturnAppender.Layout = Layout; ReturnAppender.ActivateOptions(); return ReturnAppender; }
/// <summary> /// Creates a file appender /// </summary> /// <param name="LogfileName">Log file name for the appender to use</param> /// <returns>A configured file appender</returns> private static FileAppender CreateFileAppender(string LogfileName) { var ReturnAppender = new FileAppender { Name = "FileAppender" }; m_FileDate = DateTime.Now.ToString("MM-dd-yyyy"); m_BaseFileName = LogfileName; ReturnAppender.File = m_BaseFileName + "_" + m_FileDate + ".txt"; ReturnAppender.AppendToFile = true; var Layout = new log4net.Layout.PatternLayout { ConversionPattern = "%date{MM/dd/yyyy HH:mm:ss}, %message, %level,%newline" }; Layout.ActivateOptions(); ReturnAppender.Layout = Layout; ReturnAppender.ActivateOptions(); return ReturnAppender; }
void StartLogging() { //Setup log4net for the current domain log4net.Appender.RollingFileAppender appender = new log4net.Appender.RollingFileAppender(); log4net.Layout.PatternLayout layout = new log4net.Layout.PatternLayout("%date [%thread] %-5level %logger - %message%newline"); appender.Layout = layout; appender.File = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"log\servicebrowser.log"); appender.AppendToFile = true; appender.RollingStyle = log4net.Appender.RollingFileAppender.RollingMode.Date; appender.DatePattern = "yyyyMMdd"; layout.ActivateOptions(); appender.ActivateOptions(); log4net.Config.BasicConfigurator.Configure(appender); }
/// <summary> /// Create File appender, This appender is responsible to write stream of data when invoked, in /// our case, this appender is handeled my the Bufferappender /// </summary> /// <param name="cacheName">Name of the file appender</param> /// <param name="fileName">Filename to which is to write logs</param> /// <returns>returns the created appender</returns> private log4net.Appender.IAppender CreateRollingFileAppender(string fileName) { log4net.Appender.RollingFileAppender appender = new log4net.Appender.RollingFileAppender(); appender.Name = "RollingFileAppender" + _loggerName; appender.File = fileName; //doesnt matter since all files are created with a new name appender.AppendToFile = true; appender.RollingStyle = RollingFileAppender.RollingMode.Size; appender.MaximumFileSize = "5MB"; appender.MaxSizeRollBackups = -1; appender.Threshold = log4net.Core.Level.All; log4net.Layout.PatternLayout layout = new log4net.Layout.PatternLayout(); layout.ConversionPattern = "%-27date{ISO8601}" + "\t%-45.42appdomain" + "\t%-43logger" + "\t%-42thread" + "\t%-9level" + "\t%message" + "%newline"; layout.Header = "TIMESTAMP \tAPPDOMAIN \tLOGGERNAME \tTHREADNAME \tLEVEL \tMESSAGE\r\n"; layout.Footer = "END \n"; layout.ActivateOptions(); appender.Layout = layout; appender.ActivateOptions(); return appender; }
private static void SetUpConsoleLogger() { string consolePattern = "%message%newline"; log4net.Layout.PatternLayout layout = new log4net.Layout.PatternLayout( consolePattern ); layout.Header = ""; layout.Footer = ""; layout.ActivateOptions(); log4net.Appender.ConsoleAppender consoleAppender = new log4net.Appender.ConsoleAppender(); //consoleAppender.ErrorHandler = new LoggingErrorHandler(); consoleAppender.Name = "Console appender"; consoleAppender.Threshold = log4net.Core.Level.Warn; consoleAppender.Layout = layout; consoleAppender.Target = "Console.Out"; consoleAppender.ActivateOptions(); // A slight bit of hackery in order to programatically set more than one appender (which isn't supported by BasicConfigurator) log4net.Repository.Hierarchy.Logger root = ( (log4net.Repository.Hierarchy.Hierarchy)log4net.LogManager.GetRepository() ).Root; root.AddAppender( consoleAppender ); root.Repository.Configured = true; }
/// <summary> /// Creates a layout object for a Db appender parameter /// </summary> /// <param name="LayoutStr">Name of parameter</param> /// <returns></returns> private static log4net.Layout.IRawLayout CreateLayout(string LayoutStr) { var layoutConvert = new log4net.Layout.RawLayoutConverter(); var returnLayout = new log4net.Layout.PatternLayout { ConversionPattern = LayoutStr }; returnLayout.ActivateOptions(); var retItem = (log4net.Layout.IRawLayout)layoutConvert.ConvertFrom(returnLayout); return retItem; }
public ILogger GetLogger(string name) { if(String.IsNullOrEmpty(name)) { throw new ArgumentNullOrEmptyException("name"); } if (RunContext.Current.RunMode == RunMode.Demo) { name = name + "_demo"; } this.lock4loggers.EnterReadLock(); try { if (this.loggers.ContainsKey(name)) { return this.loggers[name]; } } finally { this.lock4loggers.ExitReadLock(); } this.lock4loggers.EnterWriteLock(); try { if (this.loggers.ContainsKey(name)) { return this.loggers[name]; } // 当在默认日志配置文件 Repository 中未配置日志时,使用代码的方式对日志进行默认配置,配置后日志输出到 logs\{name}\n.log 中 log4net.Core.ILogger logger = Repository.Exists(name); if (logger == null) { // 使用代码进行配置 log4net.Repository.ILoggerRepository defaultRepository = CustomLogManager.GetRepository("defaultRepository_" + name); if (defaultRepository == null) { defaultRepository = CustomLogManager.CreateRepository("defaultRepository_" + name); defaultRepository.Threshold = log4net.Core.Level.Info; CustomFileAppender appender = new CustomFileAppender(); appender.Name = name + "_Appender"; appender.File = String.Format("logs\\{0}\\{1}.log", name, name); appender.Enable = true; appender.DirectoryByDate = true; appender.MaximumFileSize = "1000KB"; appender.LockingModel = new log4net.Appender.FileAppender.ExclusiveLock(); log4net.Layout.PatternLayout layout = new log4net.Layout.PatternLayout(); layout.ConversionPattern = "%date{MM-dd HH:mm:ss.fff} %-5level %-8property{RunMode} %-8property{Category} - %message%newline"; layout.ActivateOptions(); appender.Layout = layout; appender.Encoding = Encoding.UTF8; appender.ActivateOptions(); log4net.Config.BasicConfigurator.Configure(defaultRepository, appender); } this.loggers[name] = new DefaultLogger(CustomLogManager.GetLogger(defaultRepository, name)); return this.loggers[name]; } else { this.loggers[name] = new DefaultLogger(CustomLogManager.GetLogger(Repository, name)); return this.loggers[name]; } } finally { this.lock4loggers.ExitWriteLock(); } }
private static void SetUpFileLogger() { string filePattern = "%date %-15.15thread %-5level: %message%newline"; log4net.Layout.ILayout layout; log4net.Layout.PatternLayout normalTextLayout = new log4net.Layout.PatternLayout( filePattern ); normalTextLayout.ActivateOptions(); layout = normalTextLayout; log4net.Appender.FileAppender fileAppender = new log4net.Appender.FileAppender(); fileAppender.AppendToFile = false; fileAppender.Encoding = Encoding.UTF8; fileAppender.File = Paths.LogPath; fileAppender.ImmediateFlush = true; fileAppender.Layout = layout; fileAppender.LockingModel = new log4net.Appender.FileAppender.ExclusiveLock(); fileAppender.Name = "File appender"; fileAppender.Threshold = log4net.Core.Level.Debug; fileAppender.ActivateOptions(); // A slight bit of hackery in order to programatically set more than one appender (which isn't supported by BasicConfigurator) log4net.Repository.Hierarchy.Logger root = ( (log4net.Repository.Hierarchy.Hierarchy)log4net.LogManager.GetRepository() ).Root; root.AddAppender( fileAppender ); root.Repository.Configured = true; }