public ResultSummary Run(object fixture, SpecificationConfig specificationConfig)
        {
            var source = string.IsNullOrEmpty(specificationConfig.BaseInputDirectory)
                ? (Source)new EmbeddedResourceSource(fixture.GetType().Assembly)
                : new FileSource(fixture.GetType().Assembly, specificationConfig.BaseInputDirectory);

            var target = new FileTarget(specificationConfig.BaseOutputDirectory);

            var testSummary = new SummarizingResultRecorder();
            var anySpecExecuted = false;

            var fileExtensions = specificationConfig.SpecificationFileExtensions;
            foreach (var fileExtension in fileExtensions)
            {
                var specLocator = new ClassNameBasedSpecificationLocator(fileExtension);
                var specResource = specLocator.locateSpecification(fixture);
                if (source.canFind(specResource))
                {
                    var fixtureResult = RunSingleSpecification(fixture, source, specLocator, target, specificationConfig);
                    AddToTestResults(fixtureResult, testSummary);
                    anySpecExecuted = true;
                }
            }
            if (anySpecExecuted) return testSummary;

            throw new InvalidOperationException(string.Format("no specification extensions defined for: {0}", specificationConfig));
        }
        public void Test_Can_Get_File_Path_Successfully()
        {
            var resource = new Resource("\\blah\\blah.txt");

            var target = new FileTarget(new File(@"c:\temp"), new IOUtil());

            Assert.AreEqual(@"c:\temp\blah\blah.txt", target.resolvedPathFor(resource));
        }
예제 #3
0
파일: Program.cs 프로젝트: MGramolini/vodca
        /// <summary>
        /// Initializes static members of the <see cref="Program"/> class.
        /// </summary>
        static Program()
        {
            var folder = Environment.CurrentDirectory.EnsureEndsWith(@"\");

            var target = new FileTarget
            {
                Layout = "${longdate} ${message}",
                FileName = folder + @"yuicompressor-${level}.log",
                KeepFileOpen = false
            };

            Vodca.SDK.NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Debug);
        }
예제 #4
0
 private void scheduler_DragDrop(object sender, DragEventArgs e)
 {
     if (!e.Data.GetDataPresent(DataFormats.FileDrop))
     e.Effect = DragDropEffects.None;
        else
        {
     string[] files = (string[])e.Data.GetData(DataFormats.FileDrop, false);
     if (e.Effect == DragDropEffects.Copy)
     {
      foreach (string file in files)
       using (FileStream stream = new FileStream(file, FileMode.Open,
        FileAccess.Read, FileShare.Read))
       {
        try
        {
     Program.eraserClient.Tasks.LoadFromStream(stream);
        }
        catch (SerializationException ex)
        {
     MessageBox.Show(S._("Could not import task list from {0}. The " +
      "error returned was: {1}", file, ex.Message), S._("Eraser"),
      MessageBoxButtons.OK, MessageBoxIcon.Error,
      MessageBoxDefaultButton.Button1,
      S.IsRightToLeft(null) ?
       MessageBoxOptions.RtlReading | MessageBoxOptions.RightAlign : 0);
        }
       }
     }
     else if (e.Effect == DragDropEffects.Move)
     {
      Task task = new Task();
      foreach (string file in files)
      {
       FileSystemObjectTarget target;
       if (Directory.Exists(file))
        target = new FolderTarget();
       else
        target = new FileTarget();
       target.Path = file;
       task.Targets.Add(target);
      }
      Program.eraserClient.Tasks.Add(task);
     }
        }
        DropTargetHelper.Drop(e.Data, new Point(e.X, e.Y), e.Effect);
 }
예제 #5
0
        private void IntializeLogger(string logPath, LoggerLevel logLevel)
        {
            if (logPath.StartsWith("/"))
            {
                logPath = HostingEnvironment.MapPath(logPath);
            }

            var config = new LoggingConfiguration();

            var fileTarget = new FileTarget();

            fileTarget.Layout = "${message}";

            config.AddTarget("file", fileTarget);

            if (logPath.EndsWith(".log"))
            {
                fileTarget.FileName = logPath;
            }
            else
            {
                var logFile = "MissionSearch.log";
                fileTarget.FileName = string.Format(@"{0}\{1}", logPath, logFile);
            }



            switch (logLevel)
            {
            case LoggerLevel.Debug:
                config.LoggingRules.Add(new LoggingRule("*", NLog.LogLevel.Trace, fileTarget));
                break;

            case LoggerLevel.Info:
                config.LoggingRules.Add(new LoggingRule("*", NLog.LogLevel.Info, fileTarget));
                break;

            case LoggerLevel.Error:
                config.LoggingRules.Add(new LoggingRule("*", NLog.LogLevel.Error, fileTarget));
                break;
            }

            /*
             * if (logLevel == LogLevel.Info)
             * {
             *  var rule2 = new LoggingRule("*", LogLevel.Info, fileTarget);
             *  config.LoggingRules.Add(rule2);
             * }
             * else if (logLevel == LogLevel.Trace)
             * {
             *  var rule2 = new LoggingRule("*", LogLevel.Info, fileTarget);
             *  config.LoggingRules.Add(rule2);
             *
             *  var rule3 = new LoggingRule("*", LogLevel.Trace, fileTarget);
             *  config.LoggingRules.Add(rule3);
             * }
             * */

            LogManager.Configuration = config;

            _logger = LogManager.GetLogger("MissionSearch");
        }
예제 #6
0
        private static void CommandAddTask(ConsoleArguments arg)
        {
            AddTaskArguments arguments = (AddTaskArguments)arg;

               Task task = new Task();
               ErasureMethod method = arguments.ErasureMethod == Guid.Empty ?
            ErasureMethodManager.Default :
            ErasureMethodManager.GetInstance(arguments.ErasureMethod);
               switch (arguments.Schedule.ToUpperInvariant())
               {
            case "NOW":
             task.Schedule = Schedule.RunNow;
             break;
            case "MANUALLY":
             task.Schedule = Schedule.RunManually;
             break;
            case "RESTART":
             task.Schedule = Schedule.RunOnRestart;
             break;
            default:
             throw new ArgumentException(string.Format(CultureInfo.CurrentCulture,
              "Unknown schedule type: {0}", arguments.Schedule), "--schedule");
               }

               List<string> trueValues = new List<string>(new string[] { "yes", "true" });
               string[] strings = new string[] {

            "(?<recycleBin>recyclebin)",

            "unused=(?<unusedVolume>.*)(?<unusedTips>,clusterTips(=(?<unusedTipsValue>true|false))?)?",

            "dir=(?<directoryName>.*)(?<directoryParams>(?<directoryExcludeMask>,-[^,]+)|(?<directoryIncludeMask>,\\+[^,]+)|(?<directoryDeleteIfEmpty>,deleteIfEmpty(=(?<directoryDeleteIfEmptyValue>true|false))?))*",

            "file=(?<fileName>.*)"
               };

               Regex regex = new Regex(string.Join("|", strings),
            RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.RightToLeft);
               foreach (string argument in arguments.PositionalArguments)
               {
            Match match = regex.Match(argument);
            if (match.Captures.Count == 0)
            {
             Console.WriteLine("Unknown argument: {0}, skipped.", argument);
             continue;
            }

            ErasureTarget target = null;
            if (match.Groups["recycleBin"].Success)
            {
             target = new RecycleBinTarget();
            }
            else if (match.Groups["unusedVolume"].Success)
            {
             UnusedSpaceTarget unusedSpaceTarget = new UnusedSpaceTarget();
             target = unusedSpaceTarget;
             unusedSpaceTarget.Drive = match.Groups["unusedVolume"].Value;

             if (!match.Groups["unusedTips"].Success)
              unusedSpaceTarget.EraseClusterTips = false;
             else if (!match.Groups["unusedTipsValue"].Success)
              unusedSpaceTarget.EraseClusterTips = true;
             else
              unusedSpaceTarget.EraseClusterTips =
               trueValues.IndexOf(match.Groups["unusedTipsValue"].Value) != -1;
            }
            else if (match.Groups["directoryName"].Success)
            {
             FolderTarget folderTarget = new FolderTarget();
             target = folderTarget;

             folderTarget.Path = match.Groups["directoryName"].Value;
             if (!match.Groups["directoryDeleteIfEmpty"].Success)
              folderTarget.DeleteIfEmpty = false;
             else if (!match.Groups["directoryDeleteIfEmptyValue"].Success)
              folderTarget.DeleteIfEmpty = true;
             else
              folderTarget.DeleteIfEmpty =
               trueValues.IndexOf(match.Groups["directoryDeleteIfEmptyValue"].Value) != -1;
             if (match.Groups["directoryExcludeMask"].Success)
              folderTarget.ExcludeMask += match.Groups["directoryExcludeMask"].Value.Remove(0, 2) + ' ';
             if (match.Groups["directoryIncludeMask"].Success)
              folderTarget.IncludeMask += match.Groups["directoryIncludeMask"].Value.Remove(0, 2) + ' ';
            }
            else if (match.Groups["fileName"].Success)
            {
             FileTarget fileTarget = new FileTarget();
             target = fileTarget;
             fileTarget.Path = match.Groups["fileName"].Value;
            }

            if (target == null)
             continue;

            target.Method = method;
            task.Targets.Add(target);
               }

               if (task.Targets.Count == 0)
            throw new ArgumentException("Tasks must contain at least one erasure target.");

               try
               {
            using (RemoteExecutorClient client = new RemoteExecutorClient())
            {
             client.Run();
             if (!client.IsConnected)
             {

              Process eraserInstance = Process.Start(
               Assembly.GetExecutingAssembly().Location, "--quiet");
              eraserInstance.WaitForInputIdle();

              client.Run();
              if (!client.IsConnected)
               throw new IOException("Eraser cannot connect to the running " +
            "instance for erasures.");
             }

             client.Tasks.Add(task);
            }
               }
               catch (UnauthorizedAccessException e)
               {

            throw new UnauthorizedAccessException("Another instance of Eraser " +
             "is already running but it is running with higher privileges than " +
             "this instance of Eraser. Tasks cannot be added in this manner.\n\n" +
             "Close the running instance of Eraser and start it again without " +
             "administrator privileges, or run the command again as an " +
             "administrator.", e);
               }
        }
예제 #7
0
        /// <summary>
        /// Extends the logging rules in the "NLog.config" with node log settings rules.
        /// </summary>
        /// <param name="settings">Node log settings to extend the rules from the configuration file, or null if no extension is required.</param>
        /// <param name="dataFolder">Data folder to determine path to log files.</param>
        private static void AddFilters(LogSettings settings = null, DataFolder dataFolder = null)
        {
            if (settings == null)
            {
                return;
            }

            logSettings = settings;
            folder      = dataFolder;

            // If we use "debug*" targets, which are defined in "NLog.config", make sure they log into the correct log folder in data directory.
            List <Target> debugTargets = LogManager.Configuration.AllTargets.Where(t => (t.Name != null) && t.Name.StartsWith("debug")).ToList();

            foreach (Target debugTarget in debugTargets)
            {
                FileTarget debugFileTarget = debugTarget is AsyncTargetWrapper ? (FileTarget)((debugTarget as AsyncTargetWrapper).WrappedTarget) : (FileTarget)debugTarget;
                string     currentFile     = debugFileTarget.FileName.Render(new LogEventInfo {
                    TimeStamp = DateTime.UtcNow
                });
                debugFileTarget.FileName = Path.Combine(folder.LogPath, Path.GetFileName(currentFile));

                if (debugFileTarget.ArchiveFileName != null)
                {
                    string currentArchive = debugFileTarget.ArchiveFileName.Render(new LogEventInfo {
                        TimeStamp = DateTime.UtcNow
                    });
                    debugFileTarget.ArchiveFileName = Path.Combine(folder.LogPath, currentArchive);
                }
            }

            // Remove rule that forbids logging before the logging is initialized.
            LoggingRule nullPreInitRule = null;

            foreach (LoggingRule rule in LogManager.Configuration.LoggingRules)
            {
                if (rule.Final && rule.NameMatches("*") && (rule.Targets.Count > 0) && (rule.Targets[0].Name == "null"))
                {
                    nullPreInitRule = rule;
                    break;
                }
            }

            LogManager.Configuration.LoggingRules.Remove(nullPreInitRule);

            // Configure main file target, configured using command line or node configuration file settings.
            var mainTarget = new FileTarget
            {
                Name             = "main",
                FileName         = Path.Combine(folder.LogPath, "node.txt"),
                ArchiveFileName  = Path.Combine(folder.LogPath, "node-${date:universalTime=true:format=yyyy-MM-dd}.txt"),
                ArchiveNumbering = ArchiveNumberingMode.Sequence,
                ArchiveEvery     = FileArchivePeriod.Day,
                MaxArchiveFiles  = 7,
                Layout           = "[${longdate:universalTime=true} ${threadid}${mdlc:item=id}] ${level:uppercase=true}: ${callsite} ${message}",
                Encoding         = Encoding.UTF8
            };

            LogManager.Configuration.AddTarget(mainTarget);

            // Default logging level is Info for all components.
            var defaultRule = new LoggingRule($"{nameof(Stratis)}.*", settings.LogLevel, mainTarget);

            if (settings.DebugArgs.Any() && settings.DebugArgs[0] != "1")
            {
                lock (KeyCategories)
                {
                    var usedCategories = new HashSet <string>(StringComparer.Ordinal);

                    // Increase selected categories to Debug.
                    foreach (string key in settings.DebugArgs)
                    {
                        if (!KeyCategories.TryGetValue(key.Trim(), out string category))
                        {
                            // Allow direct specification - e.g. "-debug=Stratis.Bitcoin.Miner".
                            category = key.Trim();
                        }

                        if (!usedCategories.Contains(category))
                        {
                            usedCategories.Add(category);
                            var rule = new LoggingRule(category, settings.LogLevel, mainTarget);
                            LogManager.Configuration.LoggingRules.Add(rule);
                        }
                    }
                }
            }

            LogManager.Configuration.LoggingRules.Add(defaultRule);

            // Apply new rules.
            LogManager.ReconfigExistingLoggers();
        }
