/// <summary>
        /// Formats and writes <paramref name="entries" /> to <paramref name="textWriter" />.
        /// </summary>
        /// <param name="entries"></param>
        /// <param name="textWriter"></param>
        /// <param name="entryFormatter"></param>
        /// <typeparam name="TEntry"></typeparam>
        public static void WriteEntriesTo <TEntry>(this IEnumerable <TEntry> entries, TextWriter textWriter, EntryFormatter <TEntry> entryFormatter = null)
            where TEntry : ILogEntry
        {
            Contract.Requires <ArgumentNullException>(entries != null);
            Contract.Requires <ArgumentNullException>(textWriter != null);

            if (entryFormatter == null)
            { // Try creating the default log formatter
                entryFormatter = DefaultFormatterAttribute.GetDefaultFormatterFor <TEntry>();
                if (entryFormatter == null)
                {
                    throw new ArgumentNullException(nameof(entryFormatter),
                                                    $"No [DefaultFormatter] could be found for entry type {typeof(TEntry).FullName}, so logFormatter argument must be set.");
                }
            }

            var setupLog     = new SetupLog();
            var formatWriter = new TextWriterFormatWriter(setupLog, textWriter, disposeWriter: false);
            var logWriter    = new TextLogWriter(setupLog, formatWriter);

            logWriter.AddFormat(entryFormatter);
            IEntryWriter <TEntry> entryWriter;

            logWriter.TryGetEntryWriter(out entryWriter);
            using (logWriter)
            {
                logWriter.Start();
                for (var enumerator = entries.GetEnumerator(); enumerator.MoveNext();)
                {
                    TEntry logEntry = enumerator.Current;
                    entryWriter.Write(ref logEntry);
                }
            }
        }
 public void TextLogWriter_WriteBatch_WritesArrayToStream()
 {
     using (var stream = new System.IO.MemoryStream())
     {
         using (var textWriter = new System.IO.StreamWriter(stream))
         {
             var writer    = new TextLogWriter(textWriter, Formatters.SimpleLogEventFormatter.DefaultInstance);
             var logEvents = new LogEvent[]
             {
                 new LogEvent()
                 {
                     EventName = "Test event."
                 },
                 new LogEvent()
                 {
                     EventName = "Test event 2."
                 }
             };
             writer.WriteBatch(logEvents, 2);
             Assert.IsTrue(stream.Length > 0);
             stream.Seek(0, System.IO.SeekOrigin.Begin);
             var result = System.Text.UTF8Encoding.UTF8.GetString(stream.GetBuffer());
             Assert.IsTrue(result.Contains("Test event."));
             Assert.IsTrue(result.Contains("Test event 2."));
         }
     }
 }
 /// <summary>
 /// Applies all configured formatters to <paramref name="writer" />.
 /// </summary>
 /// <param name="writer"></param>
 protected void ApplyConfiguredFormatters(TextLogWriter writer)
 {
     foreach (var formatterTuple in _formatters)
     {
         var configureFormatterAction = formatterTuple.Item3;
         configureFormatterAction(writer);
     }
 }
 protected internal ApplicationManager()
 {
     TextLogWriter writer = new TextLogWriter(new System.IO.MemoryStream());
     writer.Level = LogLevel.Fatal;
     writer.AutoflushLevel = LogLevel.Fatal;
     writer.IsEnabled = false;
     Logger = new StandardLogger(writer);
 }
 public void TextLogWriter_Constructor_AllowsNullEncoding()
 {
     using (var stream = new System.IO.MemoryStream())
     {
         using (var textWriter = new System.IO.StreamWriter(stream))
         {
             var writer = new TextLogWriter(textWriter, Formatters.SimpleLogEventFormatter.DefaultInstance);
         }
     }
 }
Beispiel #6
0
 public static ILogWriter[] GetLogWriter(string connectionPathFile, ConnectionStringSettings connectionPathDb)
 {
     ILogWriter[] logWriters = new ILogWriter[2];
     logWriters[0] = new TextLogWriter(connectionPathFile);
     if (connectionPathDb != null)
     {
         logWriters[1] = new DbLogWriter(new DbFactory(connectionPathDb).CreateContext());
     }
     return(logWriters);
 }
        /// <inheritdoc />
        public override ILogWriter CreateLogWriter(ITracerFactory setupTracerFactory)
        {
            var formatWriter = CreateFormatWriter(setupTracerFactory);

            formatWriter.FieldDelimiter  = FieldDelimiter;
            formatWriter.SpacesPerIndent = SpacesPerIndent;
            formatWriter.IncludeDate     = IncludeDate;
            formatWriter.IncludeTime     = IncludeTime;
            formatWriter.OutputTimeZone  = TimeZone;

            var logWriter = new TextLogWriter(setupTracerFactory, formatWriter);

            ApplyConfiguredFormatters(logWriter);
            return(logWriter);
        }
