public static void Main() { ILayout simpleLayout = new SimpleLayout(); IAppender consoleAppender = new ConsoleAppender(simpleLayout); var fileAppender = new FileAppender(simpleLayout); fileAppender.File = "../../log.txt"; var logger = new Logger(consoleAppender, fileAppender); logger.Error("Error parsing JSON."); logger.Info(string.Format("User {0} successfully registered.", "Dobri")); logger.Warn("Warning - missing files."); var xmlLayout = new XmlLayout(); consoleAppender = new ConsoleAppender(xmlLayout); logger = new Logger(consoleAppender); logger.Fatal("mscorlib.dll does not respond"); logger.Critical("No connection string found in App.config"); consoleAppender = new ConsoleAppender(simpleLayout); consoleAppender.ReportLevel = ReportLevel.Error; logger = new Logger(consoleAppender); logger.Info("Everything seems fine"); logger.Warn("Warning: ping is too high - disconnect imminent"); logger.Error("Error parsing request"); logger.Critical("No connection string found in App.config"); logger.Fatal("mscorlib.dll does not respond"); }
static void Main() { //ILayout xmLayout = new XmlLayout(); //FileAppender fileAppender = // new FileAppender(xmLayout); //ILogger logger = new Logger(fileAppender); //fileAppender.File = "log.txt"; //fileAppender.ReportLevel = ReportLevel.Error; ILayout simpleLayout = new SimpleLayout(); ConsoleAppender consoleAppender = new ConsoleAppender(simpleLayout); ILogger logger = new Logger(consoleAppender); consoleAppender.ReportLevel = ReportLevel.Error; try { logger.Info("Everything seems fine"); logger.Warn("Warning: ping is too high - disconnect imminent"); logger.Error("Error parsing request"); logger.Critical("No connection string found in App.config"); logger.Fatal("mscorlib.dll does not respond"); } catch (ArgumentException ex) { Console.WriteLine(ex.Message); } }
static void Main() { var simpleLayout = new SimpleLayout(); var consoleAppender = new ConsoleAppender(simpleLayout); var fileAppender = new FileAppender(simpleLayout); fileAppender.LogFile = "log.txt"; var errorLog = new Log(new Level("Error"), "Error parsing JSON."); var infoLog = new Log(new Level("Info"), string.Format("User {0} successfully registered.", "Pesho")); var warnLog = new Log(new Level("Warning"), "Warning - missing files."); var logger = new Models.Logger(new List<IAppender> { consoleAppender, fileAppender }); logger.AppendLog(errorLog); logger.AppendLog(infoLog); logger.AppendLog(warnLog); //xml Logger var xmlLayout = new XmlLayout(); var consoleXmlAppender = new ConsoleAppender(xmlLayout); var xmlLogger = new Models.Logger(new List<IAppender>{consoleXmlAppender}); var fatalLog = new Log(new Level("Fatal"), "mscorlib.dll does not respond"); var criticalLog = new Log(new Level("Critical"), "No connection string found in App.config"); xmlLogger.AppendLog(fatalLog); xmlLogger.AppendLog(criticalLog); }
public static void Main() { ILayout simpleLayout = new SimpleLayout(); IAppender consoleAppender = new ConsoleAppender(simpleLayout); ILogger logger = new Logger(consoleAppender); logger.Error("Error parsing JSON"); logger.Info($"User {"Pesho"} successfully registered."); }
public static void Main() { var simpleLayout = new SimpleLayout(); var consoleAppender = new ConsoleAppender(simpleLayout); var fileAppender = new FileAppender(simpleLayout); fileAppender.File = "log.txt"; var logger = new Logger(consoleAppender, fileAppender); logger.Error("Error parsing JSON."); logger.Info(string.Format("User {0} successfully registered.", "Pesho")); logger.Warn("Warning - missing files."); }
static void Main(string[] args) { ILayout simpleLayout = new SimpleLayout(); IAppender consoleAppender = new ConsoleAppender(simpleLayout); consoleAppender.ReportLevel = ReportLevel.Error; ILogger logger = new Logger(consoleAppender); logger.Info("Everything seems fine"); logger.Warn("Warning: ping is too high - disconnect imminent"); logger.Error("Error parsing request"); logger.Critical("No connection string found in App.config"); logger.Fatal("mscorlib.dll does not respond"); }
static void Main() { //Init dependencies ILayout layout = new XmlLayout(); IAppender fileAppender = new FileAppender(layout, "file.txt"); IAppender consoleAppender = new ConsoleAppender(layout); Logger logger = new Logger(consoleAppender); //shows every report level above ReportLevel.Warn consoleAppender.ReportLevel = ReportLevel.Fatal; logger.Critical("Critical Sample Report"); logger.Fatal("Fatal Sample Report"); logger.Info("Info Sample Report"); }
public static void Main() { ILayout simpleLayout = new SimpleLayout(); IDataAppender consoleAppender = new ConsoleAppender(simpleLayout); ILogger logger = new Logger(consoleAppender); logger.Error("Error parsing JSON."); logger.Info($"User {"Pesho"} successfully registered."); var fileAppender = new FileAppender(simpleLayout, "log.txt"); logger = new Logger(fileAppender); logger.Error("Error parsing JSON."); logger.Info($"User {"Pesho"} successfully registered."); logger.Warn("Warning - missing files."); }
static void Main(string[] args) { ILayout simpleLayout = new SimpleLayout(); IAppender consoleAppender = new ConsoleAppender(simpleLayout); ILogger logger = new Logger(consoleAppender); logger.Error("Error parsing JSON"); logger.Info(string.Format("User {0} successfully registered.", "Pesho")); Console.WriteLine(new string('-', 20)); //We create a second Appender and add it to the existing ILogger object IFileAppender fileAppender = new FileAppender(simpleLayout); fileAppender.File = "log.txt"; logger.AddAppender(fileAppender); logger.Fatal("mscorlib.dll does not respond"); logger.Critical("No connection string found in App.config"); Console.WriteLine(new string('-', 20)); //We set the new XML Layout on each Appender that the Logger object uses foreach (IAppender appender in logger.Appenders) { appender.Layout = new XmlLayout(); } logger.Fatal("mscorlib.dll does not respond"); logger.Critical("No connection string found in App.config"); Console.WriteLine(new string('-', 20)); //We set the Report Level Minimum at Error foreach (IAppender appender in logger.Appenders) { appender.ReportLevelMinimum = Enums.ReportLevel.Error; } logger.Info("Everything seems fine"); logger.Warning("Warning: ping is too high - disconnect imminent"); logger.Error("Error parsing request"); logger.Critical("No connection string found in App.config"); logger.Fatal("mscorlib.dll does not respond"); Console.WriteLine(new string('-', 20)); }
public void TestConsoleAppender_ShouldAppendCorrectly() { const string FakeResult = "It works"; string expetedOutput = "It works" + Environment.NewLine; DateTime date = It.IsAny<DateTime>(); const ReportLevel ReportLevel = ReportLevel.Error; var message = It.IsAny<string>(); var mock = new Mock<ILayout>(); mock.Setup(layout => layout.LayoutMaker(date, ReportLevel, message)).Returns(FakeResult); StringWriter actualOutput = new StringWriter(); Console.SetOut(actualOutput); IAppender consoleAppender = new ConsoleAppender(mock.Object); consoleAppender.Append(date, ReportLevel, message); mock.Verify(a => a.LayoutMaker(date, ReportLevel, message), Times.Once); Assert.AreEqual(expetedOutput, actualOutput.ToString()); }
public static void Main() { var simpleLayout = new SimpleLayout(); var jsonLayout = new JsonLayout(); // var myLayout = new SoftUniLayout(); var consoleAppender = new ConsoleAppender(simpleLayout); consoleAppender.ReportLevel = ReportLevel.Error; consoleAppender.ReportLevel = ReportLevel.Error; var fileAppender = new FileAppendder(jsonLayout, "../../Log.txt"); fileAppender.ReportLevel = ReportLevel.Error; var logger = new Logger(consoleAppender, fileAppender); logger.Error("Error parsing JSON."); logger.Warning("User John successfully registered"); logger.Info("Everything seems fine"); logger.Warning("Warning: ping is too high - disconnect imminent"); logger.Error("Error parsing request"); logger.Critical("No connection string found in App.config"); logger.Fatal("mscorlib.dll does not respond"); fileAppender.Close(); }
/// <summary> /// 使用文本文件记录异常日志 /// </summary> public static void LoadFileAppender() { string currentPath = AppDomain.CurrentDomain.BaseDirectory; currentPath = Path.Combine(currentPath, @"Log"); string txtLogPath = Path.Combine(currentPath, "Log-" + DateTime.Now.ToString("yyyyMMdd") + ".txt"); log4net.Repository.Hierarchy.Hierarchy hier = (log4net.Repository.Hierarchy.Hierarchy)log4net.LogManager.GetRepository(); if (hier != null) { FileAppender fileAppender = new FileAppender(); fileAppender.Name = "LogFileAppender"; fileAppender.File = txtLogPath; fileAppender.AppendToFile = true; PatternLayout patternLayout = new PatternLayout { ConversionPattern = "%date [%thread] %-5level %logger - %message%newline" //[%property{log4net:HostName}] }; patternLayout.ActivateOptions(); fileAppender.Layout = patternLayout; fileAppender.Encoding = Encoding.UTF8; fileAppender.LockingModel = new FileAppender.MinimalLock(); fileAppender.ActivateOptions(); log4net.Config.BasicConfigurator.Configure(fileAppender); // add console appender ConsoleAppender conAppender = new ConsoleAppender(); conAppender.Name = "Console"; conAppender.Layout = patternLayout; conAppender.ActivateOptions(); log4net.Config.BasicConfigurator.Configure(conAppender); } }
public static void Setup() { var hierarchy = (Hierarchy)LogManager.GetRepository(Assembly.GetEntryAssembly()); var patternLayout = new PatternLayout { ConversionPattern = "%date [%thread] %-5level %logger - %message%newline" }; patternLayout.ActivateOptions(); /* * var roller = new RollingFileAppender * { * AppendToFile = false, * File = @"Logs\log.txt", * Layout = patternLayout, * MaxSizeRollBackups = 5, * MaximumFileSize = "1GB", * RollingStyle = RollingFileAppender.RollingMode.Size, * StaticLogFileName = true * }; * roller.ActivateOptions(); * hierarchy.Root.AddAppender(roller); */ var console = new ConsoleAppender { Layout = patternLayout }; console.ActivateOptions(); hierarchy.Root.AddAppender(console); hierarchy.Root.Level = Level.All; hierarchy.Configured = true; }
static void Main() { ILayout simpleLayout = new SimpleLayout(); IAppender consoleAppender = new ConsoleAppender(simpleLayout); var fileAppender = new FileAppender(simpleLayout) { File = "../../logResult.txt" }; var logger = new Logger(consoleAppender, fileAppender); logger.Error("Error : Index out of bounds."); logger.Info("Database modified."); logger.Warn("Warning - script not found."); var xmlLayout = new XmlLayout(); consoleAppender = new ConsoleAppender(xmlLayout); logger = new Logger(consoleAppender); logger.Fatal("Windows blue :)"); logger.Critical("Server down"); consoleAppender = new ConsoleAppender(simpleLayout) { ReportLevel = ReportLevel.Error }; logger = new Logger(consoleAppender); logger.Info("Process finished."); logger.Warn("Warning: CPU temperature too high"); logger.Error("No Internet connection"); logger.Critical("Windows blue :)"); logger.Fatal("Server down"); }
public static ILog GetLogger(String loggerName) { if (_consoleAppender == null) { _consoleAppender = GetConsoleAppender(); } if (_fileAppender == null) { _fileAppender = GetFileAppender(); } if (_rollingFileAppender == null) { _rollingFileAppender = GetRollingFileAppender(); } if (_logger != null) { return(_logger); } BasicConfigurator.Configure(_consoleAppender, _fileAppender, _rollingFileAppender); _logger = LogManager.GetLogger(loggerName); return(_logger); }
/// <summary> /// Program wide initialization method /// </summary> /// <param name="args"></param> private static int ProgramInit(String[] args) { int runLength = 0; try { runLength = int.Parse(args[1]); } catch (Exception e) { System.Console.Error.WriteLine(e); Usage(); } ConsoleAppender appender = new ConsoleAppender(new SimpleLayout()); if ("false" == args[0]) { // nothing to do } else if ("true" == args[0]) { System.Console.WriteLine("Flagging as shipped code."); ((Hierarchy)LogManager.GetRepository()).Threshold = log4net.Core.Level.Warn; } else { Usage(); } ((Logger)SHORT_LOG.Logger).Level = log4net.Core.Level.Info; ((Hierarchy)LogManager.GetRepository()).Root.Level = log4net.Core.Level.Info; ((Hierarchy)LogManager.GetRepository()).Root.AddAppender(appender); return(runLength); }
public App() { InitializeComponent(); log4net.Repository.Hierarchy.Hierarchy hierarchy = (Hierarchy)log4net.LogManager.GetRepository(Assembly.GetAssembly(typeof(App))); PatternLayout patternLayout = new PatternLayout(); patternLayout.ConversionPattern = "[%thread] %-5level %logger - %message"; patternLayout.ActivateOptions(); var cca = new ConsoleAppender(); cca.Layout = patternLayout; cca.ActivateOptions(); hierarchy.Root.AddAppender(cca); hierarchy.Root.Level = Level.Debug; hierarchy.Configured = true; { var config = new NLog.Config.LoggingConfiguration(); // Targets where to log to: File and Console var logconsole = new NLog.Targets.ConsoleTarget("logconsole"); // Rules for mapping loggers to targets // config.AddRule(LogLevel.Warn, LogLevel.Fatal, logconsole); // Apply config NLog.LogManager.Configuration = config; } MainPage = new MainPage(); }
private static void ConfigureDebugLogging() { if (File.Exists(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "log4net.config"))) { return; // that overrides the default config } var loggerRepository = LogManager.GetRepository(typeof(HttpServer).Assembly); var patternLayout = new PatternLayout(PatternLayout.DefaultConversionPattern); var consoleAppender = new ConsoleAppender { Layout = patternLayout, }; consoleAppender.ActivateOptions(); ((Logger)loggerRepository.GetLogger(typeof(HttpServer).FullName)).AddAppender(consoleAppender); var fileAppender = new RollingFileAppender { AppendToFile = false, File = "Raven.Server.log", Layout = patternLayout, MaxSizeRollBackups = 3, MaximumFileSize = "1024KB", StaticLogFileName = true, LockingModel = new FileAppender.MinimalLock() }; fileAppender.ActivateOptions(); var asyncBufferingAppender = new AsyncBufferingAppender(); asyncBufferingAppender.AddAppender(fileAppender); ((Hierarchy)loggerRepository).Root.AddAppender(asyncBufferingAppender); loggerRepository.Configured = true; }
Usage() { #region Log4NetInCode var layout = new PatternLayout { ConversionPattern = "%d [%t] %-5p %c [%x] - %m%n" }; layout.ActivateOptions(); var consoleAppender = new ConsoleAppender { Threshold = Level.Debug, Layout = layout }; consoleAppender.ActivateOptions(); var executingAssembly = Assembly.GetExecutingAssembly(); var repository = log4net.LogManager.GetRepository(executingAssembly); BasicConfigurator.Configure(repository, consoleAppender); LogManager.Use <Log4NetFactory>(); #endregion }
public IAppender CreateAppender(string type, string errorLvl, string layoutType) { ILayout layout = this.layoutFactory.CreateLayout(layoutType); ErrorLevel errorLevel = this.ParseErrorLevel(errorLvl); IAppender appender = null; switch (type) { case "ConsoleAppender": appender = new ConsoleAppender(layout, errorLevel); break; case "FileAppender": var file = new LogFile(string.Format(defaultFileName, this.amountOfFiles)); appender = new FileAppender(layout, errorLevel, file); break; default: throw new ArgumentException("Invalid appender."); } return(appender); }
public static void Main() { try { var simpleLayout = new SimpleLayout(); var xmlLayout = new XmlLayout(); IAppender consoleAppender = new ConsoleAppender(simpleLayout); IAppender fileAppender = new FileAppender(simpleLayout); fileAppender.File = "../../log.txt"; IAppender fileAppenderXml = new FileAppender(xmlLayout); fileAppenderXml.File = "../../log.xml"; ILogger logger = new Logger(consoleAppender, fileAppender, fileAppenderXml); // add in logs logger.Error("Error parsing JSON."); logger.Info(string.Format("User {0} successfully registered.", "Pesho")); logger.Warn("Warn - missing files."); logger.Fatal("mscorlib.dll does not respond"); logger.Critical("No connection string found in App.config"); logger.Info("Everything seems fine"); logger.Warn("Warning: ping is too high - disconnect imminent"); logger.Error("Error parsing request"); logger.Critical("No connection string found in App.config"); logger.Fatal("mscorlib.dll does not respond"); } catch (ArgumentException ex) { Console.WriteLine(ex.Message); } Console.WriteLine(); }
public static ILog GetLogger(Type type) { if (_consoleAppender == null) { _consoleAppender = GetConsoleAppender(); } if (_fileAppender == null) { _fileAppender = GetFileAppender(); } if (_rollingFileAppender == null) { _rollingFileAppender = GetRollingFileAppender(); } if (_logger != null) return _logger; BasicConfigurator.Configure(_consoleAppender, _fileAppender, _rollingFileAppender); _logger = LogManager.GetLogger(type); return _logger; }
static void Main() { var simpleLayout = new SimpleLayout(); var consoleAppender = new ConsoleAppender(simpleLayout); var fileAppender = new FileAppender(simpleLayout); fileAppender.FilePath = "../../log.txt"; var logger = new Logger(consoleAppender, fileAppender); logger.Error("Error parsing JSON."); logger.Info(string.Format("User {0} successfully registered.", "Pesho")); logger.Warn("Warning - missing files."); //var xmlLayout = new XmlLayout(); //var consoleAppender = new ConsoleAppender(xmlLayout); //var logger = new Logger(consoleAppender); //logger.Fatal("mscorlib.dll does not respond"); //logger.Critical("No connection string found in App.config"); //var simpleLayout = new SimpleLayout(); //var consoleAppender = new ConsoleAppender(simpleLayout); //consoleAppender.ReportLevel = ReportLevel.Error; //var logger = new Logger(consoleAppender); //logger.Info("Everything seems fine"); //logger.Warn("Warning: ping is too high - disconnect imminent"); //logger.Error("Error parsing request"); //logger.Critical("No connection string found in App.config"); //logger.Fatal("mscorlib.dll does not respond"); }
public IAppender CreateAppender(string appenderType, string layoutType) { ILayout layout = null; switch (layoutType) { case "SimpleLayout": layout = new SimpleLayout(); break; case "XmlLayout": layout = new XmlLayout(); break; default: throw new ArgumentException("Layout type does not exist."); } IAppender appender; switch (appenderType) { case "ConsoleAppender": appender = new ConsoleAppender(layout); break; case "FileAppender": appender = new FileAppender(layout); break; default: throw new ArgumentException("Appender type does not exist."); } return(appender); }
public IAppender CreateAppender(string appenderType, string levelString, string layoutType) { ILayout layout = this.LayoutFactory.CreateLayout(layoutType); ErrorLevel errorLevel = this.ParseErrorLevel(levelString); IAppender appender = null; switch (appenderType) { case "ConsoleAppender": appender = new ConsoleAppender(layout, errorLevel); break; case "FileAppender": ILogFile logFile = new LogFile(string.Format(DefaultFileName, this.fileNumber)); appender = new FileAppender(layout, errorLevel, logFile); break; default: throw new ArgumentException("Invalid Appender Type!"); } return(appender); }
public static void Setup() { Hierarchy hierarchy = (Hierarchy)LogManager.GetRepository(); PatternLayout patternLayout = new PatternLayout(); patternLayout.ConversionPattern = "%date [%thread] %-5level %logger - %message%newline"; patternLayout.ActivateOptions(); RollingFileAppender roller = new RollingFileAppender(); roller.AppendToFile = false; roller.File = @"Logs\EventLog.txt"; roller.Layout = patternLayout; roller.MaxSizeRollBackups = 5; roller.MaximumFileSize = "1GB"; roller.RollingStyle = RollingFileAppender.RollingMode.Size; roller.StaticLogFileName = true; roller.ActivateOptions(); hierarchy.Root.AddAppender(roller); MemoryAppender memory = new MemoryAppender(); memory.ActivateOptions(); hierarchy.Root.AddAppender(memory); ConsoleAppender consoleAppender = new ConsoleAppender(); consoleAppender.Layout = patternLayout; consoleAppender.ActivateOptions(); hierarchy.Root.AddAppender(consoleAppender); hierarchy.Root.Level = Level.All; hierarchy.Configured = true; }
public static void EnsureEqualConsoleAppender(ConsoleAppender ca1, ConsoleAppender ca2) { EnsureEqualAppender(ca1, ca2); }
private static void InitLoggers(ServiceDescriptor d, bool enableCLILogging) { // TODO: Make logging levels configurable Level logLevel = Level.Debug; // TODO: Debug should not be printed to console by default. Otherwise commands like 'status' will be pollutted // This is a workaround till there is a better command line parsing, which will allow determining Level consoleLogLevel = Level.Info; Level eventLogLevel = Level.Warn; // Legacy format from winsw-1.x: (DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " - " + message); PatternLayout pl = new PatternLayout { ConversionPattern = "%d %-5p - %m%n" }; pl.ActivateOptions(); List <IAppender> appenders = new List <IAppender>(); // wrapper.log string wrapperLogPath = Path.Combine(d.LogDirectory, d.BaseName + ".wrapper.log"); var wrapperLog = new FileAppender { AppendToFile = true, File = wrapperLogPath, ImmediateFlush = true, Name = "Wrapper file log", Threshold = logLevel, LockingModel = new FileAppender.MinimalLock(), Layout = pl }; wrapperLog.ActivateOptions(); appenders.Add(wrapperLog); // Also display logs in CLI if required if (enableCLILogging) { var consoleAppender = new ConsoleAppender { Name = "Wrapper console log", Threshold = consoleLogLevel, Layout = pl, }; consoleAppender.ActivateOptions(); appenders.Add(consoleAppender); } // System log var systemEventLogger = new ServiceEventLogAppender { Name = "System event log", Threshold = eventLogLevel, provider = eventLogProvider }; systemEventLogger.ActivateOptions(); appenders.Add(systemEventLogger); BasicConfigurator.Configure( #if NETCOREAPP LogManager.GetRepository(Assembly.GetExecutingAssembly()), #endif appenders.ToArray()); }
public static void Setup() { if (_blnIsInitialized) { return; } PatternLayout patternLayoutFull = new PatternLayout(); patternLayoutFull.ConversionPattern = "%date [%thread] |%level| |%class.%method() line: %line| || %message %newline"; patternLayoutFull.ActivateOptions(); RollingFileAppender roller = new RollingFileAppender(); roller.Layout = patternLayoutFull; Hierarchy hierarchy = (Hierarchy)LogManager.GetRepository(); #region File logger roller.AppendToFile = true; roller.File = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), string.Format(@"{0}\{1}.txt", Constants.APPLICATIONNAME, Constants.APPLICATIONNAME)); roller.RollingStyle = RollingFileAppender.RollingMode.Composite; roller.MaxSizeRollBackups = 5; roller.MaximumFileSize = "20MB"; roller.StaticLogFileName = true; roller.LockingModel = new FileAppender.MinimalLock(); roller.ActivateOptions(); hierarchy.Root.AddAppender(roller); #endregion File logger //#region Windows Event Logger //var eventLoggerAppender = new EventLogAppender //{ // ApplicationName = Constants.APPLICATIONNAME, // LogName = Constants.APPLICATIONNAME, // Layout = patternLayout, // Threshold = Level.Error //}; //eventLoggerAppender.ActivateOptions(); //hierarchy.Root.AddAppender(eventLoggerAppender); //#endregion Windows Event Logger if (Environment.UserInteractive) { // we write to console and capture it later to a WPF window //so, we only write the parts the end-user like to see var patternLayoutPartial = new PatternLayout(); patternLayoutPartial.ConversionPattern = "%date [%thread] |%level| || %message %newline"; patternLayoutPartial.ActivateOptions(); var consoleAppender = new ConsoleAppender { Name = Constants.APPLICATIONNAME, Layout = patternLayoutPartial, Threshold = Level.All }; consoleAppender.ActivateOptions(); hierarchy.Root.AddAppender(consoleAppender); } hierarchy.Configured = true; _blnIsInitialized = true; }
static void CreateAppenderFromConfig(string appenderName) { if (string.IsNullOrEmpty(appenderName)) { return; } string options = ConfigMgr.GetDefaultValue(appenderName, ""); var tokens = new StringArray(options, ','); string name = appenderName.Substring(9); if (tokens.Length < 2) { Console.WriteLine("Log.CreateAppenderFromConfig: Wrong configuration for appender {0}. Config line: {1}", name, options); return; } AppenderFlags flags = AppenderFlags.None; AppenderType type = (AppenderType)uint.Parse(tokens[0]); LogLevel level = (LogLevel)uint.Parse(tokens[1]); if (level > LogLevel.Fatal) { Console.WriteLine("Log.CreateAppenderFromConfig: Wrong Log Level {0} for appender {1}\n", level, name); return; } if (tokens.Length > 2) { flags = (AppenderFlags)uint.Parse(tokens[2]); } byte id = NextAppenderId(); switch (type) { case AppenderType.Console: { var appender = new ConsoleAppender(id, name, level, flags); appenders[id] = appender; break; } case AppenderType.File: { string filename; if (tokens.Length < 4) { if (name != "Server") { Console.WriteLine("Log.CreateAppenderFromConfig: Missing file name for appender {0}", name); return; } filename = Process.GetCurrentProcess().ProcessName + ".log"; } else { filename = tokens[3]; } appenders[id] = new FileAppender(id, name, level, filename, m_logsDir, flags); break; } case AppenderType.DB: { appenders[id] = new DBAppender(id, name, level); break; } default: Console.WriteLine("Log.CreateAppenderFromConfig: Unknown type {0} for appender {1}", type, name); break; } }
protected static void SetupLog4Net() { #if TestUseLog4Net ConsoleAppender appender = new ConsoleAppender { Layout = new log4net.Layout.PatternLayout() }; log4net.Config.BasicConfigurator.Configure(appender); #endif }
public LogService(string repositoryName, string name, string path) { var repository = LogManager.GetAllRepositories().Where(item => item.Name == repositoryName).FirstOrDefault(); if (repository != null) { //this.log = log4net.LogManager.GetLogger(repositoryName, name); this.hierarchy = (Hierarchy)LogManager.GetRepository(repositoryName); } else { this.hierarchy = (Hierarchy)LogManager.CreateRepository(repositoryName); } var xmlLayout = new XmlLayoutSchemaLog4j() { LocationInfo = true }; xmlLayout.ActivateOptions(); this.rollingAppender = new RollingFileAppender() { AppendToFile = true, File = Path.Combine(path, @"logs", $"{repositoryName}_{name}"), DatePattern = "_yyyy-MM-dd'.xml'", Layout = xmlLayout, Encoding = Encoding.UTF8, MaxSizeRollBackups = 5, MaximumFileSize = "1GB", RollingStyle = RollingFileAppender.RollingMode.Date, StaticLogFileName = false }; this.rollingAppender.ActivateOptions(); var patternLayout = new PatternLayout() { ConversionPattern = conversionPattern }; patternLayout.ActivateOptions(); this.consoleAppender = new ConsoleAppender() { Layout = patternLayout }; this.consoleAppender.AddFilter(new log4net.Filter.LevelRangeFilter() { LevelMin = GetLevel(this.verbose), LevelMax = Level.Fatal, }); this.consoleAppender.ActivateOptions(); this.hierarchy.Root.AddAppender(this.consoleAppender); this.hierarchy.Root.AddAppender(this.rollingAppender); this.hierarchy.Root.Level = Level.All; this.hierarchy.Configured = true; this.log = log4net.LogManager.GetLogger(repositoryName, name); this.name = name; }
public void TestLoggerWarning_ShouldAppendOnTheConsoleCorrectly() { DateTime date = DateTime.Now; const ReportLevel ReportLevel = ReportLevel.Warnimg; var message = It.IsAny<string>(); string expetedOutput = string.Format("{0}-{1}-{2}{3}", date, ReportLevel, message, Environment.NewLine); var layout = new SimpleLayout(); IAppender consoleAppender = new ConsoleAppender(layout); ILogger logger = new Logger(consoleAppender); StringWriter actualOutput = new StringWriter(); Console.SetOut(actualOutput); logger.Warning(message); Assert.AreEqual(expetedOutput, actualOutput.ToString()); }
protected override void OnStart(string[] args) { #region logging PatternLayout layout = new PatternLayout { ConversionPattern = "%d %-5p %c - %m%n" }; layout.ActivateOptions(); ConsoleAppender appender = new ConsoleAppender { Layout = layout, Threshold = Level.Info }; appender.ActivateOptions(); BasicConfigurator.Configure(appender); LogManager.Use <Log4NetFactory>(); #endregion #region create-config BusConfiguration busConfiguration = new BusConfiguration(); #endregion #region endpoint-name busConfiguration.EndpointName("Sample.FirstEndpoint"); #endregion #region container ContainerBuilder builder = new ContainerBuilder(); //configure your custom services //builder.RegisterInstance(new MyService()); IContainer container = builder.Build(); busConfiguration.UseContainer <AutofacBuilder>(c => c.ExistingLifetimeScope(container)); #endregion #region serialization busConfiguration.UseSerialization <JsonSerializer>(); #endregion #region transport busConfiguration.UseTransport <MsmqTransport>(); #endregion #region sagas //Not required since Sagas are enabled by default in Version 5 #endregion #region persistence busConfiguration.UsePersistence <InMemoryPersistence, StorageType.Sagas>(); busConfiguration.UsePersistence <InMemoryPersistence, StorageType.Subscriptions>(); busConfiguration.UsePersistence <InMemoryPersistence, StorageType.Timeouts>(); #endregion #region critical-errors busConfiguration.DefineCriticalErrorAction((errorMessage, exception) => { // Log the critical error logger.Fatal(string.Format("CRITICAL: {0}", errorMessage), exception); // Kill the process on a critical error Environment.FailFast(string.Format("The following critical error was encountered by NServiceBus:\n{0}\nNServiceBus is shutting down.", errorMessage), exception); }); #endregion #region start-bus busConfiguration.EnableInstallers(); bus = Bus.Create(busConfiguration).Start(); #endregion }
protected override void OnStart(string[] args) { #region logging PatternLayout layout = new PatternLayout { ConversionPattern = "%d %-5p %c - %m%n" }; layout.ActivateOptions(); ConsoleAppender appender = new ConsoleAppender { Layout = layout, Threshold = Level.Info }; appender.ActivateOptions(); BasicConfigurator.Configure(appender); SetLoggingLibrary.Log4Net(); #endregion #region create-config Configure configure = Configure.With(); #endregion #region endpoint-name configure.DefineEndpointName("Samples.FirstEndpoint"); #endregion #region container ContainerBuilder builder = new ContainerBuilder(); //configure your custom services //builder.RegisterInstance(new MyService()); IContainer container = builder.Build(); configure.AutofacBuilder(container); #endregion #region serialization Configure.Serialization.Json(); #endregion #region transport configure.UseTransport <Msmq>(); #endregion #region sagas Configure.Features.Enable <Sagas>(); #endregion #region persistence configure.InMemorySagaPersister(); configure.UseInMemoryTimeoutPersister(); configure.InMemorySubscriptionStorage(); #endregion #region critical-errors Configure.Instance.DefineCriticalErrorAction((errorMessage, exception) => { // Log the critical error logger.Fatal(string.Format("CRITICAL: {0}", errorMessage), exception); // Kill the process on a critical error Environment.FailFast(string.Format("The following critical error was encountered by NServiceBus:\n{0}\nNServiceBus is shutting down.", errorMessage), exception); }); #endregion #region start-bus bus = configure.UnicastBus() .CreateBus() .Start(() => configure.ForInstallationOn <Windows>().Install()); #endregion }
public static void Run(string[] argsArray, IServiceConfig?config = null) { bool inConsoleMode = argsArray.Length > 0; config ??= LoadConfigAndInitLoggers(inConsoleMode); if (!inConsoleMode) { Log.Debug("Starting WinSW in service mode"); using var service = new WrapperService(config); try { ServiceBase.Run(service); } catch { // handled in OnStart } return; } Log.Debug("Starting WinSW in console mode"); if (argsArray.Length == 0) { PrintHelp(); return; } var args = new List <string>(Array.AsReadOnly(argsArray)); if (args[0] == "/redirect") { var f = new FileStream(args[1], FileMode.Create); var w = new StreamWriter(f) { AutoFlush = true }; Console.SetOut(w); Console.SetError(w); var handle = f.SafeFileHandle; _ = Kernel32.SetStdHandle(-11, handle); // set stdout _ = Kernel32.SetStdHandle(-12, handle); // set stder args = args.GetRange(2, args.Count - 2); } bool elevated; if (args[0] == "/elevated") { elevated = true; _ = ConsoleApis.FreeConsole(); _ = ConsoleApis.AttachConsole(ConsoleApis.ATTACH_PARENT_PROCESS); #if VNEXT string stdinName = args[1]; if (stdinName != NoPipe) { var stdin = new NamedPipeClientStream(".", stdinName, PipeDirection.In, PipeOptions.Asynchronous); stdin.Connect(); Console.SetIn(new StreamReader(stdin)); } string stdoutName = args[2]; if (stdoutName != NoPipe) { var stdout = new NamedPipeClientStream(".", stdoutName, PipeDirection.Out, PipeOptions.Asynchronous); stdout.Connect(); Console.SetOut(new StreamWriter(stdout) { AutoFlush = true }); } string stderrName = args[3]; if (stderrName != NoPipe) { var stderr = new NamedPipeClientStream(".", stderrName, PipeDirection.Out, PipeOptions.Asynchronous); stderr.Connect(); Console.SetError(new StreamWriter(stderr) { AutoFlush = true }); } args = args.GetRange(4, args.Count - 4); #else args = args.GetRange(1, args.Count - 1); #endif } else if (Environment.OSVersion.Version.Major == 5) { // Windows XP elevated = true; } else { elevated = IsProcessElevated(); } switch (args[0].ToLower()) { case "install": Install(); return; case "uninstall": Uninstall(); return; case "start": Start(); return; case "stop": Stop(true); return; case "stopwait": Stop(false); return; case "restart": Restart(); return; case "restart!": RestartSelf(); return; case "status": Status(); return; case "test": Test(); return; case "testwait": TestWait(); return; case "help": case "--help": case "-h": case "-?": case "/?": PrintHelp(); return; case "version": PrintVersion(); return; default: Console.WriteLine("Unknown command: " + args[0]); PrintAvailableCommands(); throw new Exception("Unknown command: " + args[0]); } void Install() { if (!elevated) { Elevate(); return; } Log.Info($"Installing service '{Format(config)}'..."); using var scm = ServiceManager.Open(ServiceManagerAccess.CreateService); if (scm.ServiceExists(config.Name)) { Log.Error($"A service with ID '{config.Name}' already exists."); Throw.Command.Win32Exception(Errors.ERROR_SERVICE_EXISTS, "Failed to install the service."); } string?username = null; string?password = null; bool allowServiceLogonRight = false; if (args.Count > 1 && args[1] == "/p") { Credentials.PromptForCredentialsConsole(ref username, ref password); Console.Write("Set Account rights to allow log on as a service (y/n)?: "); var keypressed = Console.ReadKey(); Console.WriteLine(); if (keypressed.Key == ConsoleKey.Y) { allowServiceLogonRight = true; } } else { if (config.ServiceAccount.HasServiceAccount()) { username = config.ServiceAccount.FullUser; password = config.ServiceAccount.Password; allowServiceLogonRight = config.ServiceAccount.AllowServiceLogonRight; } } if (allowServiceLogonRight) { Security.AddServiceLogonRight(config.ServiceAccount.Domain !, config.ServiceAccount.User !); } using var sc = scm.CreateService( config.Name, config.DisplayName, config.Interactive, config.StartMode, $"\"{config.ExecutablePath}\"", config.ServiceDependencies, username, password); string description = config.Description; if (description.Length != 0) { sc.SetDescription(description); } var actions = config.FailureActions; if (actions.Length > 0) { sc.SetFailureActions(config.ResetFailureAfter, actions); } bool isDelayedAutoStart = config.StartMode == ServiceStartMode.Automatic && config.DelayedAutoStart; if (isDelayedAutoStart) { sc.SetDelayedAutoStart(true); } string?securityDescriptor = config.SecurityDescriptor; if (securityDescriptor != null) { // throws ArgumentException sc.SetSecurityDescriptor(new RawSecurityDescriptor(securityDescriptor)); } string eventLogSource = config.Name; if (!EventLog.SourceExists(eventLogSource)) { EventLog.CreateEventSource(eventLogSource, "Application"); } Log.Info($"Service '{Format(config)}' was installed successfully."); } void Uninstall() { if (!elevated) { Elevate(); return; } Log.Info($"Uninstalling service '{Format(config)}'..."); using var scm = ServiceManager.Open(ServiceManagerAccess.Connect); try { using var sc = scm.OpenService(config.Name); if (sc.Status != ServiceControllerStatus.Stopped) { // We could fail the opeartion here, but it would be an incompatible change. // So it is just a warning Log.Warn($"Service '{Format(config)}' is started. It may be impossible to uninstall it."); } sc.Delete(); Log.Info($"Service '{Format(config)}' was uninstalled successfully."); } catch (CommandException e) when(e.InnerException is Win32Exception inner) { switch (inner.NativeErrorCode) { case Errors.ERROR_SERVICE_DOES_NOT_EXIST: Log.Warn($"Service '{Format(config)}' does not exist."); break; // there's no such service, so consider it already uninstalled case Errors.ERROR_SERVICE_MARKED_FOR_DELETE: Log.Error(e.Message); // TODO: change the default behavior to Error? break; // it's already uninstalled, so consider it a success default: Throw.Command.Exception("Failed to uninstall the service.", inner); break; } } } void Start() { if (!elevated) { Elevate(); return; } using var svc = new ServiceController(config.Name); try { Log.Info($"Starting service '{Format(svc)}'..."); svc.Start(); Log.Info($"Service '{Format(svc)}' started successfully."); } catch (InvalidOperationException e) when(e.InnerException is Win32Exception inner && inner.NativeErrorCode == Errors.ERROR_SERVICE_DOES_NOT_EXIST) { Throw.Command.Exception(inner); } catch (InvalidOperationException e) when(e.InnerException is Win32Exception inner && inner.NativeErrorCode == Errors.ERROR_SERVICE_ALREADY_RUNNING) { Log.Info($"Service '{Format(svc)}' has already started."); } } void Stop(bool noWait) { if (!elevated) { Elevate(); return; } using var svc = new ServiceController(config.Name); try { Log.Info($"Stopping service '{Format(svc)}'..."); svc.Stop(); if (!noWait) { try { WaitForStatus(svc, ServiceControllerStatus.Stopped, ServiceControllerStatus.StopPending); } catch (TimeoutException) { Throw.Command.Exception("Failed to stop the service."); } } Log.Info($"Service '{Format(svc)}' stopped successfully."); } catch (InvalidOperationException e) when(e.InnerException is Win32Exception inner && inner.NativeErrorCode == Errors.ERROR_SERVICE_DOES_NOT_EXIST) { Throw.Command.Exception(inner); } catch (InvalidOperationException e) when(e.InnerException is Win32Exception inner && inner.NativeErrorCode == Errors.ERROR_SERVICE_NOT_ACTIVE) { Log.Info($"Service '{Format(svc)}' has already stopped."); } } void Restart() { if (!elevated) { Elevate(); return; } using var svc = new ServiceController(config.Name); List <ServiceController>?startedDependentServices = null; try { if (HasAnyStartedDependentService(svc)) { startedDependentServices = new(); foreach (var service in svc.DependentServices) { if (service.Status != ServiceControllerStatus.Stopped) { startedDependentServices.Add(service); } } } Log.Info($"Stopping service '{Format(svc)}'..."); svc.Stop(); try { WaitForStatus(svc, ServiceControllerStatus.Stopped, ServiceControllerStatus.StopPending); } catch (TimeoutException) { Throw.Command.Exception("Failed to stop the service."); } } catch (InvalidOperationException e) when(e.InnerException is Win32Exception inner && inner.NativeErrorCode == Errors.ERROR_SERVICE_DOES_NOT_EXIST) { Throw.Command.Exception(inner); } catch (InvalidOperationException e) when(e.InnerException is Win32Exception inner && inner.NativeErrorCode == Errors.ERROR_SERVICE_NOT_ACTIVE) { } Log.Info($"Starting service '{Format(svc)}'..."); svc.Start(); try { WaitForStatus(svc, ServiceControllerStatus.Running, ServiceControllerStatus.StartPending); } catch (TimeoutException) { Throw.Command.Exception("Failed to start the service."); } if (startedDependentServices != null) { foreach (var service in startedDependentServices) { if (service.Status == ServiceControllerStatus.Stopped) { Log.Info($"Starting service '{Format(service)}'..."); service.Start(); } } } Log.Info($"Service '{Format(svc)}' restarted successfully."); } void RestartSelf() { if (!elevated) { Throw.Command.Win32Exception(Errors.ERROR_ACCESS_DENIED); } Log.Info("Restarting the service with id '" + config.Name + "'"); // run restart from another process group. see README.md for why this is useful. if (!ProcessApis.CreateProcess( null, config.ExecutablePath + " restart", IntPtr.Zero, IntPtr.Zero, false, ProcessApis.CREATE_NEW_PROCESS_GROUP, IntPtr.Zero, null, default, out var processInfo)) { Throw.Command.Win32Exception("Failed to invoke restart."); } _ = HandleApis.CloseHandle(processInfo.ProcessHandle); _ = HandleApis.CloseHandle(processInfo.ThreadHandle); } void Status() { using var svc = new ServiceController(config.Name); try { Console.WriteLine(svc.Status != ServiceControllerStatus.Stopped ? "Started" : "Stopped"); } catch (InvalidOperationException e) when(e.InnerException is Win32Exception inner && inner.NativeErrorCode == Errors.ERROR_SERVICE_DOES_NOT_EXIST) { Console.WriteLine("NonExistent"); } } void Test() { if (!elevated) { Elevate(); return; } var wsvc = new WrapperService(config); wsvc.RaiseOnStart(args.ToArray()); Thread.Sleep(1000); wsvc.RaiseOnStop(); } void TestWait() { if (!elevated) { Elevate(); return; } var wsvc = new WrapperService(config); wsvc.RaiseOnStart(args.ToArray()); Console.WriteLine("Press any key to stop the service..."); _ = Console.Read(); wsvc.RaiseOnStop(); } // [DoesNotReturn] void Elevate() { #if VNEXT string?stdinName = Console.IsInputRedirected ? Guid.NewGuid().ToString() : null; string?stdoutName = Console.IsOutputRedirected ? Guid.NewGuid().ToString() : null; string?stderrName = Console.IsErrorRedirected ? Guid.NewGuid().ToString() : null; #endif string exe = Environment.GetCommandLineArgs()[0]; string commandLine = Environment.CommandLine; string arguments = "/elevated" + #if VNEXT " " + (stdinName ?? NoPipe) + " " + (stdoutName ?? NoPipe) + " " + (stderrName ?? NoPipe) + #endif commandLine.Remove(commandLine.IndexOf(exe), exe.Length).TrimStart('"'); var startInfo = new ProcessStartInfo { UseShellExecute = true, Verb = "runas", FileName = ExecutablePath, Arguments = arguments, WindowStyle = ProcessWindowStyle.Hidden, }; try { using var elevated = Process.Start(startInfo) !; #if VNEXT if (stdinName != null) { var stdin = new NamedPipeServerStream(stdinName, PipeDirection.Out, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous); stdin.WaitForConnectionAsync().ContinueWith(_ => Console.OpenStandardInput().CopyToAsync(stdin)); } if (stdoutName != null) { var stdout = new NamedPipeServerStream(stdoutName, PipeDirection.In, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous); stdout.WaitForConnectionAsync().ContinueWith(_ => stdout.CopyToAsync(Console.OpenStandardOutput())); } if (stderrName != null) { var stderr = new NamedPipeServerStream(stderrName, PipeDirection.In, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous); stderr.WaitForConnectionAsync().ContinueWith(_ => stderr.CopyToAsync(Console.OpenStandardError())); } #endif elevated.WaitForExit(); Environment.Exit(elevated.ExitCode); } catch (Win32Exception e) when(e.NativeErrorCode == Errors.ERROR_CANCELLED) { Log.Fatal(e.Message); Environment.Exit(e.ErrorCode); } } } private static IServiceConfig LoadConfigAndInitLoggers(bool inConsoleMode) { // TODO: Make logging levels configurable var fileLogLevel = Level.Debug; // TODO: Debug should not be printed to console by default. Otherwise commands like 'status' will be pollutted // This is a workaround till there is a better command line parsing, which will allow determining var consoleLogLevel = Level.Info; var eventLogLevel = Level.Warn; var layout = new PatternLayout { ConversionPattern = "%d %-5p - %m%n" }; layout.ActivateOptions(); var repository = LogManager.GetRepository(Assembly.GetExecutingAssembly()); if (inConsoleMode) { var consoleAppender = new ConsoleAppender { Name = "Wrapper console log", Threshold = consoleLogLevel, Layout = layout, }; consoleAppender.ActivateOptions(); BasicConfigurator.Configure(repository, consoleAppender); } else { var eventLogAppender = new ServiceEventLogAppender(WrapperService.eventLogProvider) { Name = "Wrapper event log", Threshold = eventLogLevel, }; eventLogAppender.ActivateOptions(); BasicConfigurator.Configure(repository, eventLogAppender); } string executablePath = ExecutablePath; string directory = Path.GetDirectoryName(executablePath) !; string baseName = Path.GetFileNameWithoutExtension(executablePath); IServiceConfig config = File.Exists(Path.Combine(directory, baseName + ".xml")) ? new XmlServiceConfig(baseName, directory) : File.Exists(Path.Combine(directory, baseName + ".yml")) ? new YamlServiceConfig(baseName, directory) : throw new FileNotFoundException($"Unable to locate {baseName}.[xml|yml] file within executable directory"); // .wrapper.log string wrapperLogPath = Path.Combine(config.LogDirectory, config.BaseName + ".wrapper.log"); var fileAppender = new FileAppender { AppendToFile = true, File = wrapperLogPath, ImmediateFlush = true, Name = "Wrapper file log", Threshold = fileLogLevel, LockingModel = new FileAppender.MinimalLock(), Layout = layout, }; fileAppender.ActivateOptions(); BasicConfigurator.Configure(repository, fileAppender); return(config); } internal static unsafe bool IsProcessElevated()
async Task AsyncOnStart() { #region logging var layout = new PatternLayout { ConversionPattern = "%d %-5p %c - %m%n" }; layout.ActivateOptions(); var appender = new ConsoleAppender { Layout = layout, Threshold = Level.Info }; appender.ActivateOptions(); BasicConfigurator.Configure(appender); LogManager.Use <Log4NetFactory>(); #endregion #region create-config var endpointConfiguration = new EndpointConfiguration("Samples.FirstEndpoint"); #endregion #region container var builder = new ContainerBuilder(); // configure custom services // builder.RegisterInstance(new MyService()); var container = builder.Build(); endpointConfiguration.UseContainer <AutofacBuilder>( customizations: customizations => { customizations.ExistingLifetimeScope(container); }); #endregion #region serialization endpointConfiguration.UseSerialization <XmlSerializer>(); #endregion #region error endpointConfiguration.SendFailedMessagesTo("error"); #endregion #region audit endpointConfiguration.AuditProcessedMessagesTo("audit"); #endregion #region transport endpointConfiguration.UseTransport <LearningTransport>(); #endregion #region persistence endpointConfiguration.UsePersistence <LearningPersistence>(); #endregion #region critical-errors endpointConfiguration.DefineCriticalErrorAction( onCriticalError: async context => { // Log the critical error log.Fatal($"CRITICAL: {context.Error}", context.Exception); await context.Stop() .ConfigureAwait(false); // Kill the process on a critical error var output = $"NServiceBus critical error:\n{context.Error}\nShutting down."; Environment.FailFast(output, context.Exception); }); #endregion #region start-bus endpointConfiguration.EnableInstallers(); endpointInstance = await Endpoint.Start(endpointConfiguration) .ConfigureAwait(false); #endregion var myMessage = new MyMessage(); await endpointInstance.SendLocal(myMessage) .ConfigureAwait(false); }
public LogService() { var repositoryName = AppUtility.ProductName; var name = "global"; var repository = LogManager.GetAllRepositories().Where(item => item.Name == repositoryName).FirstOrDefault(); if (repository != null) { throw new InvalidOperationException(); } this.hierarchy = (Hierarchy)LogManager.CreateRepository(repositoryName); var xmlLayout = new XmlLayoutSchemaLog4j() { LocationInfo = true }; xmlLayout.ActivateOptions(); this.rollingAppender = new RollingFileAppender() { AppendToFile = true, File = Path.Combine(AppUtility.UserAppDataPath, "logs", "log"), DatePattern = "_yyyy-MM-dd'.xml'", Layout = xmlLayout, Encoding = Encoding.UTF8, MaxSizeRollBackups = 5, MaximumFileSize = "1GB", RollingStyle = RollingFileAppender.RollingMode.Date, StaticLogFileName = false, LockingModel = new RollingFileAppender.MinimalLock() }; this.rollingAppender.ActivateOptions(); var patternLayout = new PatternLayout() { ConversionPattern = conversionPattern }; patternLayout.ActivateOptions(); this.consoleAppender = new ConsoleAppender() { Layout = patternLayout }; this.consoleAppender.AddFilter(new log4net.Filter.LevelRangeFilter() { LevelMin = GetLevel(this.verbose), LevelMax = Level.Fatal, }); this.consoleAppender.ActivateOptions(); this.hierarchy.Root.AddAppender(this.consoleAppender); this.hierarchy.Root.AddAppender(this.rollingAppender); this.hierarchy.Root.Level = Level.All; this.hierarchy.Root.Additivity = false; this.hierarchy.Configured = true; this.log = log4net.LogManager.GetLogger(repositoryName, name); this.name = name; }
public static void Main(string[] args) { ConsoleAppender consoleAppender = new ConsoleAppender(); consoleAppender.Layout = new PatternLayout("%date [%thread] %-5level %logger [%property{NDC}] - %message%newline"); log4net.Config.BasicConfigurator.Configure(consoleAppender); string serverURI = "http://127.0.0.1:8003"; UserAccountServicesConnector m_Connector = new UserAccountServicesConnector(serverURI); UUID user1 = UUID.Random(); string first = "Completely"; string last = "Clueless"; string email = "*****@*****.**"; UserAccount account = new UserAccount(user1); account.FirstName = first; account.LastName = last; account.Email = email; account.ServiceURLs = new Dictionary <string, object>(); account.ServiceURLs.Add("InventoryServerURI", "http://cnn.com"); account.ServiceURLs.Add("AssetServerURI", "http://cnn.com"); bool success = m_Connector.StoreUserAccount(account); if (success) { m_log.InfoFormat("[USER CLIENT]: Successfully created account for user {0} {1}", account.FirstName, account.LastName); } else { m_log.InfoFormat("[USER CLIENT]: failed to create user {0} {1}", account.FirstName, account.LastName); } System.Console.WriteLine("\n"); account = m_Connector.GetUserAccount(UUID.Zero, user1); if (account == null) { m_log.InfoFormat("[USER CLIENT]: Unable to retrieve accouny by UUID for {0}", user1); } else { m_log.InfoFormat("[USER CLIENT]: Account retrieved correctly: userID={0}; FirstName={1}; LastName={2}; Email={3}", account.PrincipalID, account.FirstName, account.LastName, account.Email); foreach (KeyValuePair <string, object> kvp in account.ServiceURLs) { m_log.DebugFormat("\t {0} -> {1}", kvp.Key, kvp.Value); } } System.Console.WriteLine("\n"); account = m_Connector.GetUserAccount(UUID.Zero, first, last); if (account == null) { m_log.InfoFormat("[USER CLIENT]: Unable to retrieve accouny by name for {0}", user1); } else { m_log.InfoFormat("[USER CLIENT]: Account retrieved correctly: userID={0}; FirstName={1}; LastName={2}; Email={3}", account.PrincipalID, account.FirstName, account.LastName, account.Email); foreach (KeyValuePair <string, object> kvp in account.ServiceURLs) { m_log.DebugFormat("\t {0} -> {1}", kvp.Key, kvp.Value); } } System.Console.WriteLine("\n"); account = m_Connector.GetUserAccount(UUID.Zero, email); if (account == null) { m_log.InfoFormat("[USER CLIENT]: Unable to retrieve accouny by email for {0}", user1); } else { m_log.InfoFormat("[USER CLIENT]: Account retrieved correctly: userID={0}; FirstName={1}; LastName={2}; Email={3}", account.PrincipalID, account.FirstName, account.LastName, account.Email); foreach (KeyValuePair <string, object> kvp in account.ServiceURLs) { m_log.DebugFormat("\t {0} -> {1}", kvp.Key, kvp.Value); } } }
//IBlazorApplicationBuilder //IComponentsApplicationBuilder public void Configure(IComponentsApplicationBuilder app) { bool result1 = WebRequest.RegisterPrefix("http://", new FakeRequestFactory()); Console.WriteLine("webrequestmod " + result1); bool result2 = WebRequest.RegisterPrefix("https://", new FakeRequestFactory()); Console.WriteLine("webrequestmod " + result2); app.AddComponent <App>("app"); log4net.Repository.Hierarchy.Hierarchy hierarchy = (Hierarchy)log4net.LogManager.GetRepository(Assembly.GetAssembly(typeof(Startup))); PatternLayout patternLayout = new PatternLayout(); patternLayout.ConversionPattern = "%date [%thread] %-5level %logger - %message%newline"; patternLayout.ActivateOptions(); var cca = new ConsoleAppender(); cca.Layout = patternLayout; cca.ActivateOptions(); hierarchy.Root.AddAppender(cca); hierarchy.Root.Level = Level.Debug; hierarchy.Configured = true; log.Info("test"); log.Info("Configure Done"); //System.Net.WebRequest.get_InternalDefaultWebProxy //WebRequest.DefaultWebProxy = GlobalProxySelection.GetEmptyWebProxy(); Directory.CreateDirectory(@"/home/web_user/Desktop"); BinaryLog.onFlightMode += (firmware, modeno) => { try { if (firmware == "") { return(null); } var modes = Common.getModesList((Firmwares)Enum.Parse(typeof(Firmwares), firmware)); string currentmode = null; foreach (var mode in modes) { if (mode.Key == modeno) { currentmode = mode.Value; break; } } return(currentmode); } catch { return(null); } }; CustomMessageBox.ShowEvent += (text, caption, buttons, icon, yestext, notext) => { Console.WriteLine("CustomMessageBox " + caption + " " + text); return(CustomMessageBox.DialogResult.OK); }; }
public static void Main(string[] args) { ConsoleAppender consoleAppender = new ConsoleAppender(); consoleAppender.Layout = new PatternLayout("%date [%thread] %-5level %logger [%property{NDC}] - %message%newline"); log4net.Config.BasicConfigurator.Configure(consoleAppender); string serverURI = "http://127.0.0.1:8003"; PresenceServicesConnector m_Connector = new PresenceServicesConnector(serverURI); UUID user1 = UUID.Random(); UUID session1 = UUID.Random(); UUID region1 = UUID.Random(); bool success = m_Connector.LoginAgent(user1.ToString(), session1, UUID.Zero); if (success) { m_log.InfoFormat("[PRESENCE CLIENT]: Successfully logged in user {0} with session {1}", user1, session1); } else { m_log.InfoFormat("[PRESENCE CLIENT]: failed to login user {0}", user1); } System.Console.WriteLine("\n"); PresenceInfo pinfo = m_Connector.GetAgent(session1); if (pinfo == null) { m_log.InfoFormat("[PRESENCE CLIENT]: Unable to retrieve presence for {0}", user1); } else { m_log.InfoFormat("[PRESENCE CLIENT]: Presence retrieved correctly: userID={0}; regionID={1}", pinfo.UserID, pinfo.RegionID); } System.Console.WriteLine("\n"); success = m_Connector.ReportAgent(session1, region1); if (success) { m_log.InfoFormat("[PRESENCE CLIENT]: Successfully reported session {0} in region {1}", user1, region1); } else { m_log.InfoFormat("[PRESENCE CLIENT]: failed to report session {0}", session1); } pinfo = m_Connector.GetAgent(session1); if (pinfo == null) { m_log.InfoFormat("[PRESENCE CLIENT]: Unable to retrieve presence for {0} for second time", user1); } else { m_log.InfoFormat("[PRESENCE CLIENT]: Presence retrieved correctly: userID={0}; regionID={2}", pinfo.UserID, pinfo.RegionID); } System.Console.WriteLine("\n"); success = m_Connector.LogoutAgent(session1); if (success) { m_log.InfoFormat("[PRESENCE CLIENT]: Successfully logged out user {0}", user1); } else { m_log.InfoFormat("[PRESENCE CLIENT]: failed to logout user {0}", user1); } pinfo = m_Connector.GetAgent(session1); if (pinfo == null) { m_log.InfoFormat("[PRESENCE CLIENT]: Unable to retrieve presence for {0} for fourth time", user1); } else { m_log.InfoFormat("[PRESENCE CLIENT]: Presence retrieved correctly: userID={0}; regionID={1}", pinfo.UserID, pinfo.RegionID); } System.Console.WriteLine("\n"); success = m_Connector.ReportAgent(session1, UUID.Random()); if (success) { m_log.InfoFormat("[PRESENCE CLIENT]: Report agent succeeded, but this is wrong"); } else { m_log.InfoFormat("[PRESENCE CLIENT]: failed to report agent, as it should because user is not logged in"); } }
static void Main(string[] args) { List <IAppender> testAppender = new List <IAppender>(); ILayout layout = null; ILogFile logFile = new LogFile(); var repeat = int.Parse(Console.ReadLine()); for (int i = 0; i < repeat; i++) { IAppender appender = null; var inputCommand = Console.ReadLine().Split(' '); if (inputCommand[1] == "SimpleLayout") { layout = new SimpleLayout(); } if (inputCommand[1] == "XmlLayout") { layout = new XmlLayout(); } if (inputCommand[0] == "ConsoleAppender") { appender = new ConsoleAppender(layout); } else if (inputCommand[0] == "FileAppender") { appender = new FileAppender(layout, logFile); } if (inputCommand.Length == 3) { foreach (ReportLevel current in Enum.GetValues(typeof(ReportLevel))) { if (current.ToString().ToLower() == inputCommand[2].ToLower()) { appender.ReportLevel = current; } } } testAppender.Add(appender); } ILogger logger = new Logger(testAppender.ToArray()); while (true) { var inputCommand = Console.ReadLine().Split('|'); if (inputCommand[0] == "END") { break; } switch (inputCommand[0]) { case "INFO": logger.Info(inputCommand[1], inputCommand[2]); break; case "WARNING": logger.Warning(inputCommand[1], inputCommand[2]); break; case "ERROR": logger.Error(inputCommand[1], inputCommand[2]); break; case "CRITICAL": logger.Critical(inputCommand[1], inputCommand[2]); break; case "FATAL": logger.Fatal(inputCommand[1], inputCommand[2]); break; default: break; } } }
// private static readonly ILog m_log = // LogManager.GetLogger( // MethodBase.GetCurrentMethod().DeclaringType); public static void Main(string[] args) { ConsoleAppender consoleAppender = new ConsoleAppender(); consoleAppender.Layout = new PatternLayout("%date [%thread] %-5level %logger [%property{NDC}] - %message%newline"); log4net.Config.BasicConfigurator.Configure(consoleAppender); string serverURI = "http://127.0.0.1:8001"; GridServicesConnector m_Connector = new GridServicesConnector(serverURI); GridRegion r1 = CreateRegion("Test Region 1", 1000, 1000); GridRegion r2 = CreateRegion("Test Region 2", 1001, 1000); GridRegion r3 = CreateRegion("Test Region 3", 1005, 1000); Console.WriteLine("[GRID CLIENT]: *** Registering region 1"); string msg = m_Connector.RegisterRegion(UUID.Zero, r1); if (msg == String.Empty) { Console.WriteLine("[GRID CLIENT]: Successfully registered region 1"); } else { Console.WriteLine("[GRID CLIENT]: region 1 failed to register"); } Console.WriteLine("[GRID CLIENT]: *** Registering region 2"); msg = m_Connector.RegisterRegion(UUID.Zero, r2); if (msg == String.Empty) { Console.WriteLine("[GRID CLIENT]: Successfully registered region 2"); } else { Console.WriteLine("[GRID CLIENT]: region 2 failed to register"); } Console.WriteLine("[GRID CLIENT]: *** Registering region 3"); msg = m_Connector.RegisterRegion(UUID.Zero, r3); if (msg == String.Empty) { Console.WriteLine("[GRID CLIENT]: Successfully registered region 3"); } else { Console.WriteLine("[GRID CLIENT]: region 3 failed to register"); } bool success; Console.WriteLine("[GRID CLIENT]: *** Deregistering region 3"); success = m_Connector.DeregisterRegion(r3.RegionID); if (success) { Console.WriteLine("[GRID CLIENT]: Successfully deregistered region 3"); } else { Console.WriteLine("[GRID CLIENT]: region 3 failed to deregister"); } Console.WriteLine("[GRID CLIENT]: *** Registering region 3 again"); msg = m_Connector.RegisterRegion(UUID.Zero, r3); if (msg == String.Empty) { Console.WriteLine("[GRID CLIENT]: Successfully registered region 3"); } else { Console.WriteLine("[GRID CLIENT]: region 3 failed to register"); } Console.WriteLine("[GRID CLIENT]: *** GetNeighbours of region 1"); List <GridRegion> regions = m_Connector.GetNeighbours(UUID.Zero, r1.RegionID); if (regions == null) { Console.WriteLine("[GRID CLIENT]: GetNeighbours of region 1 failed"); } else if (regions.Count > 0) { if (regions.Count != 1) { Console.WriteLine("[GRID CLIENT]: GetNeighbours of region 1 returned more neighbours than expected: " + regions.Count); } else { Console.WriteLine("[GRID CLIENT]: GetNeighbours of region 1 returned the right neighbour " + regions[0].RegionName); } } else { Console.WriteLine("[GRID CLIENT]: GetNeighbours of region 1 returned 0 neighbours"); } Console.WriteLine("[GRID CLIENT]: *** GetRegionByUUID of region 2 (this should succeed)"); GridRegion region = m_Connector.GetRegionByUUID(UUID.Zero, r2.RegionID); if (region == null) { Console.WriteLine("[GRID CLIENT]: GetRegionByUUID returned null"); } else { Console.WriteLine("[GRID CLIENT]: GetRegionByUUID returned region " + region.RegionName); } Console.WriteLine("[GRID CLIENT]: *** GetRegionByUUID of non-existent region (this should fail)"); region = m_Connector.GetRegionByUUID(UUID.Zero, UUID.Random()); if (region == null) { Console.WriteLine("[GRID CLIENT]: GetRegionByUUID returned null"); } else { Console.WriteLine("[GRID CLIENT]: GetRegionByUUID returned region " + region.RegionName); } Console.WriteLine("[GRID CLIENT]: *** GetRegionByName of region 3 (this should succeed)"); region = m_Connector.GetRegionByName(UUID.Zero, r3.RegionName); if (region == null) { Console.WriteLine("[GRID CLIENT]: GetRegionByName returned null"); } else { Console.WriteLine("[GRID CLIENT]: GetRegionByName returned region " + region.RegionName); } Console.WriteLine("[GRID CLIENT]: *** GetRegionByName of non-existent region (this should fail)"); region = m_Connector.GetRegionByName(UUID.Zero, "Foo"); if (region == null) { Console.WriteLine("[GRID CLIENT]: GetRegionByName returned null"); } else { Console.WriteLine("[GRID CLIENT]: GetRegionByName returned region " + region.RegionName); } Console.WriteLine("[GRID CLIENT]: *** GetRegionsByName (this should return 3 regions)"); regions = m_Connector.GetRegionsByName(UUID.Zero, "Test", 10); if (regions == null) { Console.WriteLine("[GRID CLIENT]: GetRegionsByName returned null"); } else { Console.WriteLine("[GRID CLIENT]: GetRegionsByName returned " + regions.Count + " regions"); } Console.WriteLine("[GRID CLIENT]: *** GetRegionRange (this should return 2 regions)"); regions = m_Connector.GetRegionRange(UUID.Zero, 900 * (int)Constants.RegionSize, 1002 * (int)Constants.RegionSize, 900 * (int)Constants.RegionSize, 1002 * (int)Constants.RegionSize); if (regions == null) { Console.WriteLine("[GRID CLIENT]: GetRegionRange returned null"); } else { Console.WriteLine("[GRID CLIENT]: GetRegionRange returned " + regions.Count + " regions"); } Console.WriteLine("[GRID CLIENT]: *** GetRegionRange (this should return 0 regions)"); regions = m_Connector.GetRegionRange(UUID.Zero, 900 * (int)Constants.RegionSize, 950 * (int)Constants.RegionSize, 900 * (int)Constants.RegionSize, 950 * (int)Constants.RegionSize); if (regions == null) { Console.WriteLine("[GRID CLIENT]: GetRegionRange returned null"); } else { Console.WriteLine("[GRID CLIENT]: GetRegionRange returned " + regions.Count + " regions"); } Console.Write("Proceed to deregister? Press enter..."); Console.ReadLine(); // Deregister them all Console.WriteLine("[GRID CLIENT]: *** Deregistering region 1"); success = m_Connector.DeregisterRegion(r1.RegionID); if (success) { Console.WriteLine("[GRID CLIENT]: Successfully deregistered region 1"); } else { Console.WriteLine("[GRID CLIENT]: region 1 failed to deregister"); } Console.WriteLine("[GRID CLIENT]: *** Deregistering region 2"); success = m_Connector.DeregisterRegion(r2.RegionID); if (success) { Console.WriteLine("[GRID CLIENT]: Successfully deregistered region 2"); } else { Console.WriteLine("[GRID CLIENT]: region 2 failed to deregister"); } Console.WriteLine("[GRID CLIENT]: *** Deregistering region 3"); success = m_Connector.DeregisterRegion(r3.RegionID); if (success) { Console.WriteLine("[GRID CLIENT]: Successfully deregistered region 3"); } else { Console.WriteLine("[GRID CLIENT]: region 3 failed to deregister"); } }
public void Act(int countOfAppenders) { IAppender[] appenders = new IAppender[countOfAppenders]; for (int i = 0; i < countOfAppenders; i++) { var input = Console.ReadLine().Split(); ILayout layout = null; switch (input[1]) { case nameof(SimpleLayout): layout = new SimpleLayout(); break; case nameof(XmlLayout): layout = new XmlLayout(); break; default: throw new ArgumentException(); } IAppender appender = null; switch (input[0]) { case nameof(ConsoleAppender): appender = new ConsoleAppender(layout); break; case nameof(FileAppender): appender = new FileAppender(layout); ((FileAppender)appender).File = new LogFile(); break; } if (input.Length == 3) { ReportLevel level = (ReportLevel)Enum.Parse(typeof(ReportLevel), input[2]); appender.ReportLevel = level; } appenders[i] = appender; } var logger = new Logger(appenders); string command; while ((command = Console.ReadLine()) != "END") { var input = command.Split('|'); string time = input[1]; string message = input[2]; ReportLevel level = (ReportLevel)Enum.Parse(typeof(ReportLevel), input[0]); switch (level) { case ReportLevel.CRITICAL: logger.Critical(time, message); break; case ReportLevel.ERROR: logger.Error(time, message); break; case ReportLevel.FATAL: logger.Fatal(time, message); break; case ReportLevel.INFO: logger.Info(time, message); break; case ReportLevel.WARNING: logger.Warn(time, message); break; } } Console.WriteLine(logger); }