예제 #8
0
        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}";

                if (config.EnableConsoleLog)
                {
                    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))
                {
                    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)
                {
                    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.GetCurrentClassLogger();
        }
예제 #9
0
        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  = "{0}" + Options.Separator + "{1}" + Options.Separator + "{2}" + Options.Separator + "{3}" + Options.Separator + "{4}" + Options.Separator + "{5}" + Options.Separator + "{6:u}" + Options.Separator + "{7}" + Options.Separator + "{8}";
                    shareResultTemplate = "{0}" + Options.Separator + "{1}";
                    dirResultTemplate   = "{0}" + Options.Separator + "{1}";
                }
                // otherwise just do the normal thing
                else
                {
                    // treat all as strings except LastWriteTime {6}
                    fileResultTemplate  = "{{{0}}}<{1}|{2}{3}|{4}|{5}|{6:u}>({7}) {8}";
                    shareResultTemplate = "{{{0}}}({1}) {2}";
                    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();
            }
        }
예제 #10
0
        public void AsyncMultiFileWrite()
        {
            //InternalLogger.LogToConsole = true;
            //InternalLogger.LogLevel = LogLevel.Trace;

            string tempPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());
            try
            {
                FileTarget ft = new FileTarget();
                ft.FileName = Path.Combine(tempPath, "${level}.txt");
                ft.LineEnding = LineEndingMode.LF;
                ft.Layout = "${message} ${threadid}";

                // this also checks that thread-volatile layouts
                // such as ${threadid} are properly cached and not recalculated
                // in logging threads.

                string threadID = Thread.CurrentThread.ManagedThreadId.ToString();

                //InternalLogger.LogToConsole = true;
                //InternalLogger.LogLevel = LogLevel.Trace;
                SimpleConfigurator.ConfigureForTargetLogging(new AsyncTargetWrapper(ft, 1000, AsyncTargetWrapperOverflowAction.Grow), LogLevel.Debug);
                LogManager.ThrowExceptions = true;

                for (int i = 0; i < 250; ++i)
                {
                    logger.Trace("@@@");
                    logger.Debug("aaa");
                    logger.Info("bbb");
                    logger.Warn("ccc");
                    logger.Error("ddd");
                    logger.Fatal("eee");
                }
                LogManager.Flush();
                LogManager.Configuration = null;

                Assert.IsFalse(File.Exists(Path.Combine(tempPath, "Trace.txt")));

                AssertFileContents(Path.Combine(tempPath, "Debug.txt"),
                    StringRepeat(250, "aaa " + threadID + "\n"), Encoding.UTF8);

                AssertFileContents(Path.Combine(tempPath, "Info.txt"),
                    StringRepeat(250, "bbb " + threadID + "\n"), Encoding.UTF8);

                AssertFileContents(Path.Combine(tempPath, "Warn.txt"),
                    StringRepeat(250, "ccc " + threadID + "\n"), Encoding.UTF8);

                AssertFileContents(Path.Combine(tempPath, "Error.txt"),
                    StringRepeat(250, "ddd " + threadID + "\n"), Encoding.UTF8);

                AssertFileContents(Path.Combine(tempPath, "Fatal.txt"),
                    StringRepeat(250, "eee " + threadID + "\n"), Encoding.UTF8);
            }
            finally
            {
                //if (File.Exists(tempFile))
                //    File.Delete(tempFile);
                LogManager.Configuration = null;
                if (Directory.Exists(tempPath))
                    Directory.Delete(tempPath, true);
            }
        }
예제 #11
0
        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();
        }
예제 #12
0
        private static void Start(string[] args)
        {
            //register object builder assembly
            string path = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "SpaceEngineers.ObjectBuilders.DLL");

            VRage.Plugins.MyPlugins.RegisterGameObjectBuildersAssemblyFile(path);

            MyObjectBuilderType.RegisterAssemblies( );
            MyObjectBuilderSerializer.RegisterAssembliesAndLoadSerializers( );

            //Setup error handling for unmanaged exceptions
            AppDomain.CurrentDomain.UnhandledException += AppDomain_UnhandledException;
            Application.ThreadException += Application_ThreadException;
            Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);

            //AppDomain.CurrentDomain.ClearEventInvocations("_unhandledException");

            BaseLog.Info("Starting SEServerExtender with {0} arguments: {1}", args.Length, string.Join("\r\n\t", args));

            CommandLineArgs extenderArgs = CommandLineArgs = new CommandLineArgs
            {
                ConsoleTitle = string.Empty,
                AutoStart    = false,
                WorldName    = string.Empty,
                InstanceName = string.Empty,
                NoGui        = false,
                NoConsole    = false,
                Debug        = false,
                GamePath     = new DirectoryInfo(PathManager.BasePath).Parent.FullName,
                //TODO: turn noWFC back to off by default whenever WCF gets fixed
                NoWcf          = true,
                Autosave       = 0,
                InstancePath   = string.Empty,
                CloseOnCrash   = false,
                RestartOnCrash = false,
                Args           = string.Join(" ", args.Select(x => string.Format("\"{0}\"", x)))
            };

            if (ConfigurationManager.AppSettings["WCFChatMaxMessageHistoryAge"] != null)
            {
                if (!int.TryParse(ConfigurationManager.AppSettings["WCFChatMaxMessageHistoryAge"], out _maxChatHistoryMessageAge))
                {
                    ConfigurationManager.AppSettings.Add("WCFChatMaxMessageHistoryAge", "3600");
                }
            }
            if (ConfigurationManager.AppSettings["WCFChatMaxMessageHistoryCount"] != null)
            {
                if (!int.TryParse(ConfigurationManager.AppSettings["WCFChatMaxMessageHistoryCount"], out _maxChatHistoryMessageCount))
                {
                    ConfigurationManager.AppSettings.Add("WCFChatMaxMessageHistoryCount", "100");
                }
            }

            bool logPathSet = false;

            //Process the args
            foreach (string arg in args)
            {
                string[] splitAtEquals = arg.Split('=');
                if (splitAtEquals.Length > 1)
                {
                    string argName  = splitAtEquals[0];
                    string argValue = splitAtEquals[1];

                    string lowerCaseArgument = argName.ToLower( );
                    if (lowerCaseArgument.Equals("instance"))
                    {
                        if (argValue[argValue.Length - 1] == '"')
                        {
                            argValue = argValue.Substring(1, argValue.Length - 2);
                        }
                        extenderArgs.InstanceName = argValue;

                        //Only let this override log path if the log path wasn't already explicitly set
                        if (!logPathSet)
                        {
                            FileTarget baseLogTarget = LogManager.Configuration.FindTargetByName("BaseLog") as FileTarget;
                            if (baseLogTarget != null)
                            {
                                baseLogTarget.FileName = baseLogTarget.FileName.Render(new LogEventInfo {
                                    TimeStamp = DateTime.Now
                                }).Replace("NoInstance", argValue);
                            }
                            FileTarget chatLogTarget = LogManager.Configuration.FindTargetByName("ChatLog") as FileTarget;
                            if (chatLogTarget != null)
                            {
                                chatLogTarget.FileName = chatLogTarget.FileName.Render(new LogEventInfo {
                                    TimeStamp = DateTime.Now
                                }).Replace("NoInstance", argValue);
                            }
                            FileTarget pluginLogTarget = LogManager.Configuration.FindTargetByName("PluginLog") as FileTarget;
                            if (pluginLogTarget != null)
                            {
                                pluginLogTarget.FileName = pluginLogTarget.FileName.Render(new LogEventInfo {
                                    TimeStamp = DateTime.Now
                                }).Replace("NoInstance", argValue);
                            }
                        }
                    }
                    else if (lowerCaseArgument.Equals("gamepath"))
                    {
                        if (argValue[argValue.Length - 1] == '"')
                        {
                            argValue = argValue.Substring(1, argValue.Length - 2);
                        }
                        extenderArgs.GamePath = argValue;
                    }
                    else if (lowerCaseArgument.Equals("autosave"))
                    {
                        if (!int.TryParse(argValue, out extenderArgs.Autosave))
                        {
                            BaseLog.Warn("Autosave parameter was not a valid integer.");
                        }
                    }
                    else if (lowerCaseArgument.Equals("path"))
                    {
                        if (argValue[argValue.Length - 1] == '"')
                        {
                            argValue = argValue.Substring(1, argValue.Length - 2);
                        }
                        extenderArgs.InstancePath = argValue;
                    }
                    else if (lowerCaseArgument.Equals("instancepath"))
                    {
                        if (argValue[argValue.Length - 1] == '"')
                        {
                            argValue = argValue.Substring(1, argValue.Length - 2);
                        }
                        extenderArgs.InstancePath = argValue;
                    }
                    else if (lowerCaseArgument.Equals("title"))
                    {
                        if (argValue[argValue.Length - 1] == '"')
                        {
                            argValue = argValue.Substring(1, argValue.Length - 2);
                        }
                        extenderArgs.ConsoleTitle = argValue;
                    }
                    else if (lowerCaseArgument == "logpath")
                    {
                        if (argValue[argValue.Length - 1] == '"')
                        {
                            argValue = argValue.Substring(1, argValue.Length - 2);
                        }

                        //This argument always prevails.
                        FileTarget baseLogTarget = LogManager.Configuration.FindTargetByName("BaseLog") as FileTarget;
                        if (baseLogTarget != null)
                        {
                            Layout l = new SimpleLayout(Path.Combine(argValue, "SEServerExtenderLog-${shortdate}.log"));
                            baseLogTarget.FileName = l.Render(new LogEventInfo {
                                TimeStamp = DateTime.Now
                            });
                            ApplicationLog.BaseLog = BaseLog;
                        }
                        FileTarget chatLogTarget = LogManager.Configuration.FindTargetByName("ChatLog") as FileTarget;
                        if (chatLogTarget != null)
                        {
                            Layout l = new SimpleLayout(Path.Combine(argValue, "ChatLog-${shortdate}.log"));
                            chatLogTarget.FileName = l.Render(new LogEventInfo {
                                TimeStamp = DateTime.Now
                            });
                            ApplicationLog.ChatLog = ChatLog;
                        }
                        FileTarget pluginLogTarget = LogManager.Configuration.FindTargetByName("PluginLog") as FileTarget;
                        if (pluginLogTarget != null)
                        {
                            Layout l = new SimpleLayout(Path.Combine(argValue, "PluginLog-${shortdate}.log"));
                            pluginLogTarget.FileName = l.Render(new LogEventInfo {
                                TimeStamp = DateTime.Now
                            });
                            logPathSet = true;
                            ApplicationLog.PluginLog = PluginLog;
                        }
                    }
                }
                else
                {
                    string lowerCaseArgument = arg.ToLower( );
                    if (lowerCaseArgument.Equals("autostart"))
                    {
                        extenderArgs.AutoStart = true;
                    }
                    else if (lowerCaseArgument.Equals("nogui"))
                    {
                        extenderArgs.NoGui = true;

                        //Implies autostart
                        //extenderArgs.AutoStart = true;
                    }
                    else if (lowerCaseArgument.Equals("noconsole"))
                    {
                        extenderArgs.NoConsole = true;

                        //Implies nogui and autostart
                        extenderArgs.NoGui     = true;
                        extenderArgs.AutoStart = true;
                    }
                    else if (lowerCaseArgument.Equals("debug"))
                    {
                        extenderArgs.Debug = true;
                    }
                    else if (lowerCaseArgument.Equals("nowcf"))
                    {
                        extenderArgs.NoWcf = true;
                    }
                    else if (lowerCaseArgument.Equals("wcfon"))
                    {
                        extenderArgs.NoWcf = false;
                    }
                    else if (lowerCaseArgument.Equals("closeoncrash"))
                    {
                        extenderArgs.CloseOnCrash = true;
                    }
                    else if (lowerCaseArgument.Equals("autosaveasync"))
                    {
                        extenderArgs.AutoSaveSync = false;
                    }
                    else if (lowerCaseArgument.Equals("autosavesync"))
                    {
                        extenderArgs.AutoSaveSync = true;
                    }
                    else if (lowerCaseArgument.Equals("restartoncrash"))
                    {
                        extenderArgs.RestartOnCrash = true;
                    }
                    //these things are legacy and don't work anyway

                    /*
                     *                  else if ( lowerCaseArgument.Equals( "wrr" ) )
                     *                  {
                     *                          extenderArgs.WorldRequestReplace = true;
                     *                  }
                     *                  else if ( lowerCaseArgument.Equals( "wrm" ) )
                     *                  {
                     *                          extenderArgs.WorldDataModify = true;
                     *                  }
                     * else if (lowerCaseArgument.Equals("wvm"))
                     * {
                     *  extenderArgs.WorldVoxelModify = true;
                     * }
                     */
                }
            }

            if (!Environment.UserInteractive)
            {
                extenderArgs.NoConsole = true;
                extenderArgs.NoGui     = true;
                extenderArgs.AutoStart = true;
            }

            if (extenderArgs.Debug)
            {
                ExtenderOptions.IsDebugging = true;
            }

            try
            {
                bool unitTestResult = BasicUnitTestManager.Instance.Run( );
                if (!unitTestResult)
                {
                    ExtenderOptions.IsInSafeMode = true;
                }

                Server = Server.Instance;
                Server.CommandLineArgs = extenderArgs;
                Server.IsWCFEnabled    = !extenderArgs.NoWcf;
                Server.Init( );

                ChatManager.ChatCommand guiCommand = new ChatManager.ChatCommand("gui", ChatCommand_GUI, false);
                ChatManager.Instance.RegisterChatCommand(guiCommand);

                if (!CommandLineArgs.NoConsole)
                {
                    if (string.IsNullOrEmpty(extenderArgs.ConsoleTitle) || string.IsNullOrWhiteSpace(extenderArgs.ConsoleTitle))
                    {
                        Console.Title = "SESE";
                    }
                    else
                    {
                        Console.Title = extenderArgs.ConsoleTitle;
                    }
                }

                if (extenderArgs.AutoStart)
                {
                    Server.StartServer( );
                }

                if (!extenderArgs.NoWcf)
                {
                    string uriString = string.Format("{0}{1}", ConfigurationManager.AppSettings["WCFServerServiceBaseAddress"], CommandLineArgs.InstanceName);
                    BaseLog.Info("Opening up WCF service listener at {0}", uriString);
                    ServerServiceHost = new ServiceHost(typeof(ServerService.ServerService), new Uri(uriString, UriKind.Absolute));
                    ServerServiceHost.Open( );
                    ChatManager.Instance.ChatMessage += ChatManager_ChatMessage;
                }

                if (!extenderArgs.NoGui)
                {
                    Thread uiThread = new Thread(StartGui);
                    uiThread.SetApartmentState(ApartmentState.STA);
                    uiThread.Start( );
                }
                else if (Environment.UserInteractive)
                {
                    Console.ReadLine( );
                }
            }
            catch (AutoException eEx)
            {
                if (!extenderArgs.NoConsole)
                {
                    BaseLog.Info("AutoException - {0}\n\r{1}", eEx.AdditionnalInfo, eEx.GetDebugString( ));
                }
                if (!extenderArgs.NoGui)
                {
                    MessageBox.Show(string.Format("{0}\n\r{1}", eEx.AdditionnalInfo, eEx.GetDebugString( )), @"SEServerExtender", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }

                if (extenderArgs.NoConsole && extenderArgs.NoGui)
                {
                    throw eEx.GetBaseException( );
                }
            }
            catch (TargetInvocationException ex)
            {
                if (!extenderArgs.NoConsole)
                {
                    BaseLog.Info("TargetInvocationException - {0}\n\r{1}", ex, ex.InnerException);
                }
                if (!extenderArgs.NoGui)
                {
                    MessageBox.Show(string.Format("{0}\n\r{1}", ex, ex.InnerException), @"SEServerExtender", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }

                if (extenderArgs.NoConsole && extenderArgs.NoGui)
                {
                    throw;
                }
            }
            catch (Exception ex)
            {
                if (!extenderArgs.NoConsole)
                {
                    BaseLog.Info(ex, "Exception - {0}", ex);
                }
                if (!extenderArgs.NoGui)
                {
                    MessageBox.Show(ex.ToString( ), @"SEServerExtender", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }

                if (extenderArgs.NoConsole && extenderArgs.NoGui)
                {
                    throw;
                }
            }
        }
        /// <summary>
        /// Initializes application logging.
        /// </summary>
        /// <param name="path">The path.</param>
        /// <param name="remoteLoggingEnabled">if set to <c>true</c> [remote logging enabled].</param>
        /// <param name="remoteLogIpAddress">The remote log ip address.</param>
        /// <returns>ILogger.</returns>
        public static ILogger InitializeLogging(string path, bool remoteLoggingEnabled, string remoteLogIpAddress)
        {
            var filePath = Path.Combine(path, $"{DateTime.Today.Month}-{DateTime.Today.Day}-{DateTime.Today.Year}.log");
            var jsonFilePath = Path.Combine(path, $"{DateTime.Today.Month}-{DateTime.Today.Day}-{DateTime.Today.Year}.json");
            var config = new LoggingConfiguration();
            var jsonLayout = new JsonLayout
            {
                Attributes =
                {
                    new JsonAttribute("date", "${date:format=MM-dd-yyyy}"),
                    new JsonAttribute("time", "${time}"),
                    new JsonAttribute("friendlytime", @"${date:format=HH\:mm\:ss}"),
                    new JsonAttribute("hour", "${date:format=HH}"),
                    new JsonAttribute("minute", "${date:format=mm}"),
                    new JsonAttribute("ticks", "${ticks}"),
                    new JsonAttribute("logger", "${logger}"),
                    new JsonAttribute("level", "${level}"),
                    new JsonAttribute("appDomain", "${appdomain}"),
                    new JsonAttribute("version", "${assembly-version}"),
                    new JsonAttribute("ident", "${identity}"),
                    new JsonAttribute("winIdent", "${windows-identity}"),
                    new JsonAttribute("machine", "${machinename}"),
                    new JsonAttribute("message", "${message}"),
                    new JsonAttribute("exceptionData", new JsonLayout
                    {
                        Attributes =
                        {
                            new JsonAttribute("exception", "${exception}"),
                            new JsonAttribute("stack", "${stacktrace}"),
                            new JsonAttribute("callSite", "${callsite}"),
                            new JsonAttribute("callSite-Line", "${callsite-linenumber}")
                        },
                        RenderEmptyObject = false
                    })
                }
            };
            if (remoteLoggingEnabled)
            {
                var viewerTarget = new NLogViewerTarget
                {
                    Encoding = Encoding.UTF8,
                    IncludeCallSite = true,
                    NewLine = true,
                    OnOverflow = NetworkTargetOverflowAction.Split,
                    MaxConnections = 0,
                    MaxMessageSize = 65565,
                    ConnectionCacheSize = 25,
                    KeepConnection = true,
                    IncludeSourceInfo = true,
                    IncludeMdc = true,
                    IncludeNLogData = true,
                    IncludeNdc = true,
                    Address = $"udp://{remoteLogIpAddress}",
                    Layout = jsonLayout
                };
                config.AddTarget("RemoteViewer", viewerTarget);
                config.LoggingRules.Add(new LoggingRule("*", LogLevel.Debug, viewerTarget));
            }
            var fileTarget = new FileTarget
            {
                FileName = filePath,
                Layout = @"${date:format=HH\:mm\:ss} ${logger} ${message}"
            };
            config.AddTarget("LogFile", fileTarget);
            config.LoggingRules.Add(new LoggingRule("*", LogLevel.Debug, fileTarget));

            var jsonTarget = new FileTarget
            {
                FileName = jsonFilePath,
                Layout = jsonLayout
            };
            config.AddTarget("JsonLogFile", jsonTarget);
            config.LoggingRules.Add(new LoggingRule("*", LogLevel.Debug, jsonTarget));

            LogManager.Configuration = config;
            _logger = LogManager.GetCurrentClassLogger();
            return _logger;
        }
예제 #14
0
        public static void Configure(Settings settings, bool logToConsole)
        {
            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));

            if (logToConsole)
            {
                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);
        }