Beispiel #8
0
        public void TestMethod2()
        {
            var textres = new TextLogWriter("ttt.txt");
            var l       = new Queue <ILogData>();
            int i       = 0;

            while (i < 200)
            {
                l.Enqueue(new LogData("Info", "ok"));
                i++;
            }

            textres.loggerQueue = l;
            var res = textres.Write();


            Assert.IsTrue(res);
        }
Beispiel #9
0
        public void MultiLogWriterToText()
        {
            // Log output written here
            var stringWriter = new StringWriter();

            var setupTracerFactory = new SetupLog();
            EntryFormatAction <LoggingTimer.StartRecord> formatStart = (startRecord, writer) =>
            {
                writer.BeginEntry();
                writer.WriteField((buffer) => buffer.AppendFormat(">{0}", startRecord.TimingId));
                writer.EndEntry();
            };
            EntryFormatAction <LoggingTimer.StopRecord> formatStop = (stopRecord, writer) =>
            {
                writer.BeginEntry();
                writer.WriteField((buffer) => buffer.AppendFormat("<{0}", stopRecord.TimingId));
                writer.WriteField(stopRecord.ElapsedTime.ToString());
                writer.EndEntry();
            };
            var logWriter = new TextLogWriter(setupTracerFactory, new TextWriterFormatWriter(setupTracerFactory, stringWriter))
                            .AddFormat(formatStart)
                            .AddFormat(formatStop);

            using (var logManager = new LogManager(logWriter))
            {
                // LoggingTimer test class logs starts and stops
                LoggingTimer.RestartTimingIds();
                var timer   = new LoggingTimer("test LoggingTimer", logManager);
                var timing1 = timer.Start();
                Thread.Sleep(15);
                timing1.Stop();
                var timing2 = timer.Start();
                Thread.Sleep(10);
                timing2.Stop();
            }

            string logOutput = stringWriter.ToString();

            _testOutputHelper.WriteLine(logOutput);

            Assert.Contains(">2\r\n<2  00:00:00.", logOutput);
            Assert.Contains(">3\r\n<3  00:00:00.", logOutput);
        }
        protected virtual void InitializeComponents()
        {
            if (Logger == null)
            {
                TextLogWriter writer = new TextLogWriter(new System.IO.MemoryStream());
                writer.AutoflushLevel = LogLevel.Fatal;
                writer.IsEnabled      = false;
                Logger = new StandardLogger(writer);
            }
            if (ServiceProvider == null)
            {
                //if we have a kernel, then let's create a "depency-injection service provider".
                if (Kernel != null)
                {
                    ServiceProvider = new DIServiceProvider(Kernel);
                }
                //otherwise, create a regular, plain service provider
                else
                {
                    ServiceProvider = new ServiceProvider();
                }
            }
            if (PresentationController == null)
            {
                PresentationController = new PresentationController();
            }
            if (ApplicationModuleManager == null)
            {
                ApplicationModuleManager = new ApplicationModuleManager();
            }

            ApplicationModuleManager.PresentationController = PresentationController;
            //if the Kernel is present, then link both module managers (from Foundation and from Ninject).
            if (Kernel != null)
            {
                ApplicationModuleManager.ModuleManager = Kernel.Components.ModuleManager;
            }
        }
Beispiel #11
0
        /// <summary>
        /// Formats and writes <paramref name="entries" /> to <paramref name="testOutputHelper" />.
        /// </summary>
        /// <param name="testOutputHelper"></param>
        /// <param name="entries"></param>
        /// <param name="entryFormatter"></param>
        /// <typeparam name="TEntry">The log entry type; must implement <see cref="ILogEntry" /></typeparam>
        public static void WriteEntries <TEntry>(this ITestOutputHelper testOutputHelper, IEnumerable <TEntry> entries, EntryFormatter <TEntry> entryFormatter = null)
            where TEntry : ILogEntry
        {
            Contract.Requires <ArgumentNullException>(entries != null);
            Contract.Requires <ArgumentNullException>(testOutputHelper != null);

            var setupLog     = new SetupLog();
            var formatWriter = new TestOutputFormatWriter(testOutputHelper, setupLog);
            var logWriter    = new TextLogWriter(setupLog, formatWriter);

            logWriter.AddFormat(entryFormatter);
            IEntryWriter <TEntry> entryWriter;

            logWriter.TryGetEntryWriter(out entryWriter);
            using (logWriter)
            {
                logWriter.Start();
                for (var enumerator = entries.GetEnumerator(); enumerator.MoveNext();)
                {
                    TEntry logEntry = enumerator.Current;
                    entryWriter.Write(ref logEntry);
                }
            }
        }
