public static void InitializeConsoleDebugLogger() { LoggingConfiguration config = new LoggingConfiguration(); ColoredConsoleTarget ct = new ColoredConsoleTarget(); ct.Layout = "${message}"; config.AddTarget("Console", ct); config.LoggingRules.Add(new LoggingRule("*", LogLevel.Debug, ct)); LogManager.Configuration = config; }
private static void Main(string[] args) { var config = new LoggingConfiguration(); var consoleTarget = new ColoredConsoleTarget(); config.AddTarget("console", consoleTarget); config.LoggingRules.Add(new LoggingRule("*", LogLevel.Debug, consoleTarget)); LogManager.Configuration = config; Foo.Bar(); Console.ReadLine(); }
public NLogFiltering() { #region NLogFiltering LoggingConfiguration config = new LoggingConfiguration(); ColoredConsoleTarget target = new ColoredConsoleTarget(); config.AddTarget("console", target); config.LoggingRules.Add(new LoggingRule("MyNamespace.*", LogLevel.Debug, target)); LogManager.Configuration = config; SetLoggingLibrary.NLog(); #endregion }
public NLogFiltering() { #region NLogFiltering LoggingConfiguration config = new LoggingConfiguration(); ColoredConsoleTarget target = new ColoredConsoleTarget(); config.AddTarget("console", target); config.LoggingRules.Add(new LoggingRule("MyNamespace.*", LogLevel.Debug, target)); LogManager.Configuration = config; NServiceBus.Logging.LogManager.Use<NLogFactory>(); #endregion }
public static void InitializeSyslogLogger(int port, bool console) { LoggingConfiguration config = new LoggingConfiguration(); SyslogTarget st = new SyslogTarget(); st.Port = port; config.AddTarget("Syslog", st); config.LoggingRules.Add(new LoggingRule("*", LogLevel.Debug, st)); if (console) { ColoredConsoleTarget ct = new ColoredConsoleTarget(); ct.Layout = "${message}"; config.AddTarget("Console", ct); config.LoggingRules.Add(new LoggingRule("*", LogLevel.Debug, ct)); } LogManager.Configuration = config; }
Usage() { #region NLogInCode LoggingConfiguration config = new LoggingConfiguration(); ColoredConsoleTarget consoleTarget = new ColoredConsoleTarget { Layout = "${level}|${logger}|${message}${onexception:${newline}${exception:format=tostring}}" }; config.AddTarget("console", consoleTarget); config.LoggingRules.Add(new LoggingRule("*", LogLevel.Debug, consoleTarget)); LogManager.Configuration = config; NServiceBus.Logging.LogManager.Use<NLogFactory>(); #endregion }
public static LoggingConfiguration GetLoggingConfiguration(RuntimeSettings settings, bool fileOnly = false) { var logFileName = settings.CustomLogFileName ?? "log.txt"; var logLevel = settings.TracingEnabled ? NLog.LogLevel.Debug : NLog.LogLevel.Info; // Add custom date time format renderer as the default is too long ConfigurationItemFactory.Default.LayoutRenderers.RegisterDefinition("simpledatetime", typeof(SimpleDateTimeRenderer)); var logConfig = new LoggingConfiguration(); var logFile = new FileTarget { Layout = "${longdate} ${level} ${message} ${exception:format=ToString}", FileName = Path.Combine(settings.DataFolder, logFileName), ArchiveFileName = Path.Combine(settings.DataFolder, logFileName + ".{#####}.txt"), ArchiveAboveSize = 2097152, // 2 MB MaxArchiveFiles = 5, KeepFileOpen = false, ArchiveNumbering = ArchiveNumberingMode.DateAndSequence }; logConfig.AddTarget("file", logFile); var microsoftRule = new LoggingRule { LoggerNamePattern = "Microsoft.*", Final = true }; microsoftRule.SetLoggingLevels(LogLevel.Warn, LogLevel.Fatal); microsoftRule.Targets.Add(logFile); var microsoftDebugRule = new LoggingRule { LoggerNamePattern = "Microsoft.*" }; microsoftDebugRule.SetLoggingLevels(LogLevel.Debug, LogLevel.Info); microsoftDebugRule.Final = true; if (settings.TracingEnabled) { microsoftDebugRule.Targets.Add(logFile); } logConfig.LoggingRules.Add(microsoftDebugRule); var logFileRule = new LoggingRule("*", logLevel, logFile); logConfig.LoggingRules.Add(logFileRule); if (!fileOnly) { var logConsole = new ColoredConsoleTarget { Layout = "${simpledatetime} ${level} ${message} ${exception:format=ToString}" }; logConfig.AddTarget("console", logConsole); var logConsoleRule = new LoggingRule("*", logLevel, logConsole); logConfig.LoggingRules.Add(logConsoleRule); var logService = new LogCacheService(); logConfig.AddTarget("service", logService); var serviceRule = new LoggingRule("*", logLevel, logService); logConfig.LoggingRules.Add(serviceRule); microsoftRule.Targets.Add(logConsole); microsoftRule.Targets.Add(logService); if (settings.TracingEnabled) { microsoftDebugRule.Targets.Add(logConsole); microsoftDebugRule.Targets.Add(logService); } } logConfig.LoggingRules.Add(microsoftRule); return(logConfig); }
public static void Setup(bool performanceCritical = false) { if (logger != null) { throw new Exception($"{nameof(Log)} setup should only be executed once."); } logger = LogManager.GetCurrentClassLogger(); LoggingConfiguration config = new LoggingConfiguration(); string layout = $@"[${{date:format=HH\:mm\:ss}} {GetLoggerName()}${{event-properties:item={nameof(PlayerName)}}}][${{level:uppercase=true}}] ${{message}} ${{exception}}"; // Targets where to log to: File and Console ColoredConsoleTarget logConsole = new ColoredConsoleTarget(nameof(logConsole)) { Layout = layout, DetectConsoleAvailable = true }; logConsole.RowHighlightingRules.Add(new ConsoleRowHighlightingRule { Condition = ConditionParser.ParseExpression("level == LogLevel.Error"), ForegroundColor = ConsoleOutputColor.Red }); logConsole.RowHighlightingRules.Add(new ConsoleRowHighlightingRule { Condition = ConditionParser.ParseExpression("level == LogLevel.Warn"), ForegroundColor = ConsoleOutputColor.Yellow }); logConsole.RowHighlightingRules.Add(new ConsoleRowHighlightingRule { Condition = ConditionParser.ParseExpression("level == LogLevel.Debug"), ForegroundColor = ConsoleOutputColor.DarkGray }); FileTarget logFile = new FileTarget(nameof(logFile)) { FileName = $"Nitrox Logs/Nitrox-{GetLoggerName()}.log", ArchiveFileName = "Nitrox Logs/archives/Nitrox-{GetLoggerName()}.{#}.log", ArchiveEvery = FileArchivePeriod.Day, ArchiveNumbering = ArchiveNumberingMode.Date, MaxArchiveFiles = 7, Layout = layout, EnableArchiveFileCompression = true, }; AsyncTargetWrapper logFileAsync = new AsyncTargetWrapper(logFile, 1000, AsyncTargetWrapperOverflowAction.Grow); // Rules for mapping loggers to targets config.AddRule(LogLevel.Debug, LogLevel.Fatal, logConsole); config.AddRule(LogLevel.Debug, LogLevel.Fatal, logFileAsync); config.AddRuleForOneLevel(LogLevel.Info, new MethodCallTarget("ingame", (evt, obj) => { if (InGameLogger == null) { return; } evt.Properties.TryGetValue("game", out object isGameLog); if (isGameLog != null && (bool)isGameLog) { InGameLogger.Log(evt.FormattedMessage); } })); AddSensitiveFilter(config, target => target is AsyncTargetWrapper || target is FileTarget); // Apply config LogManager.Configuration = config; if (!performanceCritical) { TimeSource.Current = new AccurateLocalTimeSource(); } }
public Program(string[] args) { AppDomain.CurrentDomain.DomainUnload += new EventHandler(CurrentDomain_DomainUnload); Console.CancelKeyPress += new ConsoleCancelEventHandler(Console_CancelKeyPress); RunConfiguration config = new RunConfiguration(); config.debug = false; try { string analyzer = null; bool test = false; string agent = null; var definedValues = new List <string>(); bool parseOnly = false; var color = Console.ForegroundColor; Console.Write("\n"); Console.ForegroundColor = ConsoleColor.DarkRed; Console.Write("[[ "); Console.ForegroundColor = ConsoleColor.DarkCyan; Console.WriteLine(ProductName); Console.ForegroundColor = ConsoleColor.DarkRed; Console.Write("[[ "); Console.ForegroundColor = ConsoleColor.DarkCyan; Console.WriteLine(Copyright); Console.WriteLine(); Console.ForegroundColor = color; if (args.Length == 0) { Syntax(); } var p = new OptionSet() { { "h|?|help", v => Syntax() }, { "analyzer=", v => analyzer = v }, { "debug", v => config.debug = true }, { "1", v => config.singleIteration = true }, { "range=", v => ParseRange(config, v) }, { "t|test", v => test = true }, { "c|count", v => config.countOnly = true }, { "skipto=", v => config.skipToIteration = Convert.ToUInt32(v) }, { "seed=", v => config.randomSeed = Convert.ToUInt32(v) }, { "p|parallel=", v => ParseParallel(config, v) }, { "a|agent=", v => agent = v }, { "D|define=", v => AddNewDefine(v) }, { "definedvalues=", v => definedValues.Add(v) }, { "parseonly", v => parseOnly = true }, { "bob", var => bob() }, { "charlie", var => Charlie() }, { "showdevices", var => ShowDevices() }, { "showenv", var => ShowEnvironment() }, { "inputFilePath=", v => config.inputFilePath = v }, { "outputFilePath=", v => config.outputFilePath = v }, }; List <string> extra = p.Parse(args); if (extra.Count == 0 && agent == null && analyzer == null) { Syntax(); } Platform.LoadAssembly(); AddNewDefine("Peach.Cwd=" + Environment.CurrentDirectory); foreach (var definedValuesFile in definedValues) { var defs = PitParser.parseDefines(definedValuesFile); foreach (var kv in defs) { // Allow command line to override values in XML file. if (!DefinedValues.ContainsKey(kv.Key)) { DefinedValues.Add(kv.Key, kv.Value); } } } // Enable debugging if asked for if (config.debug) { var nconfig = new LoggingConfiguration(); var consoleTarget = new ColoredConsoleTarget(); nconfig.AddTarget("console", consoleTarget); consoleTarget.Layout = "${logger} ${message}"; var rule = new LoggingRule("*", LogLevel.Debug, consoleTarget); nconfig.LoggingRules.Add(rule); LogManager.Configuration = nconfig; } if (agent != null) { var agentType = ClassLoader.FindTypeByAttribute <AgentServerAttribute>((x, y) => y.name == agent); if (agentType == null) { Console.WriteLine("Error, unable to locate agent server for protocol '" + agent + "'.\n"); return; } var agentServer = Activator.CreateInstance(agentType) as IAgentServer; ConsoleWatcher.WriteInfoMark(); Console.WriteLine("Starting agent server"); agentServer.Run(new Dictionary <string, string>()); return; } if (analyzer != null) { var analyzerType = ClassLoader.FindTypeByAttribute <AnalyzerAttribute>((x, y) => y.Name == analyzer); if (analyzerType == null) { Console.WriteLine("Error, unable to locate analyzer called '" + analyzer + "'.\n"); return; } var field = analyzerType.GetField("supportCommandLine", BindingFlags.Static | BindingFlags.Public | BindingFlags.FlattenHierarchy); if ((bool)field.GetValue(null) == false) { Console.WriteLine("Error, analyzer not configured to run from command line."); return; } var analyzerInstance = Activator.CreateInstance(analyzerType) as Analyzer; ConsoleWatcher.WriteInfoMark(); Console.WriteLine("Starting Analyzer"); analyzerInstance.asCommandLine(new Dictionary <string, string>()); return; } Dictionary <string, object> parserArgs = new Dictionary <string, object>(); parserArgs[PitParser.DEFINED_VALUES] = this.DefinedValues; if (test) { ConsoleWatcher.WriteInfoMark(); Console.Write("Validating file [" + extra[0] + "]... "); Analyzer.defaultParser.asParserValidation(parserArgs, extra[0]); if (Type.GetType("Mono.Runtime") != null) { Console.WriteLine("File parsed successfully, but XSD validation is not supported on the Mono runtime."); } else { Console.WriteLine("No Errors Found."); } return; } Engine e = new Engine(GetUIWatcher()); dom = GetParser(e).asParser(parserArgs, extra[0]); config.pitFile = extra[0]; // Used for unittests if (parseOnly) { return; } foreach (string arg in args) { config.commandLine += arg + " "; } if (extra.Count > 1) { if (!dom.tests.ContainsKey(extra[1])) { throw new PeachException("Error, unable to locate test named \"" + extra[1] + "\"."); } e.startFuzzing(dom, dom.tests[extra[1]], config); } else { e.startFuzzing(dom, config); } exitCode = 0; } catch (SyntaxException) { // Ignore, thrown by syntax() } catch (OptionException oe) { Console.WriteLine(oe.Message + "\n"); } catch (PeachException ee) { if (config.debug) { Console.WriteLine(ee); } else { Console.WriteLine(ee.Message + "\n"); } } finally { // HACK - Required on Mono with NLog 2.0 LogManager.Configuration = null; // Reset console colors Console.ForegroundColor = DefaultForground; } }
public static void Main(string[] args) { string filename = ""; string logs = ""; try { LOG.Trace($"Args: {string.Join(", ", args)}"); if (args[0] == "-c") { filename = args[1]; } if (args[2] == "-l") { logs = args[3]; } else { LOG.Warn("Use '-c <filename> -l <log_filename>' to pass a config file to program and set where logs should be"); } } catch (IndexOutOfRangeException) { LOG.Warn("Use '-c <filename> -l <log_filename>' to pass a config file to program and set where logs should be"); LOG.Warn("Using MockConfigurationParser instead"); } IConfigurationParser configurationParser; if (string.IsNullOrWhiteSpace(filename)) { configurationParser = new MockConfigurationParser(); } else { configurationParser = new XmlConfigurationParser(filename); } Configuration configuration = configurationParser.ParseConfiguration(); LoggingConfiguration config = new LoggingConfiguration(); ColoredConsoleTarget consoleTarget = new ColoredConsoleTarget { Name = "console", Layout = "[${time} | ${level:format=FirstCharacter} | ${logger}] ${message}" }; FileTarget fileTarget = new FileTarget { FileName = logs + "/ClientNode_" + configuration.ClientAlias + ".log", DeleteOldFileOnStartup = true, Layout = "[${time} | ${level:format=FirstCharacter} | ${logger}] ${message}" }; config.AddRule(LogLevel.Trace, LogLevel.Fatal, consoleTarget); config.AddRule(LogLevel.Debug, LogLevel.Fatal, fileTarget); LogManager.Configuration = config; IClientPortFactory clientPortFactory = new ClientPortFactory(configuration); ICommandParser commandParser = new CommandParser(configuration); IClientNodeManager clientNodeManager = new ClientNodeManager(configuration, clientPortFactory); IUserInterface userInterface = new UserInterface(commandParser, clientNodeManager); try { Console.Title = configuration.ClientAlias; } catch (Exception) { LOG.Trace("Could not set the title"); } userInterface.Start(); }
// private methods... private static LoggingConfiguration GetNlogConfig(int level, string logFilePath) { var config = new LoggingConfiguration(); var loglevel = LogLevel.Info; switch (level) { case 1: loglevel = LogLevel.Debug; break; case 2: loglevel = LogLevel.Trace; break; default: break; } var callsite = "${callsite:className=false}"; if (loglevel < LogLevel.Trace) { //if trace use expanded callstack callsite = "${callsite:className=false:fileName=true:includeSourcePath=true:methodName=true}"; } // Step 2. Create targets and add them to the configuration var consoleTarget = new ColoredConsoleTarget(); //var consoleWrapper = new AsyncTargetWrapper(); //consoleWrapper.WrappedTarget = consoleTarget; //consoleWrapper.QueueLimit = 5000; //consoleWrapper.OverflowAction = AsyncTargetWrapperOverflowAction.Grow; // config.AddTarget("console", consoleWrapper); config.AddTarget("console", consoleTarget); if (logFilePath != null) { if (Directory.Exists(logFilePath)) { var fileTarget = new FileTarget(); //var fileWrapper = new AsyncTargetWrapper(); //fileWrapper.WrappedTarget = fileTarget; //fileWrapper.QueueLimit = 5000; //fileWrapper.OverflowAction = AsyncTargetWrapperOverflowAction.Grow; //config.AddTarget("file", fileWrapper); config.AddTarget("file", fileTarget); fileTarget.FileName = $"{logFilePath}/{Guid.NewGuid()}_log.txt"; // "${basedir}/file.txt"; fileTarget.Layout = @"${longdate} ${logger} " + callsite + " ${level:uppercase=true} ${message} ${exception:format=ToString,StackTrace}"; //var rule2 = new LoggingRule("*", loglevel, fileWrapper); var rule2 = new LoggingRule("*", loglevel, fileTarget); config.LoggingRules.Add(rule2); } } consoleTarget.Layout = @"${longdate} ${logger} " + callsite + " ${level:uppercase=true} ${message} ${exception:format=ToString,StackTrace}"; // Step 4. Define rules // var rule1 = new LoggingRule("*", loglevel, consoleWrapper); var rule1 = new LoggingRule("*", loglevel, consoleTarget); config.LoggingRules.Add(rule1); return(config); }
private static void TestLog() { var config = new LoggingConfiguration(); var consoleTarget = new ColoredConsoleTarget("target1") { Layout = @"${date:format=HH\:mm\:ss} ${level} ${message} ${exception}" }; config.AddTarget(consoleTarget); var fileTarget = new FileTarget("target2") { FileName = @"C:\Log\${logger}/file.txt", Layout = "${longdate} ${level} ${message} ${exception}" }; config.AddTarget(fileTarget); config.AddRuleForAllLevels(consoleTarget); config.AddRuleForOneLevel(LogLevel.Error, fileTarget); LogManager.Configuration = config; Logger logger2 = LogManager.GetLogger("Example2"); // var records = RecordFactory.CreateImageRecords(); // InsertImageRecordToDb(records); //Importer importer = new Importer(new MongoStudyRepository()); //string path = @"C:\DCMFolder\imagedb\1.2.86.76547135.7.210278.20170306131520"; //importer.ImportAsync(path).Wait(); //var _studyRepo = new MongoStudyRepository(); //string seriesUID = "2.16.840.1.114492.4530665600623454105.206257310733.43174.24"; //var series = _studyRepo.FindSeries(seriesUID); //Console.WriteLine(series.ImageCollection.Count); //Console.WriteLine("3&#\x00B2()"); // config.AddRule(LogLevel.Info, LogLevel.Fatal, consoleTarget); Logger logger = LogManager.GetLogger("Example"); logger.Trace("trace log message"); logger.Debug("debug log message"); logger.Info("info log message"); logger.Warn("warn log message"); logger.Error("error log message"); logger.Fatal("fatal log message"); logger2.Trace("trace log message"); logger2.Debug("debug log message"); logger2.Info("info log message"); logger2.Warn("warn log message"); logger2.Error("error log message"); logger2.Fatal("fatal log message"); throw new Exception("test exeption"); }
private static void SetupNLog() { var config = new LoggingConfiguration(); var loglevel = LogLevel.Info; var layout = @"${message}"; var consoleTarget = new ColoredConsoleTarget(); config.AddTarget("console", consoleTarget); consoleTarget.Layout = layout; var rule1 = new LoggingRule("*", loglevel, consoleTarget); config.LoggingRules.Add(rule1); LogManager.Configuration = config; }
public static void InitializeLogger() { var loggingConfig = new LoggingConfiguration(); var coloredConsoleTarget = new ColoredConsoleTarget() { Layout = "[${logger:shortName=true}] - ${shortdate}\n${message}\n" }; loggingConfig.AddTarget("Console", coloredConsoleTarget); loggingConfig.LoggingRules.Add(new LoggingRule("*", LogLevel.Info, coloredConsoleTarget)); coloredConsoleTarget.WordHighlightingRules.Add(new ConsoleWordHighlightingRule { Regex = "\\[[^\\]]*\\]", ForegroundColor = ConsoleOutputColor.Cyan, }); coloredConsoleTarget.WordHighlightingRules.Add(new ConsoleWordHighlightingRule { Text = "Guild Joined", ForegroundColor = ConsoleOutputColor.Green, }); coloredConsoleTarget.WordHighlightingRules.Add(new ConsoleWordHighlightingRule { Text = "Guild Left", ForegroundColor = ConsoleOutputColor.Blue, }); coloredConsoleTarget.WordHighlightingRules.Add(new ConsoleWordHighlightingRule { Text = "Guild Available", ForegroundColor = ConsoleOutputColor.Yellow }); coloredConsoleTarget.WordHighlightingRules.Add(new ConsoleWordHighlightingRule { Text = "Name", ForegroundColor = ConsoleOutputColor.Red, }); coloredConsoleTarget.WordHighlightingRules.Add(new ConsoleWordHighlightingRule { Text = "Owner", ForegroundColor = ConsoleOutputColor.Red, }); coloredConsoleTarget.WordHighlightingRules.Add(new ConsoleWordHighlightingRule { Text = "Members", ForegroundColor = ConsoleOutputColor.Red, }); coloredConsoleTarget.WordHighlightingRules.Add(new ConsoleWordHighlightingRule { Text = "Created", ForegroundColor = ConsoleOutputColor.Red, }); coloredConsoleTarget.WordHighlightingRules.Add(new ConsoleWordHighlightingRule { Text = "User", ForegroundColor = ConsoleOutputColor.Red, }); coloredConsoleTarget.WordHighlightingRules.Add(new ConsoleWordHighlightingRule { Text = "Channel", ForegroundColor = ConsoleOutputColor.Red, }); coloredConsoleTarget.WordHighlightingRules.Add(new ConsoleWordHighlightingRule { Text = "Guild", ForegroundColor = ConsoleOutputColor.Red, }); coloredConsoleTarget.WordHighlightingRules.Add(new ConsoleWordHighlightingRule { Text = "Date", ForegroundColor = ConsoleOutputColor.Red, }); coloredConsoleTarget.WordHighlightingRules.Add(new ConsoleWordHighlightingRule { Text = "Raw Message", ForegroundColor = ConsoleOutputColor.Red, }); LogManager.Configuration = loggingConfig; }
public void Run(string[] args) { PrintBanner(); BlockingMq.MakeMq(); Mq = BlockingMq.GetMq(); SnaffCon controller = null; Options myOptions; try { myOptions = Config.Parse(args); //------------------------------------------ // set up new fangled logging //------------------------------------------ LoggingConfiguration nlogConfig = new LoggingConfiguration(); ColoredConsoleTarget logconsole = null; FileTarget logfile = null; ParseLogLevelString(myOptions.LogLevelString); // Targets where to log to: File and Console if (myOptions.LogToConsole) { logconsole = new ColoredConsoleTarget("logconsole") { DetectOutputRedirected = true, UseDefaultRowHighlightingRules = false, WordHighlightingRules = { new ConsoleWordHighlightingRule("{Green}", ConsoleOutputColor.DarkGreen, ConsoleOutputColor.White), new ConsoleWordHighlightingRule("{Yellow}", ConsoleOutputColor.DarkYellow, ConsoleOutputColor.White), new ConsoleWordHighlightingRule("{Red}", ConsoleOutputColor.DarkRed, ConsoleOutputColor.White), new ConsoleWordHighlightingRule("{Black}", ConsoleOutputColor.Black, ConsoleOutputColor.White), new ConsoleWordHighlightingRule("[Trace]", ConsoleOutputColor.DarkGray, ConsoleOutputColor.Black), new ConsoleWordHighlightingRule("[Degub]", ConsoleOutputColor.Gray, ConsoleOutputColor.Black), new ConsoleWordHighlightingRule("[Info]", ConsoleOutputColor.White, ConsoleOutputColor.Black), new ConsoleWordHighlightingRule("[Error]", ConsoleOutputColor.Magenta, ConsoleOutputColor.Black), new ConsoleWordHighlightingRule("[Fatal]", ConsoleOutputColor.Red, ConsoleOutputColor.Black), new ConsoleWordHighlightingRule("[File]", ConsoleOutputColor.Green, ConsoleOutputColor.Black), new ConsoleWordHighlightingRule("[Share]", ConsoleOutputColor.Yellow, ConsoleOutputColor.Black), new ConsoleWordHighlightingRule { CompileRegex = true, Regex = @"<.*\|.*\|.*\|.*?>", ForegroundColor = ConsoleOutputColor.Cyan, BackgroundColor = ConsoleOutputColor.Black }, new ConsoleWordHighlightingRule { CompileRegex = true, Regex = @"^\d\d\d\d-\d\d\-\d\d \d\d:\d\d:\d\d [\+-]\d\d:\d\d ", ForegroundColor = ConsoleOutputColor.DarkGray, BackgroundColor = ConsoleOutputColor.Black }, new ConsoleWordHighlightingRule { CompileRegex = true, Regex = @"\((?:[^\)]*\)){1}", ForegroundColor = ConsoleOutputColor.DarkMagenta, BackgroundColor = ConsoleOutputColor.Black } } }; nlogConfig.AddRule(LogLevel, LogLevel.Fatal, logconsole); logconsole.Layout = "${message}"; } if (myOptions.LogToFile) { logfile = new FileTarget("logfile") { FileName = myOptions.LogFilePath }; nlogConfig.AddRule(LogLevel, LogLevel.Fatal, logfile); logfile.Layout = "${message}"; } // Apply config LogManager.Configuration = nlogConfig; //------------------------------------------- if (myOptions.Snaffle && (myOptions.SnafflePath.Length > 4)) { Directory.CreateDirectory(myOptions.SnafflePath); } controller = new SnaffCon(myOptions); Task thing = Task.Factory.StartNew(() => { controller.Execute(); }); while (true) { HandleOutput(); } } catch (Exception e) { Console.WriteLine(e.ToString()); DumpQueue(); } }
static void ConfigureLogger() { var config = new LoggingConfiguration(); #if DEBUG var debugConsole = new ColoredConsoleTarget() { Name = Core.CONSOLE_LOG_NAME, Layout = Core.FULL_LOG_LAYOUT, Header = $"{PRODUCT_NAME} Debugger" }; var debugRule = new LoggingRule("*", LogLevel.Debug, debugConsole); config.LoggingRules.Add(debugRule); #endif var errorFileTarget = new FileTarget() { Name = Core.ERROR_LOG_NAME, FileName = Core.ERROR_LOG_PATH, Layout = Core.LOG_LAYOUT }; config.AddTarget(errorFileTarget); var errorRule = new LoggingRule("*", LogLevel.Error, errorFileTarget); config.LoggingRules.Add(errorRule); var runtimeFileTarget = new FileTarget() { Name = Core.RUNTIME_LOG_NAME, FileName = Core.RUNTIME_LOG_PATH, Layout = Core.LOG_LAYOUT }; config.AddTarget(runtimeFileTarget); var runtimeRule = new LoggingRule("*", LogLevel.Trace, runtimeFileTarget); config.LoggingRules.Add(runtimeRule); var stackDriverTarget = new Google.Cloud.Logging.NLog.GoogleStackdriverTarget() { Name = "Google StackDriver Logger", Layout = Core.LOG_LAYOUT, ProjectId = "chop9ja", CredentialFile = Path.Combine(BASE_DIR, "credentials.json") }; config.AddTarget(stackDriverTarget); var stackDriverRule = new LoggingRule("*", LogLevel.Trace, stackDriverTarget); config.LoggingRules.Add(stackDriverRule); LogManager.Configuration = config; LogManager.ReconfigExistingLoggers(); DateTime oneMonthLater = DateTime.Now.AddMonths(1); DateTime nextMonth = new DateTime(oneMonthLater.Year, oneMonthLater.Month, 1); JobManager.AddJob(() => { Core.Log.Debug("*** Monthly Session Ended ***"); ConfigureLogger(); }, s => s.ToRunOnceAt(nextMonth)); }
internal static void InitNLog() { var config = new LoggingConfiguration(); try { ConfigurationItemFactory.Default = new ConfigurationItemFactory(); foreach (var type in typeof(Logger).Assembly.GetTypes()) { ConfigurationItemFactory.Default.RegisterType(type, string.Empty); } } catch (ReflectionTypeLoadException rtle) { // NLog has a bug that manifests itself on .NET framework 2.0 with no service pack // wherein when it does its own type registering, it can't handle types that depend // on a type in an assembly that hasn't been loaded yet. // See: http://nlog-project.org/forum#nabble-td5542525 // Also: http://msdn.microsoft.com/en-us/library/system.reflection.assembly.gettypes.aspx // Start over with a fresh ConfigurationItemFactory ConfigurationItemFactory.Default = new ConfigurationItemFactory(); foreach (var type in rtle.Types) { if (type != null) { ConfigurationItemFactory.Default.RegisterType(type, string.Empty); } } } ConfigurationItemFactory.Default.LayoutRenderers.RegisterDefinition("dateutc", typeof(DateUtcLayoutRenderer)); ConfigurationItemFactory.Default.LayoutRenderers.RegisterDefinition("messagewithexceptioninfo", typeof(MessageWithExceptionInfoLayoutRenderer)); var versionString = Assembly.GetExecutingAssembly().GetName().Version.ToString(); var basicLayout = "[${dateutc}] DesktopBootstrap-" + versionString + ": ${level}: ${messagewithexceptioninfo}"; var rootLogDir = LibraryIO.FindWritableDirectory(CommonDirectories.LocalAppData, CommonDirectories.CurrentExecutingDirectory, CommonDirectories.Temp); // Create targets and rules var outputDebugStringTarget = new OutputDebugStringTarget(); outputDebugStringTarget.Layout = basicLayout; config.AddTarget("outputdebugstring", outputDebugStringTarget); if (Library.IsDebugMode()) { config.LoggingRules.Add(new LoggingRule("*", LogLevel.Trace, outputDebugStringTarget)); } var consoleTarget = new ColoredConsoleTarget(); consoleTarget.Layout = basicLayout; config.AddTarget("console", consoleTarget); if (Debugger.IsAttached) { config.LoggingRules.Add(new LoggingRule("*", LogLevel.Trace, consoleTarget)); } if (rootLogDir != null) { var basicLogFileTarget = new FileTarget(); var logDirectory = Path.Combine(rootLogDir, "Logs"); basicLogFileTarget.FileName = Path.Combine(logDirectory, "DesktopBootstrap.log"); basicLogFileTarget.ArchiveFileName = Path.Combine(logDirectory, "DesktopBootstrap-{#}.log"); basicLogFileTarget.ArchiveAboveSize = 1024 * 1024; // 1 MB basicLogFileTarget.ArchiveNumbering = ArchiveNumberingMode.Rolling; basicLogFileTarget.MaxArchiveFiles = 14; basicLogFileTarget.Encoding = UTF8Encoding.UTF8; basicLogFileTarget.ConcurrentWrites = false; basicLogFileTarget.KeepFileOpen = false; basicLogFileTarget.Layout = basicLayout; config.AddTarget("file", basicLogFileTarget); config.LoggingRules.Add(new LoggingRule("*", LogLevel.Trace, basicLogFileTarget)); var errorLogFileTarget = new FileTarget(); var errorLogDirectory = Path.Combine(rootLogDir, "ErrorLogs"); errorLogFileTarget.FileName = Path.Combine(logDirectory, "DesktopBootstrapError.log"); errorLogFileTarget.ArchiveFileName = Path.Combine(logDirectory, "DesktopBootstrapError-{#}.log"); errorLogFileTarget.ArchiveAboveSize = 1024 * 1024; // 1 MB errorLogFileTarget.ArchiveNumbering = ArchiveNumberingMode.Rolling; errorLogFileTarget.MaxArchiveFiles = 14; errorLogFileTarget.Encoding = UTF8Encoding.UTF8; errorLogFileTarget.ConcurrentWrites = true; errorLogFileTarget.KeepFileOpen = false; errorLogFileTarget.Layout = basicLayout; config.AddTarget("errorfile", errorLogFileTarget); config.LoggingRules.Add(new LoggingRule("*", LogLevel.Error, errorLogFileTarget)); } // Activate the configuration LogManager.ThrowExceptions = false; // swallow logging exceptions LogManager.Configuration = config; }
public void DanderTest() { var config = new LoggingConfiguration(); var loglevel = LogLevel.Info; var layout = @"${message}"; var consoleTarget = new ColoredConsoleTarget(); config.AddTarget("console", consoleTarget); consoleTarget.Layout = layout; var rule1 = new LoggingRule("*", loglevel, consoleTarget); config.LoggingRules.Add(rule1); LogManager.Configuration = config; var l = LogManager.GetLogger("foo"); var logs = new List <string>(); logs.Add(@" D:\Temp\logs\Security_danderspritz_3548.evtx"); logs.Add(@" D:\Temp\logs\Security_deleted_25733.evtx"); logs.Add(@" D:\Temp\logs\Security_foxit_danderspritz.evtx"); logs.Add(@" D:\Temp\logs\Security_original.evtx"); logs.Add(@" D:\Temp\logs\System2.evtx"); foreach (var sysLog in logs) { var total = 0; var total2 = 0; l.Error(sysLog + " *******************************************"); using (var fs = new FileStream(sysLog, FileMode.Open, FileAccess.Read)) { var es = new EventLog(fs); foreach (var eventRecord in es.GetEventRecords()) { l.Info( $"Record #: {eventRecord.RecordNumber} Hidden: {eventRecord.HiddenRecord}, Timestamp: {eventRecord.TimeCreated.ToUniversalTime()} Channel: {eventRecord.Channel} Computer: {eventRecord.Computer} {eventRecord.PayloadData1} {eventRecord.PayloadData2}"); // eventRecord.ConvertPayloadToXml(); total += 1; } foreach (var esEventIdMetric in es.EventIdMetrics.OrderBy(t => t.Key)) { total2 += esEventIdMetric.Value; l.Info($"{esEventIdMetric.Key}: {esEventIdMetric.Value:N0}"); } l.Info($"Total from here: {total:N0}"); l.Info($"Total2 from here: {total2:N0}"); l.Info($"Event log details: {es}"); l.Info($"Event log error count: {es.ErrorRecords.Count:N0}"); Check.That(es.ErrorRecords.Count).IsEqualTo(0); } } }
public static void Setup(bool logToConsole = true, bool logToFile = false, bool?logDebugLevel = null) { _mutex.WaitOne(); Ready = false; try { var logConfig = new LoggingConfiguration(); ColoredConsoleTarget consoleTarget = null; // Setup console logging if (logToConsole) { consoleTarget = new ColoredConsoleTarget() { Layout = @"${date:format=HH\:mm\:ss} ${logger}${message}" }; // Modify default colours foreach (var level in LogLevel.AllLoggingLevels) { ConsoleOutputColor fgColour = ConsoleOutputColor.NoChange; if (level == LogLevel.Info) { fgColour = ConsoleOutputColor.Gray; } else if (level == LogLevel.Debug) { fgColour = ConsoleOutputColor.Yellow; } else if (level == LogLevel.Trace) { fgColour = ConsoleOutputColor.DarkYellow; } else if (level == LogLevel.Warn) { fgColour = ConsoleOutputColor.Magenta; } else if (level == LogLevel.Error) { fgColour = ConsoleOutputColor.Red; } else if (level == LogLevel.Fatal) { fgColour = ConsoleOutputColor.Red; //DarkRed; } consoleTarget.RowHighlightingRules.Add(new ConsoleRowHighlightingRule() { Condition = ConditionParser.ParseExpression("level == LogLevel." + level.Name), ForegroundColor = fgColour }); } } // Setup file logging FileTarget fileTarget = null; FileTarget fileTarget_error = null; if (logToFile) { fileTarget = new FileTarget() { Layout = @"${longdate} ${logger} | ${uppercase:${level:format}}${message}", FileName = "${basedir}/logs/ditto.log", KeepFileOpen = false, CreateDirs = true, Encoding = Encoding.UTF8, }; fileTarget_error = new FileTarget() { Layout = @"${longdate} ${logger} | ${uppercase:${level:format}}${message}", FileName = "${basedir}/logs/ditto_error.log", KeepFileOpen = false, CreateDirs = true, Encoding = Encoding.UTF8, }; } // Add targets & rules LogLevel minLogLevel = (logDebugLevel == true ? LogLevel.Trace : LogLevel.Info); if (logDebugLevel == null) { #if DEBUG minLogLevel = LogLevel.Trace; #else minLogLevel = LogLevel.Info; #endif } if (logToConsole) { logConfig.AddTarget("Console", consoleTarget); logConfig.LoggingRules.Add(new LoggingRule("*", minLogLevel, consoleTarget)); } if (logToFile) { logConfig.LoggingRules.Add(new LoggingRule("*", LogLevel.Error, fileTarget_error)); logConfig.LoggingRules.Add(new LoggingRule("*", minLogLevel, fileTarget)); } LogManager.Configuration = logConfig; Ready = true; LogToConsole = logToConsole; LogToFile = logToFile; LogDebugLevel = (minLogLevel == LogLevel.Trace || minLogLevel == LogLevel.Debug); } catch (Exception ex) { Console.WriteLine(ex); } finally { _mutex.ReleaseMutex(); } }
public static LoggingConfiguration GetNLogCOnfiguration() { //%date %-5level [%property{ExecutingCtx}] - %message | %stacktrace{5} | [%logger ]%newline" var layout = @"${longdate:universalTime=true} ${pad:padding=5:inner=${level:uppercase=true}} [${pad:padding=5:inner=${mdlc:item=IID}}] - ${message} ${when:when=length('${exception}')>0:Inner=[BEGIN_EXCEPTION_}${exception:format=toString,Data:maxInnerExceptionLevel=10}${when:when=length('${exception}')>0:Inner=_END_EXCEPTION]} | ${event-properties:item=EventId_Id} ${ndlc:uppercase=true:separator= => } | [${callsite:fileName=true:methodName=true:cleanNamesOfAsyncContinuations=true:cleanNamesOfAnonymousDelegates=true:includeSourcePath=false}] [${logger:shortName=false}] [$END$]"; // Step 1. Create configuration object var config = new LoggingConfiguration(); // Step 2. Create targets and add them to the configuration var consoleTarget = new ColoredConsoleTarget(); config.AddTarget("console", consoleTarget); var fileTarget = new FileTarget(); config.AddTarget("file", fileTarget); var commonLayout = layout; var consoleLayout = commonLayout.Replace("[$END$]", ""); consoleTarget.Layout = consoleLayout; fileTarget.FileName = "${basedir}/wwwroot/logs/log.log"; fileTarget.Layout = commonLayout; fileTarget.ArchiveNumbering = ArchiveNumberingMode.DateAndSequence; fileTarget.ArchiveEvery = FileArchivePeriod.Day; //fileTarget.KeepFileOpen = true; fileTarget.AutoFlush = true; fileTarget.ArchiveDateFormat = "dd-MM-yyyy"; fileTarget.ArchiveOldFileOnStartup = true; fileTarget.ArchiveFileName = "${basedir}/wwwroot/logs/log.{#}.log.zip"; fileTarget.EnableArchiveFileCompression = true; var blFileTarget = new FileTarget(); config.AddTarget("blFileTarget", blFileTarget); blFileTarget.FileName = "${basedir}/wwwroot/logs/_bl-log.log"; blFileTarget.Layout = fileTarget.Layout; blFileTarget.ArchiveNumbering = ArchiveNumberingMode.DateAndSequence; blFileTarget.ArchiveEvery = FileArchivePeriod.Day; blFileTarget.AutoFlush = true; blFileTarget.ArchiveDateFormat = "dd-MM-yyyy"; blFileTarget.ArchiveOldFileOnStartup = true; blFileTarget.ArchiveFileName = "${basedir}/wwwroot/logs/_bl-log.{#}.log.zip"; blFileTarget.EnableArchiveFileCompression = true; var blackHole = new NullTarget("blackHole"); config.AddTarget("blackHole", blackHole); // Step 4. Define rules var rule1 = new LoggingRule("*", NLog.LogLevel.Debug, consoleTarget); config.LoggingRules.Add(rule1); var rule2 = new LoggingRule("ES.*", NLog.LogLevel.Debug, fileTarget); config.LoggingRules.Add(rule2); var rulePH = new LoggingRule("PH.*", NLog.LogLevel.Debug, fileTarget); config.LoggingRules.Add(rulePH); var ruleMs = new LoggingRule("Microsoft.*", NLog.LogLevel.Trace, blackHole); config.LoggingRules.Add(ruleMs); var blRule = new LoggingRule("PH.Core3.Test.*", NLog.LogLevel.Debug, blFileTarget); blRule.LoggerNamePattern = "PH.Core3.Test.*"; //config.LoggingRules.Add(blRule); var dbg = fileTarget.Layout; return(config); }
public Manager(string jsonConfigFile, string logLevel, string logfileDir, CancellationToken cancelToken) { StartedOn = DateTime.UtcNow; var vfi = new FileInfo(jsonConfigFile); JsonConfig = vfi.FullName; LogfileDir = logfileDir; numMessages = 0; numConnections = 0; Outputs = new List <OutputSender>(); Listeners = new List <InputListener>(); var loggingConfiguration = new LoggingConfiguration(); // Create our default targets var coloredConsoleTarget = new ColoredConsoleTarget(); Target fileTarget = CreateDefaultFileTarget(logfileDir); loggingConfiguration.AddTarget("Console", coloredConsoleTarget); loggingConfiguration.AddTarget("DailyFile", fileTarget); // The LogLevel.Trace means has to be at least Trace to show up on console loggingConfiguration.LoggingRules.Add(new LoggingRule("*", LogLevel.Trace, coloredConsoleTarget)); // LogLevel.Debug means has to be at least Debug to show up in logfile loggingConfiguration.LoggingRules.Add(new LoggingRule("*", LogLevel.Debug, fileTarget)); LogManager.Configuration = loggingConfiguration; LogManager.EnableLogging(); LogManager.GlobalThreshold = LogLevel.FromString(logLevel); LogManager.GetCurrentClassLogger() .Info("TimberWinR Version {0}", GetAssemblyByName("TimberWinR.ServiceHost").GetName().Version.ToString()); // Is it a directory? if (Directory.Exists(jsonConfigFile)) { DirectoryInfo di = new DirectoryInfo(jsonConfigFile); LogManager.GetCurrentClassLogger().Info("Initialized, Reading Configurations From {0}", di.FullName); Config = Configuration.FromDirectory(jsonConfigFile); } else { var fi = new FileInfo(jsonConfigFile); LogManager.GetCurrentClassLogger().Info("Initialized, Reading Configurations From File: {0}", fi.FullName); if (!fi.Exists) { throw new FileNotFoundException("Missing config file", jsonConfigFile); } LogManager.GetCurrentClassLogger().Info("Initialized, Reading Config: {0}", fi.FullName); Config = Configuration.FromFile(jsonConfigFile); } LogManager.GetCurrentClassLogger().Info("Log Directory {0}", logfileDir); LogManager.GetCurrentClassLogger().Info("Logging Level: {0}", LogManager.GlobalThreshold); // Read the Configuration file if (Config != null) { if (Config.RedisOutputs != null) { foreach (var ro in Config.RedisOutputs) { var redis = new RedisOutput(this, ro, cancelToken); Outputs.Add(redis); } } if (Config.ElasticsearchOutputs != null) { foreach (var ro in Config.ElasticsearchOutputs) { var els = new ElasticsearchOutput(this, ro, cancelToken); Outputs.Add(els); } } if (Config.StdoutOutputs != null) { foreach (var ro in Config.StdoutOutputs) { var stdout = new StdoutOutput(this, ro, cancelToken); Outputs.Add(stdout); } } foreach (Parser.IISW3CLog iisw3cConfig in Config.IISW3C) { var elistner = new IISW3CInputListener(iisw3cConfig, cancelToken); Listeners.Add(elistner); foreach (var output in Outputs) { output.Connect(elistner); } } foreach (Parser.W3CLog iisw3cConfig in Config.W3C) { var elistner = new W3CInputListener(iisw3cConfig, cancelToken); Listeners.Add(elistner); foreach (var output in Outputs) { output.Connect(elistner); } } foreach (Parser.WindowsEvent eventConfig in Config.Events) { var elistner = new WindowsEvtInputListener(eventConfig, cancelToken); Listeners.Add(elistner); foreach (var output in Outputs) { output.Connect(elistner); } } foreach (var logConfig in Config.Logs) { var elistner = new LogsListener(logConfig, cancelToken); Listeners.Add(elistner); foreach (var output in Outputs) { output.Connect(elistner); } } foreach (var tcp in Config.Tcps) { var elistner = new TcpInputListener(cancelToken, tcp.Port); Listeners.Add(elistner); foreach (var output in Outputs) { output.Connect(elistner); } } foreach (var udp in Config.Udps) { var elistner = new UdpInputListener(cancelToken, udp.Port); Listeners.Add(elistner); foreach (var output in Outputs) { output.Connect(elistner); } } foreach (var stdin in Config.Stdins) { var elistner = new StdinListener(cancelToken); Listeners.Add(elistner); foreach (var output in Outputs) { output.Connect(elistner); } } var computerName = System.Environment.MachineName + "." + Microsoft.Win32.Registry.LocalMachine.OpenSubKey( @"SYSTEM\CurrentControlSet\services\Tcpip\Parameters") .GetValue("Domain", "") .ToString(); foreach (var output in Outputs) { var name = Assembly.GetExecutingAssembly().GetName(); JObject json = new JObject( new JProperty("TimberWinR", new JObject( new JProperty("version", GetAssemblyByName("TimberWinR.ServiceHost").GetName().Version.ToString()), new JProperty("host", computerName), new JProperty("output", output.Name), new JProperty("initialized", DateTime.UtcNow) ))); json.Add(new JProperty("type", "Win32-TimberWinR")); json.Add(new JProperty("host", computerName)); output.Startup(json); } } }
static void Main(string[] args) { CommandLineApplication app = new CommandLineApplication(); app.HelpOption("-? | -h | --help"); var UserNameOption = app.Option( "-u | --username <USERNAME>", "The UserName to login to the Covenant API.", CommandOptionType.SingleValue ); var PasswordOption = app.Option( "-p | --password <PASSWORD>", "The Password to login to the Covenant API.", CommandOptionType.SingleValue ); var ComputerNameOption = app.Option( "-c | --computername <COMPUTERNAME>", "The ComputerName (IPAddress or Hostname) to bind the Covenant API to.", CommandOptionType.SingleValue ); app.OnExecute(() => { if (!File.Exists(Path.Combine(Common.CovenantSharpSploitDirectory, "SharpSploit.sln")) || !File.Exists(Path.Combine(Common.CovenantRubeusDirectory, "Rubeus.sln"))) { Console.Error.WriteLine("Error: git submodules have not been initialized"); Console.Error.WriteLine("Covenant's submodules can be cloned with: git clone --recurse-submodules https://github.com/cobbr/Covenant"); Console.Error.WriteLine("Or initialized after cloning with: git submodule update --init --recursive"); return(-1); } string username = UserNameOption.Value(); string password = ""; if (UserNameOption.HasValue() && !PasswordOption.HasValue()) { Console.Write("Password: "******"0.0.0.0"; IPAddress address = null; try { address = IPAddress.Parse(CovenantBindUrl); } catch (FormatException) { address = Dns.GetHostAddresses(CovenantBindUrl).FirstOrDefault(); } IPEndPoint CovenantEndpoint = new IPEndPoint(address, Common.CovenantHTTPSPort); string CovenantUri = (CovenantBindUrl == "0.0.0.0" ? "https://127.0.0.1:" + Common.CovenantHTTPSPort : "https://" + CovenantEndpoint); var host = BuildWebHost(CovenantEndpoint, CovenantUri); using (var scope = host.Services.CreateScope()) { var services = scope.ServiceProvider; var context = services.GetRequiredService <CovenantContext>(); var userManager = services.GetRequiredService <UserManager <CovenantUser> >(); var signInManager = services.GetRequiredService <SignInManager <CovenantUser> >(); var roleManager = services.GetRequiredService <RoleManager <IdentityRole> >(); var configuration = services.GetRequiredService <IConfiguration>(); var listenerTokenSources = services.GetRequiredService <ConcurrentDictionary <int, CancellationTokenSource> >(); context.Database.EnsureCreated(); DbInitializer.Initialize(context, roleManager, listenerTokenSources).Wait(); if (!context.Users.Any() && UserNameOption.HasValue() && !string.IsNullOrEmpty(password)) { // TODO: create user CovenantUser user = new CovenantUser { UserName = UserNameOption.Value() }; Task <IdentityResult> task = userManager.CreateAsync(user, password); task.Wait(); IdentityResult userResult = task.Result; if (userResult.Succeeded) { Task t = userManager.AddToRoleAsync(user, "User"); t.Wait(); Task t2 = userManager.AddToRoleAsync(user, "Administrator"); t2.Wait(); } else { Console.Error.WriteLine($"Error creating user: {user.UserName}"); return(-1); } } } LoggingConfiguration loggingConfig = new LoggingConfiguration(); var consoleTarget = new ColoredConsoleTarget(); var fileTarget = new FileTarget(); loggingConfig.AddTarget("console", consoleTarget); loggingConfig.AddTarget("file", fileTarget); consoleTarget.Layout = @"${longdate}|${event-properties:item=EventId_Id}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}"; fileTarget.Layout = @"${longdate}|${event-properties:item=EventId_Id}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}"; fileTarget.FileName = Common.CovenantLogDirectory + "covenant.log"; loggingConfig.AddRule(NLog.LogLevel.Info, NLog.LogLevel.Fatal, "console"); loggingConfig.AddRule(NLog.LogLevel.Info, NLog.LogLevel.Fatal, "file"); var logger = NLogBuilder.ConfigureNLog(loggingConfig).GetCurrentClassLogger(); try { logger.Debug("Starting Covenant API"); host.Run(); } catch (Exception ex) { logger.Error(ex, "Covenant stopped due to exception"); throw; } finally { NLog.LogManager.Shutdown(); } return(0); }); app.Execute(args); }
public void Run(string[] args) { // prime the hoststring lazy instantiator hostString(); // print the thing PrintBanner(); // set up the message queue for operation BlockingMq.MakeMq(); // get a handle to the message queue singleton Mq = BlockingMq.GetMq(); // prime the UI handler SnaffCon controller = null; try { // parse cli opts in Options = Config.Parse(args); // set up the TSV output if the flag is set if (Options.LogTSV) { fileResultTemplate = Options.Separator + "{0}" + Options.Separator + "{1}" + Options.Separator + "{2}" + Options.Separator + "{3}" + Options.Separator + "{4}" + Options.Separator + "{5}" + Options.Separator + "{6}" + Options.Separator + "{7}" + Options.Separator + "{8}"; shareResultTemplate = Options.Separator + "{0}" + Options.Separator + "{1}"; dirResultTemplate = Options.Separator + "{0}" + Options.Separator + "{1}"; } // otherwise just do the normal thing else { fileResultTemplate = "{{{0}}}<{1}|{2}{3}|{4}|{5}|{6}>({7}) {8}"; shareResultTemplate = "{{{0}}}({1})"; dirResultTemplate = "{{{0}}}({1})"; } //------------------------------------------ // set up new fangled logging //------------------------------------------ LoggingConfiguration nlogConfig = new LoggingConfiguration(); ColoredConsoleTarget logconsole = null; FileTarget logfile = null; ParseLogLevelString(Options.LogLevelString); // Targets where to log to: File and Console if (Options.LogToConsole) { logconsole = new ColoredConsoleTarget("logconsole") { DetectOutputRedirected = true, UseDefaultRowHighlightingRules = false, WordHighlightingRules = { new ConsoleWordHighlightingRule("{Green}", ConsoleOutputColor.DarkGreen, ConsoleOutputColor.White), new ConsoleWordHighlightingRule("{Yellow}", ConsoleOutputColor.DarkYellow, ConsoleOutputColor.White), new ConsoleWordHighlightingRule("{Red}", ConsoleOutputColor.DarkRed, ConsoleOutputColor.White), new ConsoleWordHighlightingRule("{Black}", ConsoleOutputColor.Black, ConsoleOutputColor.White), new ConsoleWordHighlightingRule("[Trace]", ConsoleOutputColor.DarkGray, ConsoleOutputColor.Black), new ConsoleWordHighlightingRule("[Degub]", ConsoleOutputColor.Gray, ConsoleOutputColor.Black), new ConsoleWordHighlightingRule("[Info]", ConsoleOutputColor.White, ConsoleOutputColor.Black), new ConsoleWordHighlightingRule("[Error]", ConsoleOutputColor.Magenta, ConsoleOutputColor.Black), new ConsoleWordHighlightingRule("[Fatal]", ConsoleOutputColor.Red, ConsoleOutputColor.Black), new ConsoleWordHighlightingRule("[File]", ConsoleOutputColor.Green, ConsoleOutputColor.Black), new ConsoleWordHighlightingRule("[Share]", ConsoleOutputColor.Yellow, ConsoleOutputColor.Black), new ConsoleWordHighlightingRule { CompileRegex = true, Regex = @"<.*\|.*\|.*\|.*?>", ForegroundColor = ConsoleOutputColor.Cyan, BackgroundColor = ConsoleOutputColor.Black }, new ConsoleWordHighlightingRule { CompileRegex = true, Regex = @"^\d\d\d\d-\d\d\-\d\d \d\d:\d\d:\d\d [\+-]\d\d:\d\d ", ForegroundColor = ConsoleOutputColor.DarkGray, BackgroundColor = ConsoleOutputColor.Black }, new ConsoleWordHighlightingRule { CompileRegex = true, Regex = @"\((?:[^\)]*\)){1}", ForegroundColor = ConsoleOutputColor.DarkMagenta, BackgroundColor = ConsoleOutputColor.Black } } }; nlogConfig.AddRule(LogLevel, LogLevel.Fatal, logconsole); logconsole.Layout = "${message}"; } if (Options.LogToFile) { logfile = new FileTarget("logfile") { FileName = Options.LogFilePath }; nlogConfig.AddRule(LogLevel, LogLevel.Fatal, logfile); logfile.Layout = "${message}"; } // Apply config LogManager.Configuration = nlogConfig; //------------------------------------------- if (Options.Snaffle && (Options.SnafflePath.Length > 4)) { Directory.CreateDirectory(Options.SnafflePath); } controller = new SnaffCon(Options); Task thing = Task.Factory.StartNew(() => { controller.Execute(); }); while (true) { HandleOutput(); } } catch (Exception e) { Console.WriteLine(e.ToString()); DumpQueue(); } }
static void Main(string[] args) { CommandLineApplication app = new CommandLineApplication(); app.HelpOption("-? | -h | --help"); var UserNameOption = app.Option( "-u | --username <USERNAME>", "The initial user UserName to create on launch. (env: COVENANT_USERNAME)", CommandOptionType.SingleValue ); var PasswordOption = app.Option( "-p | --password <PASSWORD>", "The initial user Password to create on launch. (env: COVENANT_PASSWORD)", CommandOptionType.SingleValue ); var ComputerNameOption = app.Option( "-c | --computername <COMPUTERNAME>", "The ComputerName (IPAddress or Hostname) to bind Covenant to. (env: COVENANT_COMPUTER_NAME)", CommandOptionType.SingleValue ); var AdminPortOption = app.Option( "-a | --adminport <PORT>", "The Port number to bind Covenant to. (env: COVENANT_PORT)", CommandOptionType.SingleValue ); app.OnExecute(() => { if (Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") == "Development" && (!File.Exists(Path.Combine(Common.CovenantSharpSploitDirectory, "SharpSploit.sln")) || !File.Exists(Path.Combine(Common.CovenantRubeusDirectory, "Rubeus.sln")))) { Console.Error.WriteLine("Error: git submodules have not been initialized"); Console.Error.WriteLine("Covenant's submodules can be cloned with: git clone --recurse-submodules https://github.com/cobbr/Covenant"); Console.Error.WriteLine("Or initialized after cloning with: git submodule update --init --recursive"); return(-1); } string username = UserNameOption.HasValue() ? UserNameOption.Value() : Environment.GetEnvironmentVariable("COVENANT_USERNAME"); string password = PasswordOption.HasValue() ? PasswordOption.Value() : Environment.GetEnvironmentVariable("COVENANT_PASSWORD"); if (!string.IsNullOrEmpty(username) && string.IsNullOrEmpty(password)) { Console.Write("Password: "******"COVENANT_COMPUTER_NAME");; if (string.IsNullOrEmpty(CovenantBindUrl)) { CovenantBindUrl = "0.0.0.0"; } int CovenantPort = Common.CovenantDefaultAdminPort; string sPort = AdminPortOption.HasValue() ? AdminPortOption.Value() : Environment.GetEnvironmentVariable("COVENANT_PORT"); if (!string.IsNullOrEmpty(sPort) && !int.TryParse(sPort, out CovenantPort)) { CovenantPort = Common.CovenantDefaultAdminPort; } IPAddress address = null; try { address = IPAddress.Parse(CovenantBindUrl); } catch (FormatException) { address = Dns.GetHostAddresses(CovenantBindUrl).FirstOrDefault(); } IPEndPoint CovenantEndpoint = new IPEndPoint(address, CovenantPort); string CovenantUri = CovenantBindUrl == "0.0.0.0" ? "https://127.0.0.1:" + CovenantPort : "https://" + CovenantEndpoint; var host = BuildHost(CovenantEndpoint, CovenantUri); using (var scope = host.Services.CreateScope()) { var services = scope.ServiceProvider; var context = services.GetRequiredService <CovenantContext>(); var service = services.GetRequiredService <ICovenantService>(); var userManager = services.GetRequiredService <UserManager <CovenantUser> >(); var signInManager = services.GetRequiredService <SignInManager <CovenantUser> >(); var roleManager = services.GetRequiredService <RoleManager <IdentityRole> >(); var configuration = services.GetRequiredService <IConfiguration>(); configuration["CovenantPort"] = CovenantPort.ToString(); var listenerTokenSources = services.GetRequiredService <ConcurrentDictionary <int, CancellationTokenSource> >(); context.Database.EnsureCreated(); DbInitializer.Initialize(service, context, roleManager, listenerTokenSources).Wait(); CovenantUser serviceUser = new CovenantUser { UserName = "******" }; if (!context.Users.Any()) { string serviceUserPassword = Utilities.CreateSecretPassword() + "A"; userManager.CreateAsync(serviceUser, serviceUserPassword).Wait(); userManager.AddToRoleAsync(serviceUser, "ServiceUser").Wait(); if (!string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(password)) { CovenantUser user = new CovenantUser { UserName = username }; Task <IdentityResult> task = userManager.CreateAsync(user, password); task.Wait(); IdentityResult userResult = task.Result; if (userResult.Succeeded) { userManager.AddToRoleAsync(user, "User").Wait(); userManager.AddToRoleAsync(user, "Administrator").Wait(); } else { Console.Error.WriteLine($"Error creating user: {user.UserName}"); return(-1); } } } configuration["ServiceUserToken"] = Utilities.GenerateJwtToken( serviceUser.UserName, serviceUser.Id, new string[] { "ServiceUser" }, configuration["JwtKey"], configuration["JwtIssuer"], configuration["JwtAudience"], configuration["JwtExpireDays"] ); } LoggingConfiguration loggingConfig = new LoggingConfiguration(); var consoleTarget = new ColoredConsoleTarget(); var fileTarget = new FileTarget(); loggingConfig.AddTarget("console", consoleTarget); loggingConfig.AddTarget("file", fileTarget); consoleTarget.Layout = @"${longdate}|${event-properties:item=EventId_Id}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}"; fileTarget.Layout = @"${longdate}|${event-properties:item=EventId_Id}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}"; fileTarget.FileName = Common.CovenantLogDirectory + "covenant.log"; loggingConfig.AddRule(NLog.LogLevel.Info, NLog.LogLevel.Fatal, "console"); loggingConfig.AddRule(NLog.LogLevel.Info, NLog.LogLevel.Fatal, "file"); var logger = NLogBuilder.ConfigureNLog(loggingConfig).GetCurrentClassLogger(); try { logger.Debug("Starting Covenant API"); if (!IsElevated()) { Console.Error.WriteLine("WARNING: Running Covenant non-elevated. You may not have permission to start Listeners on low-numbered ports. Consider running Covenant elevated."); } Console.WriteLine($"Covenant has started! Navigate to {CovenantUri} in a browser"); host.Run(); } catch (Exception ex) { logger.Error(ex, "Covenant stopped due to exception"); throw; } finally { NLog.LogManager.Shutdown(); } return(0); }); app.Execute(args); }
public static bool Init(string[] args = null) { if (initialized) { return(true); } initialized = true; CultureInfo.DefaultThreadCurrentCulture = CultureInfo.InvariantCulture; CultureInfo.DefaultThreadCurrentUICulture = CultureInfo.InvariantCulture; Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture; Thread.CurrentThread.CurrentUICulture = CultureInfo.InvariantCulture; // Setup logging var config = new LoggingConfiguration(); var fileTarget = new FileTarget { FileName = Constants.LogDirectory + "\\${shortdate}.log", Layout = "${longdate} ${uppercase:${level}} ${message}", ReplaceFileContentsOnEachWrite = true }; config.AddTarget("file", fileTarget); config.LoggingRules.Add(new LoggingRule("*", LogLevel.Debug, fileTarget)); var coloredConsoleTarget = new ColoredConsoleTarget { UseDefaultRowHighlightingRules = false, Layout = "${longdate}|${pad:padding=5:inner=${level:uppercase=true}}| ${logger}: ${message}" }; coloredConsoleTarget.RowHighlightingRules.Add( new ConsoleRowHighlightingRule { Condition = "Level == LogLevel.Trace", ForegroundColor = ConsoleOutputColor.DarkGray }); coloredConsoleTarget.RowHighlightingRules.Add( new ConsoleRowHighlightingRule { Condition = "Level == LogLevel.Debug", ForegroundColor = ConsoleOutputColor.Gray }); coloredConsoleTarget.RowHighlightingRules.Add( new ConsoleRowHighlightingRule { Condition = "Level == LogLevel.Info", ForegroundColor = ConsoleOutputColor.White }); coloredConsoleTarget.RowHighlightingRules.Add( new ConsoleRowHighlightingRule { Condition = "Level == LogLevel.Warn", ForegroundColor = ConsoleOutputColor.Yellow }); coloredConsoleTarget.RowHighlightingRules.Add( new ConsoleRowHighlightingRule { Condition = "Level == LogLevel.Error", ForegroundColor = ConsoleOutputColor.Red }); coloredConsoleTarget.RowHighlightingRules.Add( new ConsoleRowHighlightingRule { Condition = "Level == LogLevel.Fatal", ForegroundColor = ConsoleOutputColor.Red }); config.AddTarget("coloredConsole", coloredConsoleTarget); config.AddRule(LogLevel.Trace, LogLevel.Fatal, coloredConsoleTarget); LogManager.Configuration = config; var logger = LogManager.GetCurrentClassLogger(); // Log unhandled exceptions AppDomain.CurrentDomain.UnhandledException += (sender, eventArgs) => { var exception = eventArgs.ExceptionObject as Exception; // Check if exception came from us if (exception != null && exception.Source.Equals(Assembly.GetExecutingAssembly().FullName)) { // Get the logger from the class that threw the exception and log it LogManager.GetCurrentClassLogger(new StackTrace().GetFrame(1).GetMethod().DeclaringType) .Fatal(exception); } }; // Initial notification. logger.Info("SDKEx Loading"); // Load Resource Content. ResourceLoader.Initialize(); logger.Info("Resources Initialized."); // Load GameObjects. GameObjects.Initialize(); logger.Info("GameObjects Initialized."); // Create L# menu Variables.LeagueSharpMenu = new Menu("LeagueSharp", "LeagueSharp", true).Attach(); MenuCustomizer.Initialize(Variables.LeagueSharpMenu); logger.Info("LeagueSharp Menu Created."); // Load the Orbwalker Variables.Orbwalker = new Orbwalker(Variables.LeagueSharpMenu); logger.Info("Orbwalker Initialized."); // Load the TargetSelector. Variables.TargetSelector = new TargetSelector(Variables.LeagueSharpMenu); logger.Info("TargetSelector Initialized."); // Load the Notifications Notifications.Initialize(Variables.LeagueSharpMenu); logger.Info("Notifications Initialized."); // Load the ThemeManager ThemeManager.Initialize(Variables.LeagueSharpMenu); logger.Info("ThemeManager Initialized."); // Load Damages. Damage.Initialize(); logger.Info("Damage Library Initialized."); // Load Language MultiLanguage.LoadTranslation(); logger.Info("Translations Initialized."); // Final notification. logger.Info($"SDKEx Version {Variables.KitVersion} Loaded!"); // Tell the developer everything succeeded return(initialized); }
public static void Init(string logpath = "", int logSaveDayLong = 7, long fileSize = 1024 *1024 *5 + 20) { LogHelper.Ready = false; if (logpath.Length == 0) { logPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Log"); } else { logPath = logpath; } //Internal logger InternalLogger.LogToConsole = false; InternalLogger.LogFile = logPath + "/internalLog.txt"; InternalLogger.LogWriter = new StringWriter(); InternalLogger.LogLevel = LogLevel.Warn; // Step 1. Create configuration object LoggingConfiguration logConfig = new LoggingConfiguration(); // Step 3. Set target properties //string commonLayout = @"${date:format=yyyy-MM-dd HH\:mm\:ss.fff} ${level:uppercase=true} | ${message} --> ${stacktrace} | ${newline} ${exception}"; string commonLayout = @"${date:format=yyyy-MM-dd HH\:mm\:ss\.fff} ${level:uppercase=true} | ${message} ${onexception:${exception:format=tostring} ${newline} ${stacktrace} ${newline}"; FileTarget fileTarget = new FileTarget(); logConfig.AddTarget("logFile", fileTarget); fileTarget.FileName = logPath + "/${shortdate}.txt"; fileTarget.MaxArchiveFiles = int.MaxValue; fileTarget.ArchiveFileName = logPath + @"/archives/${shortdate}_{#####}.txt"; fileTarget.ArchiveNumbering = ArchiveNumberingMode.Rolling; fileTarget.AutoFlush = true; fileTarget.DeleteOldFileOnStartup = false; fileTarget.ArchiveEvery = FileArchivePeriod.Day; fileTarget.CreateDirs = true; fileTarget.ArchiveAboveSize = fileSize; fileTarget.KeepFileOpen = false; fileTarget.ConcurrentWrites = true; fileTarget.Layout = commonLayout; LoggingRule ruleFile = new LoggingRule("*", LogLevel.Trace, fileTarget); logConfig.LoggingRules.Add(ruleFile); //控制台日志 var consoleTarget = new ColoredConsoleTarget(); consoleTarget.UseDefaultRowHighlightingRules = false; consoleTarget.Layout = commonLayout; consoleTarget.RowHighlightingRules.Add(new ConsoleRowHighlightingRule(ConditionParser.ParseExpression("level == LogLevel.Debug"), ConsoleOutputColor.DarkGray, ConsoleOutputColor.Black)); consoleTarget.RowHighlightingRules.Add(new ConsoleRowHighlightingRule(ConditionParser.ParseExpression("level == LogLevel.Info"), ConsoleOutputColor.Gray, ConsoleOutputColor.Black)); consoleTarget.RowHighlightingRules.Add(new ConsoleRowHighlightingRule(ConditionParser.ParseExpression("level == LogLevel.Warn"), ConsoleOutputColor.Yellow, ConsoleOutputColor.Black)); consoleTarget.RowHighlightingRules.Add(new ConsoleRowHighlightingRule(ConditionParser.ParseExpression("level == LogLevel.Error"), ConsoleOutputColor.Red, ConsoleOutputColor.Black)); consoleTarget.RowHighlightingRules.Add(new ConsoleRowHighlightingRule(ConditionParser.ParseExpression("level == LogLevel.Fatal"), ConsoleOutputColor.Red, ConsoleOutputColor.White)); LoggingRule ruleColoredConsole = new LoggingRule("*", LogLevel.Trace, consoleTarget); logConfig.LoggingRules.Add(ruleColoredConsole); // Step 5. Activate the configuration LogManager.Configuration = logConfig; loggerDebug = LogManager.GetLogger(""); System.Threading.Tasks.Task.Factory.StartNew(() => { while (true) { System.Threading.Thread.Sleep(1000 * 30); try { FileInfo[] fil = new DirectoryInfo(logPath).GetFiles("*.txt", SearchOption.AllDirectories); foreach (FileInfo f in fil) { string[] arr = f.Name.Split('_'); if (arr != null && arr.Length > 0) { DateTime tm = DateTime.Now; if (DateTime.TryParse(arr[0], out tm) && DateTime.Now.Subtract(tm).TotalDays > logSaveDayLong) { f.Delete(); } } } } catch { } } }, System.Threading.Tasks.TaskCreationOptions.LongRunning); LogHelper.Ready = true; }
/// <summary> /// Main async method for the bot. /// </summary> /// <param name="args"></param> /// <returns></returns> public static async Task Main(string[] args) { // Make sure Log folder exists Directory.CreateDirectory(Path.Combine(Globals.AppPath, "Logs")); // Checks for existing latest log if (File.Exists(Path.Combine(Globals.AppPath, "Logs", "latest.log"))) { // This is no longer the latest log; move to backlogs string oldLogFileName = File.ReadAllLines(Path.Combine(Globals.AppPath, "Logs", "latest.log"))[0]; File.Move(Path.Combine(Globals.AppPath, "Logs", "latest.log"), Path.Combine(Globals.AppPath, "Logs", oldLogFileName)); } // Builds a file name to prepare for future backlogging string logFileName = $"{DateTime.Now:dd-MM-yy}-1.log"; // Loops until the log file doesn't exist int index = 2; while (File.Exists(Path.Combine(Globals.AppPath, "Logs", logFileName))) { logFileName = $"{DateTime.Now:dd-MM-yy}-{index}.log"; index++; } // Logs the future backlog file name File.WriteAllText(Path.Combine(Globals.AppPath, "Logs", "latest.log"), $"{logFileName}\n"); // Set up logging through NLog LoggingConfiguration config = new LoggingConfiguration(); FileTarget logfile = new FileTarget("logfile") { FileName = Path.Combine(Globals.AppPath, "Logs", "latest.log"), Layout = "[${time}] [${level:uppercase=true}] [${logger}] ${message}" }; config.AddRule(LogLevel.Trace, LogLevel.Fatal, logfile); ColoredConsoleTarget coloredConsoleTarget = new ColoredConsoleTarget { UseDefaultRowHighlightingRules = true }; config.AddRule(LogLevel.Info, LogLevel.Fatal, coloredConsoleTarget); LogManager.Configuration = config; string settingsLocation = Path.Combine(Globals.AppPath, "Data", "settings.json"); string jsonFile = File.ReadAllText(settingsLocation); // Load the settings from file, then store it in the globals Globals.BotSettings = JsonConvert.DeserializeObject <Settings.Settings>(jsonFile); Client = new DiscordClient(new DiscordConfiguration { Token = Globals.BotSettings.BotToken, TokenType = TokenType.Bot, UseInternalLogHandler = true, LogLevel = DSharpPlus.LogLevel.Debug }); commands = Client.UseCommandsNext(new CommandsNextConfiguration { #if DEBUG_PREFIX StringPrefix = Globals.BotSettings.Prefix + Globals.BotSettings.Prefix, #else StringPrefix = Globals.BotSettings.Prefix, #endif CaseSensitive = false }); commands.RegisterCommands(Assembly.GetExecutingAssembly()); interactivity = Client.UseInteractivity(new InteractivityConfiguration { }); Client.MessageCreated += Client_MessageReceived; Client.MessageReactionAdded += Client_ReactionAdded; Client.GuildMemberRemoved += Client_UserLeft; commands.CommandExecuted += Commands_CommandExecuted; commands.CommandErrored += Commands_CommandErrored; Client.Ready += Client_Ready; // Client.Log += Client_Log; await Client.ConnectAsync(); await UpdateStandingsAsync(); List <IScheduledTask> tasks = new List <IScheduledTask> { #if DEBUG_PREFIX new TestTask() #endif }; CancellationToken token = new CancellationToken(false); SchedulerHostedService scheduler = new SchedulerHostedService(tasks); await scheduler.StartAsync(token); await Task.Delay(-1, token); }
internal static void InitCoreLoggers(bool uniqueInstance) { try { if ((Directory.GetCurrentDirectory() != AppContext.BaseDirectory) && File.Exists(NLogConfigurationFile)) { LogManager.Configuration = new XmlLoggingConfiguration(NLogConfigurationFile); } } catch (Exception e) { ASF.ArchiLogger.LogGenericException(e); } if (LogManager.Configuration != null) { IsUsingCustomConfiguration = true; InitConsoleLoggers(); LogManager.ConfigurationChanged += OnConfigurationChanged; return; } ConfigurationItemFactory.Default.ParseMessageTemplates = false; LoggingConfiguration config = new LoggingConfiguration(); ColoredConsoleTarget coloredConsoleTarget = new ColoredConsoleTarget("ColoredConsole") { Layout = GeneralLayout }; config.AddTarget(coloredConsoleTarget); config.LoggingRules.Add(new LoggingRule("*", LogLevel.Debug, coloredConsoleTarget)); if (uniqueInstance) { try { if (!Directory.Exists(SharedInfo.ArchivalLogsDirectory)) { Directory.CreateDirectory(SharedInfo.ArchivalLogsDirectory); } } catch (Exception e) { ASF.ArchiLogger.LogGenericException(e); } FileTarget fileTarget = new FileTarget("File") { ArchiveFileName = Path.Combine("${currentdir}", SharedInfo.ArchivalLogsDirectory, SharedInfo.ArchivalLogFile), ArchiveNumbering = ArchiveNumberingMode.Rolling, ArchiveOldFileOnStartup = true, CleanupFileName = false, ConcurrentWrites = false, DeleteOldFileOnStartup = true, FileName = Path.Combine("${currentdir}", SharedInfo.LogFile), Layout = GeneralLayout, MaxArchiveFiles = 10 }; config.AddTarget(fileTarget); config.LoggingRules.Add(new LoggingRule("*", LogLevel.Debug, fileTarget)); } LogManager.Configuration = config; InitConsoleLoggers(); }
public void DirTestToFix() { var config = new LoggingConfiguration(); var loglevel = LogLevel.Debug; var layout = @"${message}"; var consoleTarget = new ColoredConsoleTarget(); config.AddTarget("console", consoleTarget); consoleTarget.Layout = layout; var rule1 = new LoggingRule("*", loglevel, consoleTarget); config.LoggingRules.Add(rule1); LogManager.Configuration = config; var l = LogManager.GetLogger("foo"); // var sourceDir = @"D:\SynologyDrive\EventLogs\To Fix\Damaged"; var sourceDir = @"D:\SynologyDrive\EventLogs\To Fix"; var files = Directory.GetFiles(sourceDir, "*.evtx").ToList(); // var files = Directory.GetFiles(@"D:\SynologyDrive\EventLogs\To Fix\Template OK","*.evtx").ToList(); l.Info($"{sourceDir}"); var total = 0; var total2 = 0; foreach (var file in files) { l.Info( $"\r\n\r\n\r\n-------------------------- file {Path.GetFileName(file)}--------------------------"); using (var fs = new FileStream(file, FileMode.Open, FileAccess.Read)) { try { var es = new EventLog(fs); foreach (var eventRecord in es.GetEventRecords()) // try { // l.Info( eventRecord); //l.Info(eventRecord.ConvertPayloadToXml()); //eventRecord.ConvertPayloadToXml(); } // catch (Exception e) // { // l.Error($"Record: {eventRecord} failed to parse: {e.Message} {e.StackTrace}"); // } foreach (var esEventIdMetric in es.EventIdMetrics.OrderBy(t => t.Key)) { total2 += esEventIdMetric.Value; l.Info($"{esEventIdMetric.Key}: {esEventIdMetric.Value:N0}"); } l.Info($"Total from here: {total:N0}"); l.Info($"Total2 from here: {total2:N0}"); l.Info($"Event log details: {es}"); l.Info($"Event log error count: {es.ErrorRecords.Count:N0}"); Check.That(es.ErrorRecords.Count).IsEqualTo(0); } catch (Exception e) { l.Error($"FILE : {file} failed to parse: {e.Message} {e.StackTrace}"); } } } }
/// <summary> /// Configures the n log. /// </summary> /// <param name="logToFile">if set to <c>true</c> [log to file].</param> /// <param name="ruleNameAndFileSet">The rule name and < file name, Logging Level >. Key is rule name; value is file name (not full path).</param> public static void ConfigureNLog(bool logToFile, Dictionary <string, Tuple <string, LoggingLevel> > ruleNameAndFileSet) { // Step 1. Create configuration object var config = new LoggingConfiguration(); // Step 2. Create targets and add them to the configuration string format = @"${time}|${pad:padding=5:inner=${level:uppercase=true}}| ${message}"; // Step 3. Set target properties if (logToFile) { string format2 = @"${time}|${pad:padding=5:inner=${level:uppercase=true}}|${logger}| ${message}"; string fileName = "${shortdate}.log", logDir = LogDirectory; if (ruleNameAndFileSet != null && ruleNameAndFileSet.Count > 0) { var nullTarget = new NullTarget("BlackHole"); config.AddTarget("BlackHole", nullTarget); int i = 0; foreach (var item in ruleNameAndFileSet) { if (string.IsNullOrWhiteSpace(item.Key) || item.Key == "*") { continue; } if (!string.IsNullOrWhiteSpace(item.Value.Item1) && item.Value.Item1 != fileName) { var name = "file_" + (++i); var target = new FileTarget { EnableFileDelete = true, CreateDirs = true, Layout = format2, FileName = Path.Combine(logDir, item.Value.Item1), Name = name, }; config.AddTarget(name, target); var level = item.Value.Item2; config.LoggingRules.Add(new LoggingRule(item.Key, LogLevel.FromString(level.ToString()), target) { Final = true }); if (level != LoggingLevel.Trace) { config.LoggingRules.Add(new LoggingRule(item.Key, LogLevel.Trace, nullTarget) { Final = true }); } } } } var fileTarget = new FileTarget { EnableFileDelete = true, CreateDirs = true, Layout = format, FileName = Path.Combine(logDir, fileName), Name = "file", }; config.AddTarget("file", fileTarget); config.LoggingRules.Add(new LoggingRule("*", LogLevel.Trace, fileTarget)); } #if DEBUG var consoleTarget = new ColoredConsoleTarget { Name = "console", Layout = format, }; config.AddTarget("console", consoleTarget); config.LoggingRules.Add(new LoggingRule("*", LogLevel.Trace, consoleTarget)); var debugTarget = new DebuggerTarget { Name = "debug", Layout = format, }; config.AddTarget("debug", debugTarget); config.LoggingRules.Add(new LoggingRule("*", LogLevel.Trace, debugTarget)); #endif // Step 5. Activate the configuration LogManager.Configuration = config; }
public static void Main(string[] args) { var configuration = (EventStoreServiceConfiguration)ConfigurationManager.GetSection("eventStore"); var address = NetworkHelpers.GetIPAddress(); if (args.Contains("--console", StringComparer.CurrentCultureIgnoreCase)) { var config = new LoggingConfiguration(); var consoleTarget = new ColoredConsoleTarget { Layout = "${message}" }; config.AddTarget("console", consoleTarget); var rule = new LoggingRule("*", LogLevel.Debug, consoleTarget); config.LoggingRules.Add(rule); LogManager.Configuration = config; } if (args.Length == 1 && args[0] == "--test") { var config = new LoggingConfiguration(); var consoleTarget = new ColoredConsoleTarget { Layout = "${message}" }; config.AddTarget("console", consoleTarget); var rule = new LoggingRule("*", LogLevel.Debug, consoleTarget); config.LoggingRules.Add(rule); LogManager.Configuration = config; var logger = LogManager.GetLogger("config"); // ReSharper disable once ObjectCreationAsStatement new EventStoreService(address, configuration, logger); return; } HostFactory.Run( hc => { hc.RunAsLocalSystem(); hc.StartAutomatically(); hc.EnableShutdown(); hc.EnableServiceRecovery(c => c.RestartService(1)); hc.Service <EventStoreService>( s => { s.ConstructUsing(name => new EventStoreService(address, configuration, LogManager.GetLogger("eventstorehost"))); s.WhenStarted(tc => tc.Start()); s.WhenStopped(tc => tc.Stop()); }); hc.SetDescription("EventStore OSS Cluster Host Service"); hc.SetDisplayName("EventStore Host"); hc.SetServiceName("EventStoreHost"); }); Console.ReadLine(); }
public static void ConfigureLogging(LoggingSettings loggingSettings) { LogManager.Use <NLogFactory>(); const long megaByte = 1024 * 1024; if (NLog.LogManager.Configuration != null) { return; } var nlogConfig = new LoggingConfiguration(); var simpleLayout = new SimpleLayout("${longdate}|${threadid}|${level}|${logger}|${message}${onexception:${newline}${exception:format=tostring}}"); var fileTarget = new FileTarget { ArchiveEvery = FileArchivePeriod.Day, FileName = Path.Combine(loggingSettings.LogPath, "logfile.${shortdate}.txt"), ArchiveFileName = Path.Combine(loggingSettings.LogPath, "logfile.{#}.txt"), ArchiveNumbering = ArchiveNumberingMode.DateAndSequence, Layout = simpleLayout, MaxArchiveFiles = 14, ArchiveAboveSize = 30 * megaByte }; var ravenFileTarget = new FileTarget { ArchiveEvery = FileArchivePeriod.Day, FileName = Path.Combine(loggingSettings.LogPath, "ravenlog.${shortdate}.txt"), ArchiveFileName = Path.Combine(loggingSettings.LogPath, "ravenlog.{#}.txt"), ArchiveNumbering = ArchiveNumberingMode.DateAndSequence, Layout = simpleLayout, MaxArchiveFiles = 14, ArchiveAboveSize = 30 * megaByte }; var consoleTarget = new ColoredConsoleTarget { Layout = simpleLayout, UseDefaultRowHighlightingRules = true }; var nullTarget = new NullTarget(); // There lines don't appear to be necessary. The rules seem to work without implicitly adding the targets?!? nlogConfig.AddTarget("console", consoleTarget); nlogConfig.AddTarget("debugger", fileTarget); nlogConfig.AddTarget("raven", ravenFileTarget); nlogConfig.AddTarget("bitbucket", nullTarget); // Only want to see raven errors nlogConfig.LoggingRules.Add(new LoggingRule("Raven.*", loggingSettings.RavenDBLogLevel, ravenFileTarget)); nlogConfig.LoggingRules.Add(new LoggingRule("Raven.*", LogLevel.Error, consoleTarget)); //Noise reduction - Only RavenDB errors on the console nlogConfig.LoggingRules.Add(new LoggingRule("Raven.*", LogLevel.Debug, nullTarget) { Final = true }); //Will swallow debug and above messages // Always want to see license logging regardless of default logging level nlogConfig.LoggingRules.Add(new LoggingRule("Particular.ServiceControl.Licensing.*", LogLevel.Info, fileTarget)); nlogConfig.LoggingRules.Add(new LoggingRule("Particular.ServiceControl.Licensing.*", LogLevel.Info, consoleTarget) { Final = true }); // Defaults nlogConfig.LoggingRules.Add(new LoggingRule("*", loggingSettings.LoggingLevel, fileTarget)); nlogConfig.LoggingRules.Add(new LoggingRule("*", loggingSettings.LoggingLevel < LogLevel.Info ? loggingSettings.LoggingLevel : LogLevel.Info, consoleTarget)); // Remove Console Logging if not needed if (!loggingSettings.PrintToConsole) { foreach (var rule in nlogConfig.LoggingRules.Where(p => p.Targets.Contains(consoleTarget)).ToList()) { nlogConfig.LoggingRules.Remove(rule); } } NLog.LogManager.Configuration = nlogConfig; }
public static async Task Main(string[] args) { int startPage = int.Parse(args[0]); int endPage = int.Parse(args[1]); Directory.CreateDirectory(@".\temp"); var outDir = Directory.CreateDirectory(@".\out"); List <AddonData> loadedData = Storage.LoadAddonData(); string date = DateTime.Now.ToString("yyyy_MM_dd_HH_mm_ss"); var directory = outDir.CreateSubdirectory(date); LoggingConfiguration config = new LoggingConfiguration(); ColoredConsoleTarget consoleTarget = new ColoredConsoleTarget("target1") { Layout = @"${date:format=HH\:mm\:ss} ${level} ${message} ${exception}" }; config.AddTarget(consoleTarget); FileTarget fileTarget = new FileTarget("target2") { FileName = directory.FullName + "/log.txt", Layout = "${longdate} ${level} ${message} ${exception}" }; config.AddTarget(fileTarget); config.AddRuleForAllLevels(fileTarget); // only errors to file config.AddRuleForAllLevels(consoleTarget); // all to console LogManager.Configuration = config; //logger = LogManager.GetLogger("AddonScraper"); var loggerFactory = new LoggerFactory(); loggerFactory.AddProvider(new NLogLoggerProvider()); //TODO: use a nlog provider for Microsoft.Extenstions.Logger, and add the provider here. logger = loggerFactory.CreateLogger("AddonScraper"); logger.LogInformation("Start"); logger.LogInformation("Loaded " + loadedData.Count); //log2.LogInformation("LOG2 start"); //HashSet<string> query = loadedData.GroupBy(x => x.FolderName) // .Where(g => g.Count() > 1) // .Select(g => g.Key) // .ToHashSet(); //List<AddonData> allDuplicates = loadedData.Where(ad => query.Contains(ad.FolderName)).ToList(); //allDuplicates.Sort((x, y) => x.FolderName.CompareTo(y.FolderName)); //Storage.SaveToFile(allDuplicates, "duplicates", Formatting.Indented, 1, 340); //logger.Info("done"); //await Task.Delay(20000); using (HttpClient httpClient = new HttpClient()) { //int start = 1; //int tries = 5; //int files = 68; //int span = 5; int start = startPage; int tries = 5; int files = endPage - startPage + 1; int span = 1; List <Task> tasks = new List <Task>(); List <CurseAddon> allCurse = new List <CurseAddon>(); List <AddonData> allValid = new List <AddonData>(); List <AddonData> allFailed = new List <AddonData>(); for (int i = 0; i < files; i++) { int from = start + (i * span); int to = from + span - 1; List <CurseAddon> scrapedAddons = await Scrape(httpClient, tries, from, to); List <CurseAddon> addons = scrapedAddons.Where(curseAddon => !IgnoredProjectNames.Contains(curseAddon.AddonURL)).ToList(); Storage.SaveToFile(directory, addons, from, to); allCurse.AddRange(addons); (List <AddonData> valid, List <AddonData> failed) = await FullProccess(httpClient, addons, tries, loadedData); Storage.SaveToFile(directory, valid, "valid", Formatting.None, from, to); Storage.SaveToFile(directory, failed, "failed", Formatting.Indented, from, to); allValid.AddRange(valid); allFailed.AddRange(failed); } int end = start + (files * span) - 1; Storage.SaveToFile(directory, allCurse, start, end); Storage.SaveToFile(directory, allValid, "allvalid", Formatting.None, start, end); Storage.SaveToFile(directory, allFailed, "allfailed", Formatting.Indented, start, end); HashSet <string> query = allValid.GroupBy(x => x.FolderName) .Where(g => g.Count() > 1) .Select(g => g.Key) .ToHashSet(); List <AddonData> allDuplicates = allValid.Where(ad => query.Contains(ad.FolderName)).ToList(); allDuplicates.Sort((x, y) => x.FolderName.CompareTo(y.FolderName)); Storage.SaveToFile(directory, allDuplicates, "duplicates", Formatting.Indented, start, end); } logger.LogInformation("End"); }
private static void ConfigureLogging() { var config = clusterConfig.Logging; var loggingConfig = new LoggingConfiguration(); if (config != null) { // parse level var level = !string.IsNullOrEmpty(config.Level) ? LogLevel.FromString(config.Level) : LogLevel.Info; var layout = "[${longdate}] [${level:format=FirstCharacter:uppercase=true}] [${logger:shortName=true}] ${message} ${exception:format=ToString,StackTrace}"; var nullTarget = new NullTarget("null") { }; loggingConfig.AddTarget(nullTarget); // Suppress some Aspnet stuff loggingConfig.AddRule(level, LogLevel.Info, nullTarget, "Microsoft.AspNetCore.Mvc.Internal.*", true); loggingConfig.AddRule(level, LogLevel.Info, nullTarget, "Microsoft.AspNetCore.Mvc.Infrastructure.*", true); // Api Log if (!string.IsNullOrEmpty(config.ApiLogFile) && !isShareRecoveryMode) { var target = new FileTarget("file") { FileName = GetLogPath(config, config.ApiLogFile), FileNameKind = FilePathKind.Unknown, Layout = layout }; loggingConfig.AddTarget(target); loggingConfig.AddRule(level, LogLevel.Fatal, target, "Microsoft.AspNetCore.*", true); } if (config.EnableConsoleLog || isShareRecoveryMode) { if (config.EnableConsoleColors) { var target = new ColoredConsoleTarget("console") { Layout = layout }; target.RowHighlightingRules.Add(new ConsoleRowHighlightingRule( ConditionParser.ParseExpression("level == LogLevel.Trace"), ConsoleOutputColor.DarkMagenta, ConsoleOutputColor.NoChange)); target.RowHighlightingRules.Add(new ConsoleRowHighlightingRule( ConditionParser.ParseExpression("level == LogLevel.Debug"), ConsoleOutputColor.Gray, ConsoleOutputColor.NoChange)); target.RowHighlightingRules.Add(new ConsoleRowHighlightingRule( ConditionParser.ParseExpression("level == LogLevel.Info"), ConsoleOutputColor.White, ConsoleOutputColor.NoChange)); target.RowHighlightingRules.Add(new ConsoleRowHighlightingRule( ConditionParser.ParseExpression("level == LogLevel.Warn"), ConsoleOutputColor.Yellow, ConsoleOutputColor.NoChange)); target.RowHighlightingRules.Add(new ConsoleRowHighlightingRule( ConditionParser.ParseExpression("level == LogLevel.Error"), ConsoleOutputColor.Red, ConsoleOutputColor.NoChange)); target.RowHighlightingRules.Add(new ConsoleRowHighlightingRule( ConditionParser.ParseExpression("level == LogLevel.Fatal"), ConsoleOutputColor.DarkRed, ConsoleOutputColor.White)); loggingConfig.AddTarget(target); loggingConfig.AddRule(level, LogLevel.Fatal, target); } else { var target = new ConsoleTarget("console") { Layout = layout }; loggingConfig.AddTarget(target); loggingConfig.AddRule(level, LogLevel.Fatal, target); } } if (!string.IsNullOrEmpty(config.LogFile) && !isShareRecoveryMode) { var target = new FileTarget("file") { FileName = GetLogPath(config, config.LogFile), FileNameKind = FilePathKind.Unknown, Layout = layout }; loggingConfig.AddTarget(target); loggingConfig.AddRule(level, LogLevel.Fatal, target); } if (config.PerPoolLogFile && !isShareRecoveryMode) { foreach (var poolConfig in clusterConfig.Pools) { var target = new FileTarget(poolConfig.Id) { FileName = GetLogPath(config, poolConfig.Id + ".log"), FileNameKind = FilePathKind.Unknown, Layout = layout }; loggingConfig.AddTarget(target); loggingConfig.AddRule(level, LogLevel.Fatal, target, poolConfig.Id); } } } LogManager.Configuration = loggingConfig; logger = LogManager.GetLogger("Core"); }
/// <summary> /// Setup all the logging targets and rules. Call only once, usually at the start of the program. /// </summary> public static void Initialize() { Directory.CreateDirectory(Constants.LogDirectory); LoggingConfiguration loggingConfiguration = new LoggingConfiguration(); // Setup and layout formatting for the console ColoredConsoleTarget consoleTarget = new ColoredConsoleTarget() { Name = Constants.ApplicationName, //Layout = "${message}" // Match the console target format with file targets. It looks cluttered on small terminals Layout = "${longdate} [${pad:padCharacter= :padding=5:fixedLength=true:alignmentOnTruncation=Right:${uppercase:${level}}}] [${callsite:includeNamespace=false:cleanNamesOfAnonymousDelegates=true:cleanNamesOfAsyncContinuations=true}] ${message}" }; // Override the trace color ConsoleRowHighlightingRule consoleTarget_RowRules_Trace = new ConsoleRowHighlightingRule() { Condition = ConditionParser.ParseExpression("level == LogLevel.Trace"), ForegroundColor = ConsoleOutputColor.Gray }; consoleTarget.RowHighlightingRules.Add(consoleTarget_RowRules_Trace); // Override the debug color ConsoleRowHighlightingRule consoleTarget_RowRules_Debug = new ConsoleRowHighlightingRule() { Condition = ConditionParser.ParseExpression("level == LogLevel.Debug"), ForegroundColor = ConsoleOutputColor.Gray }; consoleTarget.RowHighlightingRules.Add(consoleTarget_RowRules_Debug); // Override the info color ConsoleRowHighlightingRule consoleTarget_RowRules_Info = new ConsoleRowHighlightingRule() { Condition = ConditionParser.ParseExpression("level == LogLevel.Info"), ForegroundColor = ConsoleOutputColor.White }; consoleTarget.RowHighlightingRules.Add(consoleTarget_RowRules_Info); // Override the warn color ConsoleRowHighlightingRule consoleTarget_RowRules_Warn = new ConsoleRowHighlightingRule() { Condition = ConditionParser.ParseExpression("level == LogLevel.Warn"), ForegroundColor = ConsoleOutputColor.Yellow }; consoleTarget.RowHighlightingRules.Add(consoleTarget_RowRules_Warn); // Override the error color ConsoleRowHighlightingRule consoleTarget_RowRules_Error = new ConsoleRowHighlightingRule() { Condition = ConditionParser.ParseExpression("level == LogLevel.Error"), ForegroundColor = ConsoleOutputColor.Red }; consoleTarget.RowHighlightingRules.Add(consoleTarget_RowRules_Error); // Override the fatal color ConsoleRowHighlightingRule consoleTarget_RowRules_Fatal = new ConsoleRowHighlightingRule() { Condition = ConditionParser.ParseExpression("level == LogLevel.Fatal"), ForegroundColor = ConsoleOutputColor.Red }; consoleTarget.RowHighlightingRules.Add(consoleTarget_RowRules_Fatal); // Add consoleTarget to the overall configuration loggingConfiguration.AddTarget(consoleTarget); loggingConfiguration.AddRule(LogLevel.Trace, LogLevel.Fatal, Constants.ApplicationName); // ================================= // All messages from Trace to Warn levels write to the general file FileTarget fileTarget_General = new FileTarget() { Name = Constants.ApplicationName, FileName = Path.Combine(Constants.LogDirectory, "General.log"), Layout = "${longdate} [${pad:padCharacter= :padding=5:fixedLength=true:alignmentOnTruncation=Right:${uppercase:${level}}}] [${callsite:includeNamespace=false:cleanNamesOfAnonymousDelegates=true:cleanNamesOfAsyncContinuations=true}] ${message}", ArchiveFileName = Path.Combine(Constants.LogDirectory, "General{#}.Archive.log"), ArchiveEvery = FileArchivePeriod.Day, ArchiveNumbering = ArchiveNumberingMode.Rolling, MaxArchiveFiles = 7, ConcurrentWrites = false }; // Limit how often the file will get written to disk. // Default: BufferSize = 50 (log events), FlushTimeout = 5000 (milliseconds) BufferingTargetWrapper fileAsyncTargetWrapper_General = new BufferingTargetWrapper { Name = Constants.ApplicationName, WrappedTarget = fileTarget_General, BufferSize = 50, FlushTimeout = 5000, SlidingTimeout = false }; loggingConfiguration.AddTarget(fileAsyncTargetWrapper_General); loggingConfiguration.AddRule(LogLevel.Trace, LogLevel.Warn, Constants.ApplicationName); // All messages from Warn to Fatal levels write to the error file with advanced trace information FileTarget fileTarget_Error = new FileTarget() { Name = Constants.ApplicationName, FileName = Path.Combine(Constants.LogDirectory, "Error.log"), Layout = "${longdate} [${pad:padCharacter= :padding=5:fixedLength=true:alignmentOnTruncation=Right:${uppercase:${level}}}] [${callsite:includeSourcePath=true:cleanNamesOfAnonymousDelegates=true:cleanNamesOfAsyncContinuations=true}:${callsite-linenumber}; ${stacktrace}] ${message}${exception:format=ToString,StackTrace}", ArchiveFileName = Path.Combine(Constants.LogDirectory, "Error{#}.Archive.log"), ArchiveEvery = FileArchivePeriod.Day, ArchiveNumbering = ArchiveNumberingMode.Rolling, MaxArchiveFiles = 7, ConcurrentWrites = false }; loggingConfiguration.AddTarget(fileTarget_Error); loggingConfiguration.AddRule(LogLevel.Error, LogLevel.Fatal, Constants.ApplicationName); // Apply all the custom configurations to the LogManager LogManager.Configuration = loggingConfiguration; Log.Info("Logging initialization finished."); }
public static void Configure(Settings settings, bool printToConsole) { LogManager.Use <NLogFactory>(); if (NLog.LogManager.Configuration != null) { return; } var version = FileVersionInfo.GetVersionInfo(typeof(Host).Assembly.Location).ProductVersion; var nlogConfig = new LoggingConfiguration(); var simpleLayout = new SimpleLayout("${longdate}|${threadid}|${level}|${logger}|${message}${onexception:${newline}${exception:format=tostring}}"); var header = $@"------------------------------------------------------------- ServiceControl Monitoring Version: {version} Selected Transport: {settings.TransportType} -------------------------------------------------------------"; var fileTarget = new FileTarget { ArchiveEvery = FileArchivePeriod.Day, FileName = Path.Combine(settings.LogPath, "logfile.${shortdate}.txt"), ArchiveFileName = Path.Combine(settings.LogPath, "logfile.{#}.txt"), ArchiveNumbering = ArchiveNumberingMode.DateAndSequence, Layout = simpleLayout, MaxArchiveFiles = 14, ArchiveAboveSize = 30 * MegaByte, Header = new SimpleLayout(header) }; var consoleTarget = new ColoredConsoleTarget { Layout = simpleLayout, UseDefaultRowHighlightingRules = true }; var nullTarget = new NullTarget(); nlogConfig.AddTarget("console", consoleTarget); nlogConfig.AddTarget("debugger", fileTarget); nlogConfig.AddTarget("null", nullTarget); //Suppress NSB license logging since this will have it's own nlogConfig.LoggingRules.Add(new LoggingRule("NServiceBus.LicenseManager", LogLevel.Info, nullTarget) { Final = true }); // Always want to see license logging regardless of default logging level nlogConfig.LoggingRules.Add(new LoggingRule("ServiceControl.Monitoring.Licensing.*", LogLevel.Info, fileTarget)); nlogConfig.LoggingRules.Add(new LoggingRule("ServiceControl.Monitoring.Licensing.*", LogLevel.Info, consoleTarget) { Final = true }); // Defaults nlogConfig.LoggingRules.Add(new LoggingRule("*", settings.LogLevel, fileTarget)); nlogConfig.LoggingRules.Add(new LoggingRule("*", settings.LogLevel < LogLevel.Info ? settings.LogLevel : LogLevel.Info, consoleTarget)); // Remove Console Logging if not needed if (!printToConsole) { foreach (var rule in nlogConfig.LoggingRules.Where(p => p.Targets.Contains(consoleTarget)).ToList()) { nlogConfig.LoggingRules.Remove(rule); } } NLog.LogManager.Configuration = nlogConfig; var logger = LogManager.GetLogger("LoggingConfiguration"); var logEventInfo = new LogEventInfo { TimeStamp = DateTime.Now }; logger.InfoFormat("Logging to {0} with LogLevel '{1}'", fileTarget.FileName.Render(logEventInfo), settings.LogLevel.Name); }
/// <summary> /// Default initialization for on-premise paths /// </summary> private void InitializeForPremise() { // Replace log file and role name settings in the configuration var currentCfg = LogManager.Configuration; if (currentCfg == null) { Trace.WriteLine("No on-premise NLog configuration available - creating default config"); var level = global::NLog.LogLevel.Debug; var config = new LoggingConfiguration(); var console = new ColoredConsoleTarget() { UseDefaultRowHighlightingRules = true, Layout = "${date:format=HH\\:MM\\:ss} ${logger} ${message}" }; var file = new FileTarget() { FileName = "${basedir}/application.log", Layout = "${date:format=HH\\:MM\\:ss} ${logger} ${message}" }; var debug = new DebuggerTarget() { Layout = "${date:format=HH\\:MM\\:ss} ${logger} ${message}" }; config.AddTarget("debug", debug); config.AddTarget("console", console); config.AddTarget("file", file); config.LoggingRules.Add(new LoggingRule("*", level, console)); config.LoggingRules.Add(new LoggingRule("*", level, file)); config.LoggingRules.Add(new LoggingRule("*", level, debug)); LogManager.Configuration = config; } else { Trace.WriteLine("Using NLog.config for non-Azure deployment"); } }
private static void Main(string[] args) { bool processedargs = false; // Please dont kill the commented out lines below for the moment -NV //Misc.Playfields.Instance.playfields[0].districts.Add(new ZoneEngine.Misc.DistrictInfo()); //Misc.Playfields.Instance.playfields[0].districts[0].districtName = "some district"; //Misc.Playfields.Instance.playfields[0].districts.Add(new ZoneEngine.Misc.DistrictInfo()); //Misc.Playfields.Instance.playfields[0].districts[1].districtName = "some other district"; //Misc.DistrictInfo.DumpXML(@"C:\list.xml", Misc.Playfields.Instance.playfields[0]); #region Console Text... Console.Title = "CellAO " + AssemblyInfoclass.Title + " Console. Version: " + AssemblyInfoclass.Description + " " + AssemblyInfoclass.AssemblyVersion + " " + AssemblyInfoclass.Trademark; ConsoleText ct = new ConsoleText(); ct.TextRead("main.txt"); Console.WriteLine("Loading " + AssemblyInfoclass.Title + "..."); Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("Using ISComm v1.0"); Console.WriteLine("[OK]"); Console.ResetColor(); #endregion #region Delete old SqlError.log, so it doesnt get too big if (File.Exists("sqlerror.log")) { File.Delete("sqlerror.log"); } #endregion #region ISComm Code Area... Console.WriteLine("[ISComm] Waiting for Link..."); ChatCom.StartLink(Config.Instance.CurrentConfig.CommPort); //System.Console.WriteLine("[ISComm] Linked Successfully! :D"); #endregion zoneServer = new Server { EnableTCP = true, EnableUDP = false }; #region Script Loading Code Area.. csc = new ScriptCompiler(); #endregion try { zoneServer.TcpIP = IPAddress.Parse(Config.Instance.CurrentConfig.ListenIP); } catch { ct.TextRead("ip_config_parse_error.txt"); Console.ReadKey(); return; } try { zoneServer.UdpIP = IPAddress.Parse(Config.Instance.CurrentConfig.ListenIP); } catch { ct.TextRead("ip_config_parse_error.txt"); Console.ReadKey(); return; } zoneServer.TcpPort = Convert.ToInt32(Config.Instance.CurrentConfig.ZonePort); #region NLog LoggingConfiguration config = new LoggingConfiguration(); ColoredConsoleTarget consoleTarget = new ColoredConsoleTarget(); consoleTarget.Layout = "${date:format=HH\\:MM\\:ss} ${logger} ${message}"; FileTarget fileTarget = new FileTarget(); config.AddTarget("file", fileTarget); fileTarget.FileName = "${basedir}/ZoneEngineLog.txt"; fileTarget.Layout = "${date:format=HH\\:MM\\:ss} ${logger} ${message}"; LoggingRule rule1 = new LoggingRule("*", LogLevel.Trace, consoleTarget); config.LoggingRules.Add(rule1); LoggingRule rule2 = new LoggingRule("*", LogLevel.Trace, fileTarget); config.LoggingRules.Add(rule2); LogManager.Configuration = config; #endregion #region NBug SettingsOverride.LoadCustomSettings("NBug.ZoneEngine.Config"); NBug.Settings.WriteLogToDisk = true; AppDomain.CurrentDomain.UnhandledException += Handler.UnhandledException; TaskScheduler.UnobservedTaskException += Handler.UnobservedTaskException; //TODO: ADD More Handlers. #endregion FunctionC.ReadFunctions(); Console.WriteLine("Registered " + FunctionC.NumberofRegisteredFunctions().ToString() + " Functions"); #region Console Commands... string consoleCommand; ct.TextRead("zone_consolecommands.txt"); // removed CheckDBs here, added commands check and updatedb (updatedb will change to a versioning while (true) { if (!processedargs) { if (args.Length == 1) { if (args[0].ToLower() == "/autostart") { ct.TextRead("autostart.txt"); csc.Compile(false); StartTheServer(); } } processedargs = true; } Console.Write("\nServer Command >>"); consoleCommand = Console.ReadLine(); switch (consoleCommand.ToLower()) { case "start": if (zoneServer.Running) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Zone Server is already running"); Console.ResetColor(); break; } //TODO: Add Sql Check. csc.Compile(false); StartTheServer(); break; case "startm": // Multiple dll compile if (zoneServer.Running) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Zone Server is already running"); Console.ResetColor(); break; } //TODO: Add Sql Check. csc.Compile(true); StartTheServer(); break; case "stop": if (!zoneServer.Running) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Zone Server is not running"); Console.ResetColor(); break; } zoneServer.Stop(); ThreadMgr.Stop(); break; case "check": case "updatedb": using (SqlWrapper sqltester = new SqlWrapper()) { sqltester.CheckDBs(); Console.ResetColor(); } break; case "exit": case "quit": if (zoneServer.Running) { zoneServer.Stop(); ThreadMgr.Stop(); } Process.GetCurrentProcess().Kill(); break; case "ls": //list all available scripts, dont remove it since it does what it should Console.WriteLine("Available scripts"); /* Old Lua way * string[] files = Directory.GetFiles("Scripts");*/ string[] files = Directory.GetFiles("Scripts\\", "*.cs", SearchOption.AllDirectories); if (files.Length == 0) { Console.WriteLine("No scripts were found."); break; } Console.ForegroundColor = ConsoleColor.Green; foreach (string s in files) { Console.WriteLine(s); /* Old Lua way * if (s.EndsWith(".lua")) * { * Console.WriteLine(s.Split('\\')[1].Split('.')[0]); * }*/ } Console.ResetColor(); break; case "ping": // ChatCom.Server.Ping(); Console.WriteLine("Ping is disabled till we can fix it"); break; case "running": if (zoneServer.Running) { Console.WriteLine("Zone Server is Running"); break; } Console.WriteLine("Zone Server not Running"); break; case "online": if (zoneServer.Running) { Console.ForegroundColor = ConsoleColor.White; lock (zoneServer.Clients) { foreach (Client c in zoneServer.Clients) { Console.WriteLine("Character " + c.Character.Name + " online"); } } Console.ResetColor(); } break; default: ct.TextRead("zone_consolecmdsdefault.txt"); break; } } }
/// <summary> /// Initializes logging framework /// </summary> private static void InitializeLogger() { LoggingConfiguration config = new LoggingConfiguration(); // Create targets and add them to the configuration ColoredConsoleTarget consoleTarget = new ColoredConsoleTarget(); config.AddTarget("console", consoleTarget); FileTarget fileTarget = new FileTarget(); config.AddTarget("file", fileTarget); // Step 3. Set target properties consoleTarget.Layout = "${date:format=HH\\:MM\\:ss}: ${message}"; // set the file fileTarget.FileName = DUCoverConstants.LogFileName; fileTarget.Layout = "${date:format=HH\\:MM\\:ss}: ${message}"; fileTarget.DeleteOldFileOnStartup = true; // Step 4. Define rules LoggingRule rule1 = new LoggingRule("*", LogLevel.Debug, consoleTarget); config.LoggingRules.Add(rule1); LoggingRule rule2 = new LoggingRule("*", LogLevel.Debug, fileTarget); config.LoggingRules.Add(rule2); LogManager.Configuration = config; }