예제 #15
0
        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. (env: COVENANT_USERNAME)",
                CommandOptionType.SingleValue
                );
            var PasswordOption = app.Option(
                "-p | --password <PASSWORD>",
                "The Password to login to the Covenant API. (env: COVENANT_PASSWORD)",
                CommandOptionType.SingleValue
                );
            var ComputerNameOption = app.Option(
                "-c | --computername <COMPUTERNAME>",
                "The ComputerName (IPAddress or Hostname) to bind the Covenant API to. (env: COVENANT_COMPUTER_NAME)",
                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.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";
                }

                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 = 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>();
                    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.");
                    }
                    host.Run();
                }
                catch (Exception ex)
                {
                    logger.Error(ex, "Covenant stopped due to exception");
                    throw;
                }
                finally
                {
                    NLog.LogManager.Shutdown();
                }
                return(0);
            });
            app.Execute(args);
        }
예제 #16
0
        static void Main(string[] args)
        {
            Console.WriteLine($"GC: " + System.Runtime.GCSettings.LatencyMode);
            System.Runtime.GCSettings.LatencyMode = System.Runtime.GCLatencyMode.SustainedLowLatency;

            Options options = null;

            Parser.Default
            .ParseArguments <Options>(args)
            .WithParsed <Options>((opts) => options = opts)
            /*.WithNotParsed<Options>((errs) => HandleParseError(errs))*/;

            if (args.Length < 1)
            {
                //error
            }

            //var usage = "%prog [options] <config file>";
            //var opts = optparse.OptionParser(usage);
            //opts.add_option("-i", "--debuginput", dest: "debuginput", help: "read commands from file instead of from tty port");
            //opts.add_option("-I", "--input-tty", dest: "inputtty", @default: "/tmp/printer", help: "input tty name (default is /tmp/printer)");
            //opts.add_option("-l", "--logfile", dest: "logfile", help: "write log to file instead of stderr");
            //opts.add_option("-v", action: "store_true", dest: "verbose", help: "enable debug messages");
            //opts.add_option("-o", "--debugoutput", dest: "debugoutput", help: "write output to file instead of to serial port");
            //opts.add_option("-d", "--dictionary", dest: "dictionary", type: "string", action: "callback", callback: arg_dictionary, help: "file to read for mcu protocol dictionary");
            //var _tup_1 = opts.parse_args();
            //var options = _tup_1.Item1;
            //var args = _tup_1.Item2;
            //if (args.Length != 1)
            //{
            //	opts.error("Incorrect number of arguments");
            //}
            var start_args = new Dictionary <string, object> {
                { "config_file", args[0] },
                { "start_reason", "startup" }
            };
            Stream input_fd   = null;
            var    debuglevel = LogLevel.Info;
            object bglogger   = null;

            if (options.Verbose)
            {
                debuglevel = LogLevel.Debug;
            }
            if (options.Debuginput != null)
            {
                start_args["debuginput"] = options.Debuginput;
                var debuginput = File.OpenRead(options.Debuginput);
                input_fd = debuginput;
            }
            else
            {
                //input_fd = util.create_pty(options.Inputtty);
            }
            if (options.Debugoutput != null)
            {
                start_args["debugoutput"] = options.Debugoutput;
                //start_args.update(options.Dictionary);
            }
            //if (options.Logfile != null)
            //{
            //	bglogger = queuelogger.setup_bg_logging(options.Logfile, debuglevel);
            //}

            var config  = new LoggingConfiguration();
            var logfile = new FileTarget("logfile")
            {
                FileName = "file.txt"
            };
            var logconsole = new ConsoleTarget("logconsole");

            config.AddRule(LogLevel.Debug, LogLevel.Fatal, logconsole);
            config.AddRule(LogLevel.Debug, LogLevel.Fatal, logfile);

            LogManager.Configuration = config;


            var logging = LogManager.GetCurrentClassLogger();

            logging.Info("Starting Klippy...");
            start_args["software_version"] = 1.0;            //util.get_git_version();
            if (bglogger != null)
            {
                //var versions = string.Join("\n", new List<string> {
                //	 String.Format("Args: %s", sys.argv),
                //	 String.Format("Git version: %s", repr(start_args["software_version"])),
                //	 String.Format("CPU: %s", util.get_cpu_info()),
                //	 String.Format("Python: %s", repr(sys.version))
                //});
                //logging.Info(versions);
            }
            // Start Printer() class
            string res;

            while (true)
            {
                if (bglogger != null)
                {
                    //bglogger.clear_rollover_info();
                    //bglogger.set_rollover_info("versions", versions);
                }
                var printer = new Machine(input_fd, null /*bglogger*/, start_args);
                res = printer.run();
                if ("exit" == res || "error_exit" == res)
                {
                    break;
                }
                Thread.Sleep(1000);
                logging.Info("Restarting printer");
                start_args["start_reason"] = res;
            }
            if (bglogger != null)
            {
                //bglogger.stop();
            }
            if (res == "error_exit")
            {
                Environment.ExitCode = -1;
            }
        }