Beispiel #12
0
 public void TextLogWriter_Constructor_ThrowsOnNullWriter()
 {
     var writer = new TextLogWriter(null, Formatters.SimpleLogEventFormatter.DefaultInstance);
 }
Beispiel #13
0
        public static void Main(string[] args)
        {
            DebugLog("Starting");
            if (Debugger.IsAttached == false)
            {
                var pathToExe         = Process.GetCurrentProcess().MainModule.FileName;
                var pathToContentRoot = Path.GetDirectoryName(pathToExe);
                Directory.SetCurrentDirectory(pathToContentRoot);
                DebugLog("Set Current Dir as " + pathToContentRoot);
            }

            Program.textLogWriter = new TextLogWriter();
            DebugLog("Creating logs at " + Environment.CurrentDirectory + "\\Logs");

            Program.textLogWriter.InitializeLogWriter(System.Environment.CurrentDirectory + "\\Logs", "ConceptsClient", false, true, true, true);
            LogableTask task = LogableTask.NewTask("Main");

            try
            {
                task.Log(MethodBase.GetCurrentMethod(), System.Diagnostics.TraceLevel.Info, "Starting app");
                appSettings = JsonConvert.DeserializeObject <appSettingsDTO>(System.IO.File.ReadAllText(System.Environment.CurrentDirectory + "\\ConceptsClient.json"));

                appSettings.ServerUrl = string.Format(appSettings.ServerUrl, appSettings.Server);
                if (Program.appSettings.ServerUrl.EndsWith('/') == false && Program.appSettings.ServerUrl.EndsWith('\\') == false)
                {
                    appSettings.ServerUrl += "/";
                }

                //if (appSettings.LogsFolderPath == null || appSettings.LogsFolderPath == "")
                //    appSettings.LogsFolderPath = Startup.hostingEnvironment.ContentRootPath + "\\Logs";

                //textLogWriter.InitializeLogWriter(appSettings.LogsFolderPath, "ConceptsClient", false, true, true, true);


                var builder = CreateWebHostBuilder(args);
                task.Log(MethodBase.GetCurrentMethod(), System.Diagnostics.TraceLevel.Info, "web host builder created");

                builder.UseKestrel().UseIISIntegration();
                task.Log(MethodBase.GetCurrentMethod(), System.Diagnostics.TraceLevel.Info, "going to use URL " + appSettings.LocalUrl);

                //    builder.UseUrls("http://0.0.0.0:82");


                task.Log(MethodBase.GetCurrentMethod(), System.Diagnostics.TraceLevel.Info, "useUrls set");

                //   if (Debugger.IsAttached == false)// that is running as windows service
                //   builder.UseContentRoot(System.Environment.CurrentDirectory);


                task.Log(MethodBase.GetCurrentMethod(), System.Diagnostics.TraceLevel.Info, "Content root set as " + Environment.CurrentDirectory);

                var host = builder.Build();
                task.Log(MethodBase.GetCurrentMethod(), System.Diagnostics.TraceLevel.Info, "Host built now. Run as Service =" + appSettings.RunAsService);

                if (appSettings.RunAsService)
                {
                    task.Log(MethodBase.GetCurrentMethod(), System.Diagnostics.TraceLevel.Info, "Host starting as windows service");
                    task.EndTask();
                    // host.RunAsCustomService();// host.RunAsService();
                }
                else
                {
                    task.Log(MethodBase.GetCurrentMethod(), System.Diagnostics.TraceLevel.Info, "Host starting now as process");
                    task.EndTask();
                    host.Run();
                }
            }
            catch (Exception ex)
            {
                task.Log(MethodBase.GetCurrentMethod(), System.Diagnostics.TraceLevel.Error, ex);
            }
            finally
            {
                if (task.ended == false)
                {
                    task.EndTask();
                }
            }
        }