예제 #17
0
        private static ILogger GetLog()
        {
            var config     = new NLog.Config.LoggingConfiguration();
            var fileTarget = new FileTarget("logfile")
            {
                FileName             = CurrentLogPath,
                ArchiveEvery         = FileArchivePeriod.Day,
                ArchiveNumbering     = ArchiveNumberingMode.DateAndSequence,
                KeepFileOpen         = true,
                ConcurrentWrites     = false,
                AutoFlush            = false,
                OpenFileFlushTimeout = 1,
                Layout = "${longdate} ${sequenceid:padding=6} ${level:uppercase=true:padding=-5} ${message} ${onexception:" +
                         "${newline}${exception:format=ToString}" +
                         ":when=not contains('${exception:format=ShortType}','TaskCanceledException')}",
            };
            var asyncFileTarget = new AsyncTargetWrapper(fileTarget)
            {
                TimeToSleepBetweenBatches = 0,
                OverflowAction            = AsyncTargetWrapperOverflowAction.Block,
                BatchSize = 500,
            };
            var consoleTarget = new ColoredConsoleTarget("logconsole")
            {
                Layout = "${longdate} ${level:uppercase=true:padding=-5} ${message} ${onexception:" +
                         "${newline}${exception:format=Message}" +
                         ":when=not contains('${exception:format=ShortType}','TaskCanceledException')}",
            };
            var watchdogTarget = new MethodCallTarget("watchdog")
            {
                ClassName  = typeof(Watchdog).AssemblyQualifiedName,
                MethodName = nameof(Watchdog.OnLogHandler),
            };

            watchdogTarget.Parameters.AddRange(new[]
            {
                new MethodCallParameter("${level}"),
                new MethodCallParameter("${message}"),
            });
#if DEBUG
            config.AddRule(LogLevel.Trace, LogLevel.Fatal, consoleTarget, "default"); // only echo messages from default logger to the console
#else
            config.AddRule(LogLevel.Info, LogLevel.Fatal, consoleTarget, "default");
#endif
            config.AddRule(LogLevel.Debug, LogLevel.Fatal, asyncFileTarget);
            config.AddRule(LogLevel.Info, LogLevel.Fatal, watchdogTarget);

            var ignoreFilter1 = new ConditionBasedFilter {
                Condition = "contains('${message}','TaskCanceledException')", Action = FilterResult.Ignore,
            };
            var ignoreFilter2 = new ConditionBasedFilter {
                Condition = "contains('${message}','One or more pre-execution checks failed')", Action = FilterResult.Ignore,
            };
            foreach (var rule in config.LoggingRules)
            {
                rule.Filters.Add(ignoreFilter1);
                rule.Filters.Add(ignoreFilter2);
            }
            LogManager.Configuration = config;
            return(LogManager.GetLogger("default"));
        }
예제 #18
0
파일: TargetTests.cs 프로젝트: zsybupt/NLog
        public void TargetContructorWithNameTest()
        {
            var    targetTypes      = typeof(Target).Assembly.GetTypes().Where(t => !t.IsAbstract && t.IsSubclassOf(typeof(Target))).ToList();
            int    neededCheckCount = targetTypes.Count;
            int    checkCount       = 0;
            Target fileTarget       = new FileTarget();
            Target memoryTarget     = new MemoryTarget();

            foreach (Type targetType in targetTypes)
            {
                string lastPropertyName = null;

                try
                {
                    // Check if the Target can be created using a default constructor
                    var name = targetType + "_name";

                    var isWrapped  = targetType.IsSubclassOf(typeof(WrapperTargetBase));
                    var isCompound = targetType.IsSubclassOf(typeof(CompoundTargetBase));

                    if (isWrapped)
                    {
                        neededCheckCount++;

                        var args = new List <object> {
                            fileTarget
                        };

                        //default ctor
                        var defaultConstructedTarget = (WrapperTargetBase)Activator.CreateInstance(targetType);
                        defaultConstructedTarget.Name          = name;
                        defaultConstructedTarget.WrappedTarget = fileTarget;

                        //specials cases
                        if (targetType == typeof(FilteringTargetWrapper))
                        {
                            ConditionLoggerNameExpression cond = null;
                            args.Add(cond);
                            var target = (FilteringTargetWrapper)defaultConstructedTarget;
                            target.Condition = cond;
                        }
                        else if (targetType == typeof(RepeatingTargetWrapper))
                        {
                            var repeatCount = 5;
                            args.Add(repeatCount);
                            var target = (RepeatingTargetWrapper)defaultConstructedTarget;
                            target.RepeatCount = repeatCount;
                        }
                        else if (targetType == typeof(RetryingTargetWrapper))
                        {
                            var retryCount             = 10;
                            var retryDelayMilliseconds = 100;
                            args.Add(retryCount);
                            args.Add(retryDelayMilliseconds);
                            var target = (RetryingTargetWrapper)defaultConstructedTarget;
                            target.RetryCount             = retryCount;
                            target.RetryDelayMilliseconds = retryDelayMilliseconds;
                        }

                        //ctor: target
                        var targetConstructedTarget = (WrapperTargetBase)Activator.CreateInstance(targetType, args.ToArray());
                        targetConstructedTarget.Name = name;

                        args.Insert(0, name);

                        //ctor: target+name
                        var namedConstructedTarget = (WrapperTargetBase)Activator.CreateInstance(targetType, args.ToArray());

                        CheckEquals(targetType, targetConstructedTarget, namedConstructedTarget, ref lastPropertyName, ref checkCount);

                        CheckEquals(targetType, defaultConstructedTarget, namedConstructedTarget, ref lastPropertyName, ref checkCount);
                    }
                    else if (isCompound)
                    {
                        neededCheckCount++;

                        //multiple targets
                        var args = new List <object> {
                            fileTarget, memoryTarget
                        };

                        //specials cases


                        //default ctor
                        var defaultConstructedTarget = (CompoundTargetBase)Activator.CreateInstance(targetType);
                        defaultConstructedTarget.Name = name;
                        defaultConstructedTarget.Targets.Add(fileTarget);
                        defaultConstructedTarget.Targets.Add(memoryTarget);

                        //ctor: target
                        var targetConstructedTarget = (CompoundTargetBase)Activator.CreateInstance(targetType, args.ToArray());
                        targetConstructedTarget.Name = name;

                        args.Insert(0, name);

                        //ctor: target+name
                        var namedConstructedTarget = (CompoundTargetBase)Activator.CreateInstance(targetType, args.ToArray());

                        CheckEquals(targetType, targetConstructedTarget, namedConstructedTarget, ref lastPropertyName, ref checkCount);

                        CheckEquals(targetType, defaultConstructedTarget, namedConstructedTarget, ref lastPropertyName, ref checkCount);
                    }
                    else
                    {
                        //default ctor
                        var targetConstructedTarget = (Target)Activator.CreateInstance(targetType);
                        targetConstructedTarget.Name = name;

                        // ctor: name
                        var namedConstructedTarget = (Target)Activator.CreateInstance(targetType, name);

                        CheckEquals(targetType, targetConstructedTarget, namedConstructedTarget, ref lastPropertyName, ref checkCount);
                    }
                }
                catch (Exception ex)
                {
                    var    constructionFailed = true;
                    string failureMessage     =
                        $"Error testing constructors for '{targetType}.{lastPropertyName}`\n{ex.ToString()}";
                    Assert.False(constructionFailed, failureMessage);
                }
            }
            Assert.Equal(neededCheckCount, checkCount);
        }
예제 #19
0
        public void Init(string DirectoryPath, string LogName, Encoding encoding, LogLevel loglevel, long MaximumFileSize = 1024 * 1024 * 20)
        {
            isRunning = true;

            // Step 1. Create configuration object
            var config = new LoggingConfiguration();

            // Step 2. Create targets and add them to the configuration
            var fileTarget = new FileTarget();

            config.AddTarget(LogName, fileTarget);

            // Step 3. Set target properties
            fileTarget.Layout           = "${message}";
            fileTarget.FileName         = DirectoryPath + "/" + LogName + ".log";
            fileTarget.ArchiveAboveSize = MaximumFileSize;
            fileTarget.ArchiveEvery     = FileArchivePeriod.Day;
            fileTarget.ArchiveFileName  = DirectoryPath + "/${shortdate}/" + LogName + "_{#}.log";
            fileTarget.ArchiveNumbering = ArchiveNumberingMode.Sequence;
            fileTarget.MaxArchiveFiles  = 1000;
            fileTarget.Encoding         = encoding;

            NLog.LogLevel lv = NLog.LogLevel.Debug;
            if (loglevel == LogLevel.Debug)
            {
                lv = NLog.LogLevel.Debug;
            }
            else if (loglevel == LogLevel.Error)
            {
                lv = NLog.LogLevel.Error;
            }
            else if (loglevel == LogLevel.Fatal)
            {
                lv = NLog.LogLevel.Fatal;
            }
            else if (loglevel == LogLevel.Info)
            {
                lv = NLog.LogLevel.Info;
            }
            else if (loglevel == LogLevel.Off)
            {
                lv = NLog.LogLevel.Off;
            }
            else if (loglevel == LogLevel.Trace)
            {
                lv = NLog.LogLevel.Trace;
            }
            else if (loglevel == LogLevel.Warn)
            {
                lv = NLog.LogLevel.Warn;
            }

            // Step 4. Define rules
            var rule = new LoggingRule(LogName, lv, fileTarget);

            config.LoggingRules.Add(rule);

            // Step 5. Activate the configuration
            LogManager.Configuration = config;
            logger = LogManager.GetLogger(LogName);
            writethread.Add(Task.Factory.StartNew(() => WriteToFile(), TaskCreationOptions.LongRunning));

            TaskScheduler.UnobservedTaskException += (sender, args) =>
            {
                foreach (var ex in args.Exception.InnerExceptions)
                {
                    logger.Fatal(ex.ToString());
                }
                args.SetObserved();
            };

            isInitialized = true;

            logger.Info(msgWithTime(" Program Started!"));
        }
예제 #20
0
        /* Now we write our main program, making reference to the functions above where necessary. */
        static void Main(string[] args)
        {
            /* Set up log functionality */
            var config = new LoggingConfiguration();
            var target = new FileTarget {
                FileName = @"C:\Work\Logs\SupportBank.log", Layout = @"${longdate} ${level} - ${logger}: ${message}"
            };

            config.AddTarget("File Logger", target);
            config.LoggingRules.Add(new LoggingRule("*", LogLevel.Info, target));
            LogManager.Configuration = config;

            ILogger logger = LogManager.GetCurrentClassLogger();

            logger.Info("And so we begin!");



            /* This section reads all the data we'll be using */

            int entries = 0;

            Debt[] total_debts = new Debt[0];
            total_debts = Import_csv(@"C:\Work\Training\SupportBank\Transactions2014.csv", entries, total_debts);
            entries     = total_debts.Length;

            logger.Info("Finished reading 2014 entries.");

            total_debts = Import_csv(@"C:\Work\Training\SupportBank\DodgyTransactions2015.csv", entries, total_debts);
            entries     = total_debts.Length;

            logger.Info("Finished reading dodgy 2015 entries.");
            logger.Info("We've read the CSV files");


            /* Now we read the Json file. We use the function above to turn it into a string, deserialise it, convert it to the debt format, and add to the list */

            total_debts = Import_json(@"C:\Work\Training\SupportBank\Transactions2013.json", entries, total_debts);
            entries     = total_debts.Length;

            logger.Info("We've read the Json file");


            /* Now we read the xml file */
            string json_of_xml = import_xml_to_json(@"C:\Users\RTL\Documents\Transactions2012.xml");

            total_debts = Import_json_string(json_of_xml, entries, total_debts);
            entries     = total_debts.Length;

            /* Now we get a list of all the different people involved */

            List <string> people = new List <string>();

            for (int i = 0; i < entries; i++)  // Look at each transaction in turn
            {
                Debt transaction = total_debts[i];
                try
                {
                    if (transaction.From != "")
                    {
                        people.Add(transaction.From);                       // Add whoever owes to the list
                    }
                    if (transaction.To != "")
                    {
                        people.Add(transaction.To);                       // Add whoever is owed to the list
                    }
                }
                catch
                {
                    //
                }
            }
            people = people.Distinct().ToList();        // Remove any duplicates in the list of people.



            /* That finishes out compilation and sorting of the data. Here we start the actual process of taking user commands, and
             * churning out whatever data they have requested */

            bool running = true;

            while (running == true)
            {
                Console.WriteLine("Enter a command (List All, List [Specific person], Import File or Exit): ");
                string input = Console.ReadLine(); // Get user input for the command"

                var case_string = "";

                if (input == "List All" || input == "Exit" || input == "Import File")
                {
                    case_string = input;
                }
                else if (input.StartsWith("List"))
                {
                    case_string = "List Person";
                }

                switch (case_string)
                {
                case ("List All"):
                {
                    logger.Info("User wants a list of all the data!");
                    List_all(people, entries, total_debts);            // If they want List All, run that function
                    break;
                }

                case ("Exit"):
                {
                    logger.Info("User wants to leave me. What have I done??");
                    running = false;                                   // If they input Exit, end the program
                    break;
                }

                case ("Import File"):                  // Add functionality for the user to specify a file to import.
                {
                    logger.Info("User wants to import another file. Eurgh!");
                    Console.WriteLine("Please enter the file that you would like to import");
                    string file_name = Console.ReadLine();         // Get user input for the file to import.


                    try
                    {
                        string file_type = file_name.Substring(file_name.Length - 4, 4);


                        /* Now we deal with the different cases of different filetypes */

                        switch (file_type)
                        {
                        /* At this point it makes sense to create new functions to deal with the different cases */

                        case ".csv":
                        {
                            logger.Info("User wants to import a CSV. We all love commas!");
                            total_debts = Import_csv(file_name, entries, total_debts);
                            entries     = total_debts.Length;

                            people = new List <string>();                   // Update the list of people
                            for (int i = 0; i < entries; i++)               // Look at each transaction in turn
                            {
                                Debt transaction = total_debts[i];
                                try
                                {
                                    if (transaction.From != "")
                                    {
                                        people.Add(transaction.From);                                       // Add whoever owes to the list
                                    }
                                    if (transaction.To != "")
                                    {
                                        people.Add(transaction.To);                                       // Add whoever is owed to the list
                                    }
                                }
                                catch
                                {
                                    //
                                }
                            }
                            people = people.Distinct().ToList();                    // Remove any duplicates in the list of people.
                            break;
                        }

                        case "json":
                        {
                            logger.Info("User wants to import a json???? WHYYYYYY");
                            total_debts = Import_json(file_name, entries, total_debts);
                            entries     = total_debts.Length;

                            people = new List <string>();                   // Update the list of people
                            for (int i = 0; i < entries; i++)               // Look at each transaction in turn
                            {
                                Debt transaction = total_debts[i];
                                try
                                {
                                    if (transaction.From != "")
                                    {
                                        people.Add(transaction.From);                                       // Add whoever owes to the list
                                    }
                                    if (transaction.To != "")
                                    {
                                        people.Add(transaction.To);                                       // Add whoever is owed to the list
                                    }
                                }
                                catch
                                {
                                    //
                                }
                            }
                            people = people.Distinct().ToList();                    // Remove any duplicates in the list of people.
                            break;
                        }

                        default:
                            Console.WriteLine("Invalid file name! Please try again.");
                            break;
                        }
                    }

                    /* If the filename they inputted doesn't end in a sensible way, or is not long enough, we reach this part */
                    catch
                    {
                        Console.WriteLine("Invalid file name! Please try again.");
                    }
                    break;
                }

                case ("List Person"):
                {
                    string specific_person = input.Substring(5);
                    if (people.Contains(specific_person))
                    {
                        logger.Info("User wants to know the specific transactions of " + specific_person + ". Curious...");
                        List_person(specific_person, people, entries, total_debts);
                    }
                    else
                    {
                        logger.Info("User wants to find the transactions of " + specific_person + " but they don't exist :(");
                        Console.WriteLine("Error - cannot find this person. Please try again.");
                    }
                    break;
                }

                default:
                {
                    logger.Info("User can't even do a valid input command. They tried to hit me with {0}. User? More like loser!", input);
                    Console.WriteLine("Invalid input. Please enter a valid command.");
                    break;
                }
                }
            }
        }
예제 #21
0
        public void SequentialArchiveTest1()
        {
            var tempPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());
            var tempFile = Path.Combine(tempPath, "file.txt");

            try
            {
                var ft = new FileTarget
                {
                    FileName         = tempFile,
                    ArchiveFileName  = Path.Combine(tempPath, "archive/{####}.txt"),
                    ArchiveAboveSize = 1000,
                    LineEnding       = LineEndingMode.LF,
                    Layout           = "${message}",
                    MaxArchiveFiles  = 3,
                    ArchiveNumbering = ArchiveNumberingMode.Sequence
                };

                SimpleConfigurator.ConfigureForTargetLogging(ft, LogLevel.Debug);

                // we emit 5 * 250 *(3 x aaa + \n) bytes
                // so that we should get a full file + 3 archives
                for (var i = 0; i < 250; ++i)
                {
                    logger.Debug("aaa");
                }
                for (var i = 0; i < 250; ++i)
                {
                    logger.Debug("bbb");
                }
                for (var i = 0; i < 250; ++i)
                {
                    logger.Debug("ccc");
                }
                for (var i = 0; i < 250; ++i)
                {
                    logger.Debug("ddd");
                }
                for (var i = 0; i < 250; ++i)
                {
                    logger.Debug("eee");
                }

                LogManager.Configuration = null;

                AssertFileContents(tempFile,
                                   StringRepeat(250, "eee\n"),
                                   Encoding.UTF8);

                AssertFileContents(
                    Path.Combine(tempPath, "archive/0001.txt"),
                    StringRepeat(250, "bbb\n"),
                    Encoding.UTF8);

                AssertFileContents(
                    Path.Combine(tempPath, "archive/0002.txt"),
                    StringRepeat(250, "ccc\n"),
                    Encoding.UTF8);

                AssertFileContents(
                    Path.Combine(tempPath, "archive/0003.txt"),
                    StringRepeat(250, "ddd\n"),
                    Encoding.UTF8);

                Assert.IsTrue(!File.Exists(Path.Combine(tempPath, "archive/0000.txt")));
                Assert.IsTrue(!File.Exists(Path.Combine(tempPath, "archive/0004.txt")));
            }
            finally
            {
                LogManager.Configuration = null;
                if (File.Exists(tempFile))
                {
                    File.Delete(tempFile);
                }
                if (Directory.Exists(tempPath))
                {
                    Directory.Delete(tempPath, true);
                }
            }
        }
예제 #22
0
        public void RollingArchiveTest1()
        {
            // create the file in a not-existent
            // directory which forces creation
            string tempPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());
            string tempFile = Path.Combine(tempPath, "file.txt");
            try
            {
                FileTarget ft = new FileTarget();
                ft.FileName = tempFile;
                ft.ArchiveFileName = Path.Combine(tempPath, "archive/{####}.txt");
                ft.ArchiveAboveSize = 1000;
                ft.LineEnding = LineEndingMode.LF;
                ft.ArchiveNumbering = ArchiveNumberingMode.Rolling;
                ft.Layout = "${message}";
                ft.MaxArchiveFiles = 3;

                SimpleConfigurator.ConfigureForTargetLogging(ft, LogLevel.Debug);

                // we emit 5 * 250 * (3 x aaa + \n) bytes
                // so that we should get a full file + 3 archives
                for (int i = 0; i < 250; ++i)
                {
                    logger.Debug("aaa");
                }
                for (int i = 0; i < 250; ++i)
                {
                    logger.Debug("bbb");
                }
                for (int i = 0; i < 250; ++i)
                {
                    logger.Debug("ccc");
                }
                for (int i = 0; i < 250; ++i)
                {
                    logger.Debug("ddd");
                }
                for (int i = 0; i < 250; ++i)
                {
                    logger.Debug("eee");
                }

                LogManager.Configuration = null;

                AssertFileContents(tempFile,
                    StringRepeat(250, "eee\n"),
                    Encoding.UTF8);

                AssertFileContents(
                    Path.Combine(tempPath, "archive/0000.txt"),
                    StringRepeat(250, "ddd\n"),
                    Encoding.UTF8);

                AssertFileContents(
                    Path.Combine(tempPath, "archive/0001.txt"),
                    StringRepeat(250, "ccc\n"),
                    Encoding.UTF8);

                AssertFileContents(
                    Path.Combine(tempPath, "archive/0002.txt"),
                    StringRepeat(250, "bbb\n"),
                    Encoding.UTF8);

                Assert.IsTrue(!File.Exists(Path.Combine(tempPath, "archive/0003.txt")));
            }
            finally
            {
                LogManager.Configuration = null;
                if (File.Exists(tempFile))
                    File.Delete(tempFile);
                if (Directory.Exists(tempPath))
                    Directory.Delete(tempPath, true);
            }
        }
예제 #23
0
파일: App.cs 프로젝트: Devwarlt/loe-core
        private static void Main()
        {
#if DEBUG
            AllocConsole();

            var defaultStdout = new IntPtr(7);

            if (GetStdHandle(StdOutputHandle) != defaultStdout)
            {
                SetStdHandle(StdOutputHandle, defaultStdout);
            }

            Console.SetOut(new StreamWriter(Console.OpenStandardOutput())
            {
                AutoFlush = true
            });
            Console.Title = $"{Name} - Build: {Version}";

            var config       = new LoggingConfiguration();
            var developerLog = new ColoredConsoleTarget()
            {
                Name   = "developer",
                Layout = @"[${date:format=HH\:mm\:ss}] [${level}] ${message} ${exception}"
            };
            var developerFile = new FileTarget()
            {
                Name     = "developer-file",
                FileName = "../../../logs/assetsmanager/Build ${assembly-version}/${level}/${date:format=dd-MM-yyyy HH.mm.ss}.txt",
                Layout   = @"[${date:format=HH\:mm\:ss}] [${level}] ${message} ${exception}"
            };
            config.AddTarget(developerLog);
            config.AddTarget(developerFile);
            config.AddRule(LogLevel.Info, LogLevel.Fatal, developerFile);
            config.AddRuleForAllLevels(developerLog);

            LogManager.Configuration = config;

            RollbarLocator.RollbarInstance.Configure(new RollbarConfig(RollbarId));
#endif
            Info("Game Xml Manager is loading...");

            try
            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new Manager());
            }
            catch (Exception e)
            {
                Info("An error occurred!");

                Error(e);

                Thread.Sleep(100);

                Warn("Press 'ESC' to close...");

#if DEBUG
                while (Console.ReadKey(true).Key != ConsoleKey.Escape)
                {
                    ;
                }
#endif
                Environment.Exit(0);
            }
        }
예제 #24
0
        public void DeleteFileOnStartTest()
        {
            string tempFile = Path.GetTempFileName();
            try
            {
                FileTarget ft = new FileTarget();
                ft.FileName = SimpleLayout.Escape(tempFile);
                ft.LineEnding = LineEndingMode.LF;
                ft.Layout = "${level} ${message}";

                SimpleConfigurator.ConfigureForTargetLogging(ft, LogLevel.Debug);

                logger.Debug("aaa");
                logger.Info("bbb");
                logger.Warn("ccc");

                LogManager.Configuration = null;

                AssertFileContents(tempFile, "Debug aaa\nInfo bbb\nWarn ccc\n", Encoding.UTF8);

                // configure again, without
                // DeleteOldFileOnStartup

                ft = new FileTarget();
                ft.FileName = SimpleLayout.Escape(tempFile);
                ft.LineEnding = LineEndingMode.LF;
                ft.Layout = "${level} ${message}";

                SimpleConfigurator.ConfigureForTargetLogging(ft, LogLevel.Debug);

                logger.Debug("aaa");
                logger.Info("bbb");
                logger.Warn("ccc");

                LogManager.Configuration = null;
                AssertFileContents(tempFile, "Debug aaa\nInfo bbb\nWarn ccc\nDebug aaa\nInfo bbb\nWarn ccc\n", Encoding.UTF8);

                // configure again, this time with
                // DeleteOldFileOnStartup

                ft = new FileTarget();
                ft.FileName = SimpleLayout.Escape(tempFile);
                ft.LineEnding = LineEndingMode.LF;
                ft.Layout = "${level} ${message}";
                ft.DeleteOldFileOnStartup = true;

                SimpleConfigurator.ConfigureForTargetLogging(ft, LogLevel.Debug);
                logger.Debug("aaa");
                logger.Info("bbb");
                logger.Warn("ccc");

                LogManager.Configuration = null;
                AssertFileContents(tempFile, "Debug aaa\nInfo bbb\nWarn ccc\n", Encoding.UTF8);
            }
            finally
            {
                LogManager.Configuration = null;
                if (File.Exists(tempFile))
                    File.Delete(tempFile);
            }
        }
예제 #25
0
        /// <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.ApplicationNameFormatted,
                //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.ApplicationNameFormatted);

            // =================================

            // All messages from Trace to Warn levels write to the general file
            FileTarget fileTarget_General = new FileTarget()
            {
                Name             = Constants.ApplicationNameFormatted,
                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.ApplicationNameFormatted,
                WrappedTarget  = fileTarget_General,
                BufferSize     = 50,
                FlushTimeout   = 5000,
                SlidingTimeout = false
            };

            loggingConfiguration.AddTarget(fileAsyncTargetWrapper_General);
            loggingConfiguration.AddRule(LogLevel.Trace, LogLevel.Warn, Constants.ApplicationNameFormatted);

            // All messages from Warn to Fatal levels write to the error file with advanced trace information
            FileTarget fileTarget_Error = new FileTarget()
            {
                Name             = Constants.ApplicationNameFormatted,
                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.ApplicationNameFormatted);

            // Apply all the custom configurations to the LogManager
            LogManager.Configuration = loggingConfiguration;

            // Setup logger factory
            InitializeDatabaseFactory();

            Log.Info("Logging initialization finished.");
        }
예제 #26
0
        public Log()
        {
            if (log == null)
            {
                // Step 1. Create configuration object
                LoggingConfiguration logConfig = new LoggingConfiguration();

                // Step 2. Create targets and add them to the configuration

                FileTarget fileTarget = new FileTarget();
                logConfig.AddTarget("file", fileTarget);

                // Step 3. Set target properties

                //fileTarget.FileName = "${basedir}/${date}_log.txt";
                fileTarget.Layout   = "${longdate} ${uppercase:${level}} ${message}";
                fileTarget.Encoding = Encoding.UTF8;

                fileTarget.FileName        = "${basedir}/logs/log.log";
                fileTarget.ArchiveFileName = "${basedir}/logs/archives/log.{#}.log";

                fileTarget.ArchiveEvery      = FileArchivePeriod.Day;
                fileTarget.ArchiveNumbering  = ArchiveNumberingMode.Date;
                fileTarget.ArchiveDateFormat = "yyyyMMdd";
                fileTarget.MaxArchiveFiles   = 30;

                // Step 4. Define rules

                LoggingRule rule = new LoggingRule("*", LogLevel.Trace, fileTarget);
                logConfig.LoggingRules.Add(rule);

                //if (Config.GetIsOpenLogForm())
                if (false)
                {
                    RichTextBoxTarget richTextBoxInfoTarget = new RichTextBoxTarget();
                    richTextBoxInfoTarget.Name        = "info";
                    richTextBoxInfoTarget.AutoScroll  = true;
                    richTextBoxInfoTarget.MaxLines    = 10000;
                    richTextBoxInfoTarget.FormName    = "LogForm";
                    richTextBoxInfoTarget.ToolWindow  = true;
                    richTextBoxInfoTarget.ControlName = "richTextBoxInfo";
                    richTextBoxInfoTarget.UseDefaultRowColoringRules = true;
                    richTextBoxInfoTarget.Layout = "${longdate} ${uppercase:${level}} ${message}";
                    logConfig.AddTarget("richTextBoxInfoTarget", richTextBoxInfoTarget);

                    RichTextBoxTarget richTextBoxTraceTarget = new RichTextBoxTarget();
                    richTextBoxTraceTarget.Name        = "trace";
                    richTextBoxTraceTarget.AutoScroll  = true;
                    richTextBoxTraceTarget.MaxLines    = 10000;
                    richTextBoxTraceTarget.FormName    = "LogForm";
                    richTextBoxTraceTarget.ToolWindow  = true;
                    richTextBoxTraceTarget.ControlName = "richTextBoxTrace";
                    richTextBoxTraceTarget.UseDefaultRowColoringRules = true;
                    richTextBoxTraceTarget.Layout = "${longdate} ${uppercase:${level}} ${message}";
                    logConfig.AddTarget("richTextBoxTraceTarget", richTextBoxTraceTarget);

                    rule = new LoggingRule("*", LogLevel.Debug, richTextBoxInfoTarget);
                    logConfig.LoggingRules.Add(rule);

                    rule = new LoggingRule("*", LogLevel.Trace, LogLevel.Trace, richTextBoxTraceTarget);
                    logConfig.LoggingRules.Add(rule);
                }

                // Step 5. Activate the configuration
                LogManager.Configuration = logConfig;

                log = LogManager.GetLogger("Example");

                //log = NLog.LogManager.GetCurrentClassLogger();
            }
        }
예제 #27
0
        public void InitializeLoggers()
        {
            // default log directory.
            string logFolderBase;

            // Log directory supplied in Settings.xml.
            if (!string.IsNullOrEmpty(LogFolderBasePath))
            {
                logFolderBase = LogFolderBasePath;

                if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                {
                    // Add current drive letter if not supplied for Windows path target.
                    if (!LogFolderBasePath.Substring(0, 3).Contains(":\\"))
                    {
                        string windrive = Environment.SystemDirectory.Substring(0, 3);
                        logFolderBase = windrive + LogFolderBasePath;
                    }
                }
                else
                {
                    // Remove supplied drive letter if Linux is the runtime target.
                    if (LogFolderBasePath.Substring(0, 3).Contains(":\\"))
                    {
                        logFolderBase = LogFolderBasePath.Remove(0, 3).Replace("\\", "/");
                    }
                }
            }
            else
            {
                if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                {
                    string windrive = Environment.SystemDirectory.Substring(0, 3);
                    logFolderBase = windrive + "observer_logs";
                }
                else
                {
                    logFolderBase = "/tmp/observer_logs";
                }
            }

            this.LogFolderBasePath = logFolderBase;
            string file = Path.Combine(logFolderBase, "fabric_observer.log");

            if (!string.IsNullOrEmpty(FolderName) && !string.IsNullOrEmpty(Filename))
            {
                string folderPath = Path.Combine(logFolderBase, FolderName);
                file = Path.Combine(folderPath, Filename);
            }

            FilePath = file;

            var targetName = this.loggerName + "LogFile";

            if (LogManager.Configuration == null)
            {
                LogManager.Configuration = new LoggingConfiguration();
            }

            if ((FileTarget)LogManager.Configuration?.FindTargetByName(targetName) == null)
            {
                var target = new FileTarget
                {
                    Name = targetName,
                    OptimizeBufferReuse = true,
                    ConcurrentWrites    = true,
                    FileName            = file,
                    Layout = "${longdate}--${uppercase:${level}}--${message}",
                    OpenFileCacheTimeout = 5,
                    ArchiveNumbering     = ArchiveNumberingMode.DateAndSequence,
                    ArchiveEvery         = FileArchivePeriod.Day,
                    AutoFlush            = true,
                };

                LogManager.Configuration.AddTarget(this.loggerName + "LogFile", target);

                var ruleInfo = new LoggingRule(this.loggerName, NLog.LogLevel.Debug, target);

                LogManager.Configuration.LoggingRules.Add(ruleInfo);
                LogManager.ReconfigExistingLoggers();
            }

            TimeSource.Current = new AccurateUtcTimeSource();
            OLogger            = LogManager.GetLogger(this.loggerName);
        }
예제 #28
0
파일: WDNav.cs 프로젝트: subha9/WDTF
        public AutomationLogging()
        {
            string resultFolder = @"C:/WDTF/TestResult";
            string asm          = Assembly.GetCallingAssembly().FullName;
            string logFormat    = string.Format("{0:yyMMddhhmmss}", DateTime.Now);

            newLocationInResultFolder = resultFolder + "/" + currentGuid + "_" + logFormat;
            DirectoryInfo directoryInfo = new DirectoryInfo(newLocationInResultFolder);

            if (!directoryInfo.Exists)
            {
                System.IO.Directory.CreateDirectory(newLocationInResultFolder);
            }
            //FileInfo[] fileInformation = directoryInfo.GetFiles();
            //foreach (FileInfo item in fileInformation)
            //{
            //    item.Delete();
            //}
            LoggingConfiguration config = new LoggingConfiguration();
            //{TestName}_TIME.htm
            // string logFormat = string.Format("{0:yyMMddhhmmss}", DateTime.Now);


            //===========================================================================================//
            ColoredConsoleTarget consoleTarget = new ColoredConsoleTarget();

            consoleTarget.Layout = "${time} | ${level}  | ${stacktrace::topFrames=2}|${message} ";
            config.AddTarget("console", consoleTarget);
            LoggingRule consoleInfo = new LoggingRule("*", LogLevel.Info, consoleTarget);

            config.LoggingRules.Add(consoleInfo);
            //===========================================================================================//
            FileTarget fileTarget = new FileTarget();

            fileTarget.Layout   = "${time} | ${level}  | ${stacktrace:topFrames=2} | ${message} ";
            fileTarget.FileName = newLocationInResultFolder + "/" + className + "_" + logFormat + ".txt";
            config.AddTarget("file", fileTarget);
            LoggingRule fileInfo = new LoggingRule("*", LogLevel.Info, fileTarget);

            config.LoggingRules.Add(fileInfo);
            //===========================================================================================//
            TraceTarget traceTarget = new TraceTarget();

            traceTarget.Layout = "${time} | ${level}  | ${stacktrace:topFrames=2} | ${message} ";

            //===========================================================================================//
            MailTarget mailTarget = new MailTarget();

            mailTarget.Name               = "gmail";
            mailTarget.SmtpServer         = "smtp.gmail.com";
            mailTarget.SmtpPort           = 465;
            mailTarget.SmtpAuthentication = SmtpAuthenticationMode.Basic;
            mailTarget.SmtpUserName       = "******";
            mailTarget.SmtpPassword       = "******";
            mailTarget.EnableSsl          = true;
            mailTarget.From               = "*****@*****.**";
            mailTarget.To = "*****@*****.**";
            mailTarget.CC = "";
            LoggingRule mailInfo = new LoggingRule("*", LogLevel.Info, mailTarget);

            config.LoggingRules.Add(mailInfo);

            //===========================================================================================//
            DatabaseTarget dbTarget = new DatabaseTarget();

            //===========================================================================================//

            // Step 4. Define rules
            LogManager.Configuration = config;
        }
	/// <summary>  initializes the log system using the logfile argument
	/// *
	/// </summary>
	/// <param name="logFile">  file for log messages
	///
	/// </param>
	public virtual void  init(System.String logFile) {

	    /*
	    *  make our FileTarget.  Note we are going to keep the 
	    *  default behavior of not appending...
	    */
	    FileTarget target = new FileTarget(new System.IO.FileInfo(logFile), false, new VelocityFormatter("%{time} %{message}\\n%{throwable}"));

	    /*
	    *  use the toString() of RuntimeServices to make a unique logger
	    */

	    //UPGRADE_TODO: The equivalent in .NET for method 'java.Object.toString' may return a different value. 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca1043"'
	    logger = Hierarchy.DefaultHierarchy.getLoggerFor(rsvc.ToString());
	    logger.Priority = Priority.DEBUG;
	    logger.LogTargets = new LogTarget[]{target};
	}
예제 #30
0
        /// <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");
            }
        }
예제 #31
0
        /// <summary>Basic constructor.</summary>
        public MicroserviceBase()
        {
            // Listen the ProcessExit event to control service stop.
            AppDomain.CurrentDomain.ProcessExit += (s, e) => StopEvent(s, e);

            // Log configuration.
            var loggerFactory = new LoggerFactory();

            loggerFactory.AddNLog();
            LoggingConfiguration logConfig = new LoggingConfiguration();

            string instanceId = System.Environment.MachineName;

            if (instanceId.Length > 12)
            {
                instanceId = instanceId.Substring(0, 12);
            }

            // Read appsettings.json configuration file.
            string configPath    = "appsettings.json";
            var    file          = new FileInfo(configPath);
            string env           = GetEnvironmentConfigFileSuffix();
            string fileName      = file.Name.Substring(0, file.Name.Length - file.Extension.Length);
            string envConfigPath = fileName + "." + env + file.Extension;

            var builder = new ConfigurationBuilder()
                          .SetBasePath(System.Environment.CurrentDirectory)
                          .AddJsonFile(configPath, true)
                          .AddJsonFile(envConfigPath, true);

            var config  = builder.Build();
            var section = config.GetSection("Relier.Microservice");

            if (section.Exists())
            {
                // Verify if have to log Debug.
                if (section.GetValue <bool>("Debug"))
                {
                    FileTarget debugFileTarget = new FileTarget();
                    debugFileTarget.FileName = "${basedir}/logs/log-" + instanceId + "-debug.log";
                    debugFileTarget.Layout   = "${date} ${level:uppercase=true} ${message} ${exception}";
                    logConfig.AddTarget("debugFileLog", debugFileTarget);
                    logConfig.AddRule(NLog.LogLevel.Debug, NLog.LogLevel.Fatal, "debugFileLog");
                }
            }

            FileTarget generalFileLog = new FileTarget();

            generalFileLog.FileName = "${basedir}/logs/log-" + instanceId + ".log";
            generalFileLog.Layout   = "${date} ${level:uppercase=true} ${message} ${exception}";
            logConfig.AddTarget("generalFileLog", generalFileLog);
            logConfig.AddRule(NLog.LogLevel.Info, NLog.LogLevel.Fatal, "generalFileLog");

            NLog.LogManager.Configuration = logConfig;
            this.Logger = loggerFactory.CreateLogger <MicroserviceBase>();

            if (section.Exists())
            {
                // Verify if this service have any specific execution period.
                // Example: 00:00-06:00.
                string executionPeriod = section.GetValue <string>("ExecutionPeriod");
                if (!string.IsNullOrEmpty(executionPeriod))
                {
                    var regEx = new Regex("^(?:0?[0-9]|1[0-9]|2[0-3]):[0-5][0-9]-(?:0?[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$");
                    if (!regEx.IsMatch(executionPeriod))
                    {
                        string errorMessage = "Invalid time format for ExecutionPeriod parameter. The value " + executionPeriod + " is invalid. The correct pattern is HH:MM-HH:MM.";
                        this.Logger.LogError(errorMessage);
                        System.Environment.FailFast(errorMessage);
                    }

                    _executionPeriodStart = executionPeriod.Split('-')[0];
                    _executionPeriodEnd   = executionPeriod.Split('-')[1];
                }
            }
        }
예제 #32
0
                public void CallsUpdateFileOnRepo()
                {
                    this._mockRepo
                        .Setup(m => m.UpdateFile(
                            this._authToken,
                            It.IsAny<File>(),
                            It.IsAny<FileTarget>(),
                            It.IsAny<string>()
                        ))
                        .Verifiable();

                    var file = new DiskFile("Resources/content_file.gif");
                    var target = new FileTarget("pseudomuto", "reponame", "content_file.gif");

                    this._subject.PushFile(file, target, "updating file");

                    this._mockRepo.Verify();
                }
예제 #33
0
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            SetupConfig();

            if (AppConfig.NeedsConfigSetup)
            {
                int i = 1;
            }
            #region Setup Logger

            // Step 1. Create configuration object
            var config = new LoggingConfiguration();

            // Step 2. Create targets and add them to the configuration
            #region File Log

            FileTarget fileTarget;

            if (!string.IsNullOrEmpty(AppConfig.LogFileLocation))
            {
                fileTarget = new FileTarget
                {
                    ArchiveAboveSize = 1048576,
                    AutoFlush        = true,
                    MaxArchiveFiles  = 10,
                    CreateDirs       = true,
                    EnableFileDelete = true,
                    Header           =
                        "\n${date:format=HH\\:mm\\:ss}\nLog file for IMR Crawler Application\n===============================\n",
                    Footer   = "===============================\nEnd Log - ${date:format=HH\\:mm\\:ss}",
                    FileName = AppConfig.LogFileLocation + "\\${shortdate}.log",
                    Layout   =
                        "${date:format=HH\\:mm\\:ss} ${logger} : ${level:uppercase=true} : ${message} ${exception:format=message}"
                };
            }
            else
            {
                if (!Directory.Exists("C:\\Logs"))
                {
                    Directory.CreateDirectory("C:\\Logs");
                }
                fileTarget = new FileTarget
                {
                    ArchiveAboveSize = 1048576,
                    AutoFlush        = true,
                    MaxArchiveFiles  = 10,
                    CreateDirs       = true,
                    EnableFileDelete = true,
                    Header           =
                        "\n${date:format=HH\\:mm\\:ss}\nLog file for IMR Crawler Application\n===============================\n",
                    Footer   = "===============================\nEnd Log - ${date:format=HH\\:mm\\:ss}",
                    FileName = "C:\\Logs\\${shortdate}.log",
                    Layout   =
                        "${date:format=HH\\:mm\\:ss} ${logger} : ${level:uppercase=true} : ${message} ${exception:format=message}"
                };
            }

            config.AddTarget("file", fileTarget);

            #endregion

            var rule2 = new LoggingRule("*", LogLevel.Debug, fileTarget);
            config.LoggingRules.Add(rule2);

            // Step 5. Activate the configuration
            LogManager.Configuration = config;

            #endregion

            if (Environment.OSVersion.Version.Major >= 6)
            {
                if (!IsRunAsAdmin())
                {
                    ProcessStartInfo proc = new ProcessStartInfo();
                    proc.UseShellExecute  = true;
                    proc.WorkingDirectory = Environment.CurrentDirectory;
                    proc.FileName         = Application.ExecutablePath;
                    proc.Verb             = "runas";

                    try
                    {
                        Process.Start(proc);
                    }
                    catch
                    {
                        // The user refused the elevation.
                        // Do nothing and return directly ...
                        return;
                    }

                    Application.Exit();  // Quit itself
                }
                else
                {
                    Application.Run(new frmMain());
                }
            }
            else
            {
                Application.Run(new frmMain());
            }
        }
예제 #34
0
        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 + "/CableCloud.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;

            IClientWorkerFactory clientWorkerFactory = new ClientWorkerFactory();
            IListener            listener            = new Listener(configuration, clientWorkerFactory);
            IPacketForwarder     packetForwarder     = new PacketForwarder(configuration);

            ICableCloudManager cableCloudManager = new CableCloudManager(configuration, listener, packetForwarder);

            ICommandParser commandParser = new CommandParser(configuration);
            IUserInterface userInterface = new UserInterface(commandParser, cableCloudManager);

            try
            {
                Console.Title = "CC";
            }
            catch (Exception)
            {
                LOG.Trace("Could not set the title");
            }

            userInterface.Start();
        }
예제 #35
0
        /// <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 &lt; file name, Logging Level &gt;. 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;
        }
예제 #36
0
        internal void InitializeLoggers()
        {
            // default log directory.
            string logFolderBase;

            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                string windrive = Environment.SystemDirectory.Substring(0, 2);
                logFolderBase = windrive + "\\clusterobserver_logs";
            }
            else
            {
                // Linux
                logFolderBase = "clusterobserver_logs";
            }

            // log directory supplied in config. Set in ObserverManager.
            if (!string.IsNullOrEmpty(this.LogFolderBasePath))
            {
                logFolderBase = this.LogFolderBasePath;
            }

            string file = Path.Combine(logFolderBase, "cluster_observer.log");

            if (!string.IsNullOrEmpty(this.FolderName) && !string.IsNullOrEmpty(this.Filename))
            {
                string folderPath = Path.Combine(logFolderBase, this.FolderName);
                file = Path.Combine(folderPath, this.Filename);
            }

            this.FilePath = file;

            var targetName = this.loggerName + "LogFile";

            if (LogManager.Configuration == null)
            {
                LogManager.Configuration = new LoggingConfiguration();
            }

            if ((FileTarget)LogManager.Configuration?.FindTargetByName(targetName) == null)
            {
                var target = new FileTarget
                {
                    Name                 = targetName,
                    FileName             = file,
                    Layout               = "${longdate}--${uppercase:${level}}--${message}",
                    OpenFileCacheTimeout = 5,
                    ArchiveNumbering     = ArchiveNumberingMode.DateAndSequence,
                    ArchiveEvery         = FileArchivePeriod.Day,
                    AutoFlush            = true,
                };

                LogManager.Configuration.AddTarget(this.loggerName + "LogFile", target);

                var ruleInfo = new LoggingRule(this.loggerName, NLog.LogLevel.Debug, target);

                LogManager.Configuration.LoggingRules.Add(ruleInfo);
                LogManager.ReconfigExistingLoggers();
            }

            TimeSource.Current = new AccurateUtcTimeSource();
            this.OLogger       = LogManager.GetLogger(this.loggerName);
        }
예제 #37
0
        private static void Start(string[] args)
        {
            // SE_VERSION is a private constant. Need to use reflection to get it.
            FieldInfo field = typeof(SpaceEngineersGame).GetField("SE_VERSION", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static);

            SeVersion = new Version(new MyVersion((int)field.GetValue(null)).FormattedText.ToString().Replace("_", "."));

            //bool stableBuild = (bool)typeof(MyFinalBuildConstants).GetField("IS_STABLE").GetValue(null);

            ApplicationLog.BaseLog.Info($"SE version: {SeVersion}");

            string versionMessage = $"Extender version: {Assembly.GetExecutingAssembly().GetName().Version}";

#if DEBUG
            //mark debug builds as such
            versionMessage += " DEBUG";
#endif
            ApplicationLog.BaseLog.Info(versionMessage);


            //warn users about SESE EOL and Torch migration
            if (SystemInformation.UserInteractive)
            {
                Task.Run(() =>
                {
                    AutoClosingMessageBox.Show("Support for SESE is ENDING. Ongoing compatability is not guaranteed. All servers should migrate to" +
                                               "Torch (SESE2) when it becomes available. Join our discord server to stay updated on Torch's status: " +
                                               "https://discord.gg/JPrcsWt or check regularly at https://github.com/TorchAPI/Torch",
                                               "SESE EOL",
                                               20000);
                });
            }
            BaseLog.Warn("Support for SESE is ENDING. Ongoing compatability is not guaranteed. All servers should migrate to" +
                         "Torch (SESE2) when it becomes available. Join our discord server to stay updated on Torch's status: " +
                         "https://discord.gg/JPrcsWt or check regularly at https://github.com/TorchAPI/Torch");



            /*
             * if (stableBuild)
             * {
             *  BaseLog.Info("Detected \"Stable\" branch!");
             *  //BaseLog.Error("WARNING: THIS BUILD OF SESE IS NOT COMPATIBLE WITH STABLE BRANCH");
             *          //if (SystemInformation.UserInteractive)
             *          //{
             *          //    var result = MessageBox.Show("This build of SESE is not compatible with stable branch!",
             *          //                                 "Fatal Error",
             *          //                                 MessageBoxButtons.OK,
             *          //                                 MessageBoxIcon.Error);
             *          //    if (result == DialogResult.OK)
             *          //    {
             *          //        Stop();
             *          //        return;
             *          //    }
             *          //}
             *          //else
             *          //{
             *          //    Stop();
             *          //    return;
             *          //}
             *          IsStable = true;
             *          PluginManager.IsStable = true;
             *          Server.IsStable = true;
             * }
             * else
             *  BaseLog.Info("Detected \"Development\" branch!");
             */
            InitSandbox();

            //Setup error handling for unmanaged exceptions
            AppDomain.CurrentDomain.UnhandledException += AppDomain_UnhandledException;
            Application.ThreadException += Application_ThreadException;
            Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);

            //AppDomain.CurrentDomain.ClearEventInvocations("_unhandledException");

            BaseLog.Info("Starting SEServerExtender with {0} arguments: {1}", args.Length, string.Join("\r\n\t", args));

            CommandLineArgs extenderArgs = CommandLineArgs = new CommandLineArgs
            {
                ConsoleTitle = string.Empty,
                AutoStart    = false,
                WorldName    = string.Empty,
                InstanceName = string.Empty,
                NoGui        = false,
                NoConsole    = false,
                Debug        = false,
                GamePath     = new DirectoryInfo(PathManager.BasePath).Parent.FullName,
                //TODO: turn noWFC back to off by default whenever WCF gets fixed
                NoWcf          = true,
                Autosave       = 0,
                InstancePath   = string.Empty,
                CloseOnCrash   = false,
                RestartOnCrash = false,
                NoProfiler     = false,
                Args           = string.Join(" ", args.Select(x => string.Format("\"{0}\"", x)))
            };

            if (ConfigurationManager.AppSettings["WCFChatMaxMessageHistoryAge"] != null)
            {
                if (!int.TryParse(ConfigurationManager.AppSettings["WCFChatMaxMessageHistoryAge"], out _maxChatHistoryMessageAge))
                {
                    ConfigurationManager.AppSettings.Add("WCFChatMaxMessageHistoryAge", "3600");
                }
            }
            if (ConfigurationManager.AppSettings["WCFChatMaxMessageHistoryCount"] != null)
            {
                if (!int.TryParse(ConfigurationManager.AppSettings["WCFChatMaxMessageHistoryCount"], out _maxChatHistoryMessageCount))
                {
                    ConfigurationManager.AppSettings.Add("WCFChatMaxMessageHistoryCount", "100");
                }
            }

            bool logPathSet = false;
            //Process the args
            foreach (string arg in args)
            {
                string[] splitAtEquals = arg.Split('=');
                if (splitAtEquals.Length > 1)
                {
                    string argName  = splitAtEquals[0];
                    string argValue = splitAtEquals[1];

                    string lowerCaseArgument = argName.ToLower( );
                    if (lowerCaseArgument.Equals("instance"))
                    {
                        if (argValue[argValue.Length - 1] == '"')
                        {
                            argValue = argValue.Substring(1, argValue.Length - 2);
                        }
                        //sanitize input because stupid people put full paths for this argument
                        extenderArgs.InstanceName = argValue.Replace(@"\", "-").Replace(@":", "-");

                        //Only let this override log path if the log path wasn't already explicitly set
                        if (!logPathSet)
                        {
                            FileTarget baseLogTarget = LogManager.Configuration.FindTargetByName("BaseLog") as FileTarget;
                            if (baseLogTarget != null)
                            {
                                baseLogTarget.FileName = baseLogTarget.FileName.Render(new LogEventInfo {
                                    TimeStamp = DateTime.Now
                                }).Replace("NoInstance", argValue.Replace(@"\", "-").Replace(@":", "-"));
                            }
                            FileTarget chatLogTarget = LogManager.Configuration.FindTargetByName("ChatLog") as FileTarget;
                            if (chatLogTarget != null)
                            {
                                chatLogTarget.FileName = chatLogTarget.FileName.Render(new LogEventInfo {
                                    TimeStamp = DateTime.Now
                                }).Replace("NoInstance", argValue.Replace(@"\", "-").Replace(@":", "-"));
                            }
                            FileTarget pluginLogTarget = LogManager.Configuration.FindTargetByName("PluginLog") as FileTarget;
                            if (pluginLogTarget != null)
                            {
                                pluginLogTarget.FileName = pluginLogTarget.FileName.Render(new LogEventInfo {
                                    TimeStamp = DateTime.Now
                                }).Replace("NoInstance", argValue.Replace(@"\", "-").Replace(@":", "-"));
                            }
                        }
                    }
                    else if (lowerCaseArgument.Equals("gamepath"))
                    {
                        if (argValue[argValue.Length - 1] == '"')
                        {
                            argValue = argValue.Substring(1, argValue.Length - 2);
                        }
                        extenderArgs.GamePath = argValue;
                    }
                    else if (lowerCaseArgument.Equals("autosave"))
                    {
                        if (!int.TryParse(argValue, out extenderArgs.Autosave))
                        {
                            BaseLog.Warn("Autosave parameter was not a valid integer.");
                        }
                    }
                    else if (lowerCaseArgument.Equals("path"))
                    {
                        if (argValue[argValue.Length - 1] == '"')
                        {
                            argValue = argValue.Substring(1, argValue.Length - 2);
                        }
                        extenderArgs.InstancePath = argValue;
                    }
                    else if (lowerCaseArgument.Equals("instancepath"))
                    {
                        if (argValue[argValue.Length - 1] == '"')
                        {
                            argValue = argValue.Substring(1, argValue.Length - 2);
                        }
                        extenderArgs.InstancePath = argValue;
                    }
                    else if (lowerCaseArgument.Equals("title"))
                    {
                        if (argValue[argValue.Length - 1] == '"')
                        {
                            argValue = argValue.Substring(1, argValue.Length - 2);
                        }
                        extenderArgs.ConsoleTitle = argValue;
                    }
                    else if (lowerCaseArgument == "logpath")
                    {
                        if (argValue[argValue.Length - 1] == '"')
                        {
                            argValue = argValue.Substring(1, argValue.Length - 2);
                        }

                        //This argument always prevails.
                        FileTarget baseLogTarget = LogManager.Configuration.FindTargetByName("BaseLog") as FileTarget;
                        if (baseLogTarget != null)
                        {
                            Layout l = new SimpleLayout(Path.Combine(argValue, "SEServerExtenderLog-${shortdate}.log"));
                            baseLogTarget.FileName = l.Render(new LogEventInfo {
                                TimeStamp = DateTime.Now
                            });
                            ApplicationLog.BaseLog = BaseLog;
                        }
                        FileTarget chatLogTarget = LogManager.Configuration.FindTargetByName("ChatLog") as FileTarget;
                        if (chatLogTarget != null)
                        {
                            Layout l = new SimpleLayout(Path.Combine(argValue, "ChatLog-${shortdate}.log"));
                            chatLogTarget.FileName = l.Render(new LogEventInfo {
                                TimeStamp = DateTime.Now
                            });
                            ApplicationLog.ChatLog = ChatLog;
                        }
                        FileTarget pluginLogTarget = LogManager.Configuration.FindTargetByName("PluginLog") as FileTarget;
                        if (pluginLogTarget != null)
                        {
                            Layout l = new SimpleLayout(Path.Combine(argValue, "PluginLog-${shortdate}.log"));
                            pluginLogTarget.FileName = l.Render(new LogEventInfo {
                                TimeStamp = DateTime.Now
                            });
                            logPathSet = true;
                            ApplicationLog.PluginLog = PluginLog;
                        }
                    }
                }
                else
                {
                    string lowerCaseArgument = arg.ToLower( );
                    if (lowerCaseArgument.Equals("autostart"))
                    {
                        extenderArgs.AutoStart = true;
                    }
                    else if (lowerCaseArgument.Equals("nogui"))
                    {
                        extenderArgs.NoGui = true;

                        //Implies autostart
                        //extenderArgs.AutoStart = true;
                    }
                    else if (lowerCaseArgument.Equals("noconsole"))
                    {
                        extenderArgs.NoConsole = true;

                        //Implies nogui and autostart
                        extenderArgs.NoGui     = true;
                        extenderArgs.AutoStart = true;
                    }
                    else if (lowerCaseArgument.Equals("debug"))
                    {
                        extenderArgs.Debug = true;
                    }
                    else if (lowerCaseArgument.Equals("nowcf"))
                    {
                        extenderArgs.NoWcf = true;
                    }
                    else if (lowerCaseArgument.Equals("wcfon"))
                    {
                        extenderArgs.NoWcf = false;
                    }
                    else if (lowerCaseArgument.Equals("closeoncrash"))
                    {
                        extenderArgs.CloseOnCrash = true;
                    }
                    else if (lowerCaseArgument.Equals("autosaveasync"))
                    {
                        extenderArgs.AutoSaveSync = false;
                    }
                    else if (lowerCaseArgument.Equals("autosavesync"))
                    {
                        extenderArgs.AutoSaveSync = true;
                    }
                    else if (lowerCaseArgument.Equals("restartoncrash"))
                    {
                        extenderArgs.RestartOnCrash = true;
                    }
                    else if (lowerCaseArgument.Equals("noprofiler") && !IsStable)
                    {
                        extenderArgs.NoProfiler = true;
                        Server.DisableProfiler  = true;
                    }
                    //these things are legacy and don't work anyway

                    /*
                     *                  else if ( lowerCaseArgument.Equals( "wrr" ) )
                     *                  {
                     *                          extenderArgs.WorldRequestReplace = true;
                     *                  }
                     *                  else if ( lowerCaseArgument.Equals( "wrm" ) )
                     *                  {
                     *                          extenderArgs.WorldDataModify = true;
                     *                  }
                     * else if (lowerCaseArgument.Equals("wvm"))
                     * {
                     *  extenderArgs.WorldVoxelModify = true;
                     * }
                     */
                }
            }

            if (!Environment.UserInteractive)
            {
                extenderArgs.NoConsole = true;
                extenderArgs.NoGui     = true;
                extenderArgs.AutoStart = true;
            }

            if (extenderArgs.Debug)
            {
                ExtenderOptions.IsDebugging = true;
            }

            try
            {
                bool unitTestResult = BasicUnitTestManager.Instance.Run( );
                if (!unitTestResult)
                {
                    ExtenderOptions.IsInSafeMode = true;
                }

                Server = Server.Instance;
                Server.CommandLineArgs = extenderArgs;
                Server.IsWCFEnabled    = !extenderArgs.NoWcf;
                Server.Init( );

                //if(!DedicatedServerAssemblyWrapper.IsStable)
                //    InitSandbox(Path.Combine( GameInstallationInfo.GamePath, @"..\Content"), Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "SpaceEngineers"));

                ChatManager.ChatCommand guiCommand = new ChatManager.ChatCommand("gui", ChatCommand_GUI, false);
                ChatManager.Instance.RegisterChatCommand(guiCommand);

                if (!CommandLineArgs.NoConsole)
                {
                    if (string.IsNullOrEmpty(extenderArgs.ConsoleTitle) || string.IsNullOrWhiteSpace(extenderArgs.ConsoleTitle))
                    {
                        Console.Title = "SESE";
                    }
                    else
                    {
                        Console.Title = extenderArgs.ConsoleTitle;
                    }
                }

                if (extenderArgs.AutoStart)
                {
                    Server.StartServer( );
                }

                if (!extenderArgs.NoWcf)
                {
                    string uriString = string.Format("{0}{1}", ConfigurationManager.AppSettings["WCFServerServiceBaseAddress"], CommandLineArgs.InstanceName);
                    BaseLog.Info("Opening up WCF service listener at {0}", uriString);
                    ServerServiceHost = new ServiceHost(typeof(ServerService.ServerService), new Uri(uriString, UriKind.Absolute));
                    ServerServiceHost.Open( );
                    ChatManager.Instance.ChatMessage += ChatManager_ChatMessage;
                }

                if (!extenderArgs.NoGui)
                {
                    Thread uiThread = new Thread(StartGui);
                    uiThread.SetApartmentState(ApartmentState.STA);
                    uiThread.Start( );
                }
                else if (Environment.UserInteractive)
                {
                    Console.ReadLine( );
                }
            }
            catch (AutoException eEx)
            {
                if (!extenderArgs.NoConsole)
                {
                    BaseLog.Info("AutoException - {0}\n\r{1}", eEx.AdditionnalInfo, eEx.GetDebugString( ));
                }
                if (!extenderArgs.NoGui)
                {
                    MessageBox.Show(string.Format("{0}\n\r{1}", eEx.AdditionnalInfo, eEx.GetDebugString( )), @"SEServerExtender", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }

                if (extenderArgs.NoConsole && extenderArgs.NoGui)
                {
                    throw eEx.GetBaseException( );
                }
            }
            catch (TargetInvocationException ex)
            {
                if (!extenderArgs.NoConsole)
                {
                    BaseLog.Info("TargetInvocationException - {0}\n\r{1}", ex, ex.InnerException);
                }
                if (!extenderArgs.NoGui)
                {
                    MessageBox.Show(string.Format("{0}\n\r{1}", ex, ex.InnerException), @"SEServerExtender", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }

                if (extenderArgs.NoConsole && extenderArgs.NoGui)
                {
                    throw;
                }
            }
            catch (Exception ex)
            {
                if (!extenderArgs.NoConsole)
                {
                    BaseLog.Info(ex, "Exception - {0}", ex);
                }
                if (!extenderArgs.NoGui)
                {
                    MessageBox.Show(ex.ToString( ), @"SEServerExtender", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }

                if (extenderArgs.NoConsole && extenderArgs.NoGui)
                {
                    throw;
                }
            }
        }
예제 #38
0
 protected override bool ResolveParameter(string param)
 {
     int equalPos = param.IndexOf('=');
     if (IsParam(param, "method", "m"))
     {
      if (equalPos == -1)
       throw new ArgumentException("--method must be specified with an Erasure " +
        "method GUID.");
      List<KeyValuePair<string, string> > subParams =
       GetSubParameters(param.Substring(equalPos + 1));
      ErasureMethod = new Guid(subParams[0].Key);
     }
     else if (IsParam(param, "schedule", "s"))
     {
      if (equalPos == -1)
       throw new ArgumentException("--schedule must be specified with a Schedule " +
        "type.");
      List<KeyValuePair<string, string> > subParams =
       GetSubParameters(param.Substring(equalPos + 1));
      switch (subParams[0].Key)
      {
       case "now":
        Schedule = Schedule.RunNow;
        break;
       case "manually":
        Schedule = Schedule.RunManually;
        break;
       case "restart":
        Schedule = Schedule.RunOnRestart;
        break;
       default:
        throw new ArgumentException("Unknown schedule type: " + subParams[0].Key);
      }
     }
     else if (IsParam(param, "recycled", "r"))
     {
      Targets.Add(new RecycleBinTarget());
     }
     else if (IsParam(param, "unused", "u"))
     {
      if (equalPos == -1)
       throw new ArgumentException("--unused must be specified with the Volume " +
        "to erase.");
      UnusedSpaceTarget target = new UnusedSpaceTarget();
      target.EraseClusterTips = false;
      List<KeyValuePair<string, string> > subParams =
       GetSubParameters(param.Substring(equalPos + 1));
      foreach (KeyValuePair<string, string> kvp in subParams)
       if (kvp.Value == null && target.Drive == null)
        target.Drive = Path.GetFullPath(kvp.Key);
       else if (kvp.Key == "clusterTips")
        target.EraseClusterTips = true;
       else
        throw new ArgumentException("Unknown subparameter: " + kvp.Key);
      Targets.Add(target);
     }
     else if (IsParam(param, "dir", "d") || IsParam(param, "directory", null))
     {
      if (equalPos == -1)
       throw new ArgumentException("--directory must be specified with the " +
        "directory to erase.");
      FolderTarget target = new FolderTarget();
      List<KeyValuePair<string, string> > subParams =
       GetSubParameters(param.Substring(equalPos + 1));
      foreach (KeyValuePair<string, string> kvp in subParams)
       if (kvp.Value == null && target.Path == null)
        target.Path = Path.GetFullPath(kvp.Key);
       else if (kvp.Key == "excludeMask")
       {
        if (kvp.Value == null)
     throw new ArgumentException("The exclude mask must be specified " +
      "if the excludeMask subparameter is specified");
        target.ExcludeMask = kvp.Value;
       }
       else if (kvp.Key == "includeMask")
       {
        if (kvp.Value == null)
     throw new ArgumentException("The include mask must be specified " +
      "if the includeMask subparameter is specified");
        target.IncludeMask = kvp.Value;
       }
       else if (kvp.Key == "delete")
        target.DeleteIfEmpty = true;
       else
        throw new ArgumentException("Unknown subparameter: " + kvp.Key);
      Targets.Add(target);
     }
     else if (IsParam(param, "file", "f"))
     {
      if (equalPos == -1)
       throw new ArgumentException("--file must be specified with the " +
        "file to erase.");
      FileTarget target = new FileTarget();
      List<KeyValuePair<string, string> > subParams =
       GetSubParameters(param.Substring(equalPos + 1));
      foreach (KeyValuePair<string, string> kvp in subParams)
       if (kvp.Value == null && target.Path == null)
        target.Path = Path.GetFullPath(kvp.Key);
       else
        throw new ArgumentException("Unknown subparameter: " + kvp.Key);
      Targets.Add(target);
     }
     else
      return false;
     return true;
 }
예제 #39
0
 private static void SetupLogFatal(NLogConfig config, FileTarget tbTarget, LogLevel logLevel)
 {
     config.LoggingRules.Add(new LoggingRule("Breeze.*", logLevel, tbTarget));
 }