Пример #1
0
        /// <summary>
        /// Attention: All loggers from all processes that write to the same <c>logFileNameBase</c> MUST use the same value for <c>rotateLogFileWhenLargerBytes</c>!
        /// </summary>
        public static bool TryCreateNew(
            string logFileDir,
            string logFileNameBase,
            Guid logGroupId,
            int rotateLogFileWhenLargerBytes,
            DefaultFormat.Options formatOptions,
            out FileLogSink newSink)
        {
            // Bad usage - throw.

            if (logFileNameBase == null)
            {
                throw new ArgumentNullException(nameof(logFileNameBase));
            }

            if (String.IsNullOrWhiteSpace(logFileNameBase))
            {
                throw new ArgumentException($"{nameof(logFileNameBase)} may not be white-space only.", nameof(logFileNameBase));
            }

            // Ok usage, but bad state - do not throw and return false.

            newSink = null;

            if (String.IsNullOrWhiteSpace(logFileDir))
            {
                return(false);
            }

            // Normalize in respect to final dir separator:
            logFileDir = Path.GetDirectoryName(Path.Combine(logFileDir, "."));

            // Ensure the directory exists:
            if (!EnsureDirectoryExists(logFileDir, out DirectoryInfo logFileDirInfo))
            {
                return(false);
            }

            LogGroupMutex logGroupMutex = null;

            try
            {
                logGroupMutex = new LogGroupMutex(logGroupId);
                if (!logGroupMutex.TryAcquire(out LogGroupMutex.Handle logGroupMutexHandle))
                {
                    logGroupMutex.Dispose();
                    return(false);
                }

                using (logGroupMutexHandle)
                {
                    DateTimeOffset now           = DateTimeOffset.Now;
                    int            rotationIndex = FindLatestRotationIndex(logFileDirInfo, logFileNameBase, now);

                    string     logFileName = ConstructFilename(logFileNameBase, now, rotationIndex);
                    string     logFilePath = Path.Combine(logFileDir, logFileName);
                    FileStream logStream   = new FileStream(logFilePath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite);

                    newSink = new FileLogSink(logGroupMutex, logFileDir, logFileNameBase, rotateLogFileWhenLargerBytes, logStream, rotationIndex, formatOptions);
                }

                if (newSink.TryLogInfo(
                        SelfLogSourceInfo.WithCallInfo().WithAssemblyName(),
                        "Logging session started",
                        new object[]
                {
                    "LogGroupId",
                    newSink.LogGroupId,
                    "LogSessionId",
                    newSink.LogSessionId,
                    "RotateLogFileWhenLargerBytes",
                    newSink.RotateLogFileWhenLargerBytes
                }))
                {
                    return(true);
                }
            }
            catch
            { }

            // If we did not succeed, the sink may be still constructed (e.g. TryLogInfo(..) returned false).
            // We need to dispose the sink before giving up, but be brepaed for it to sbe null.
            try
            {
                if (newSink != null)
                {
                    newSink.Dispose();  // This will also dispose the logGroupMutex owned by the newSink.
                }
                else
                {
                    logGroupMutex.Dispose();
                }
            }
            catch
            { }

            newSink = null;
            return(false);
        }
Пример #2
0
 internal static LogSourceInfo WithCallInfo(LogSourceInfo logSourceInfo,
                                            [CallerLineNumber] int callLineNumber    = 0,
                                            [CallerMemberName] string callMemberName = null)
 {
     return(logSourceInfo.WithCallInfo(callLineNumber, callMemberName));
 }
Пример #3
0
        private static async Task DoWorkAsync(int workerIdNum)
        {
            DateTimeOffset startTime = DateTimeOffset.Now;

            int    iteration = 0;
            string workerId  = workerIdNum.ToString("00");

            TimeSpan runtime = DateTimeOffset.Now - startTime;

            while (runtime < TimeSpan.FromSeconds(RuntimeSecs))
            {
                DemoLogAction demoLogAction;
                Exception     error = null;

                if (iteration > 0 && iteration % 10 == 0)
                {
                    try
                    {
                        ThrowException();
                        demoLogAction = (DemoLogAction)0;   // Line never reached
                    }
                    catch (Exception ex)
                    {
                        error = ex;
                        if ((iteration / 10) % 3 == 1)
                        {
                            demoLogAction = DemoLogAction.ErrorWithMessage;
                        }
                        else if ((iteration / 10) % 3 == 2)
                        {
                            demoLogAction = DemoLogAction.ErrorWithException;
                        }
                        else
                        {
                            demoLogAction = DemoLogAction.ErrorWithMessageAndException;
                        }
                    }
                }
                else if (iteration > 0 && iteration % 4 == 0)
                {
                    demoLogAction = DemoLogAction.Debug;
                }
                else
                {
                    demoLogAction = DemoLogAction.Info;
                }

                switch (demoLogAction)
                {
                case DemoLogAction.ErrorWithMessage:
                    Log.Error(LogSourceInfo.WithCallInfo().WithinLogSourcesGroup("Some Large Component"),
                              "An error has occurred",
                              "workerId", workerId,
                              "iteration", iteration,
                              "runtime", runtime,
                              "demoLogAction", demoLogAction);
                    break;

                case DemoLogAction.ErrorWithException:
                    Log.Error(LogSourceInfo.WithCallInfo().WithLogSourcesSubgroup("Some Subcomponent"),
                              error,
                              "workerId", workerId,
                              "iteration", iteration,
                              "runtime", runtime,
                              "demoLogAction", demoLogAction);
                    break;

                case DemoLogAction.ErrorWithMessageAndException:
                    Log.Error(LogSourceInfo.WithCallInfo(),
                              "An error has occurred",
                              error,
                              "workerId", workerId,
                              "iteration", iteration,
                              "runtime", runtime,
                              "demoLogAction", demoLogAction);
                    break;

                case DemoLogAction.Debug:
                    Log.Debug(LogSourceInfo.WithSrcFileInfo(),
                              "A debug-relevant event occurred",
                              "workerId", workerId,
                              "iteration", iteration,
                              "runtime", runtime,
                              "demoLogAction", demoLogAction,
                              "<UnpairedTag />");
                    break;

                case DemoLogAction.Info:
                default:
                    Log.Info(LogSourceInfo,
                             "A log-worthy event occurred",
                             "workerId", workerId,
                             "iteration", iteration,
                             "runtime", runtime,
                             "demoLogAction", demoLogAction);
                    break;
                }


                if (iteration % 500 == 0)
                {
                    ConsoleWriteLine();
                    ConsoleWriteLine($"Worker {workerId} has been running for {runtime} and completed {iteration} iterations.");
                }

                int delaymillis;
                lock (s_rnd)
                {
                    delaymillis = s_rnd.Next(10);
                }

                await Task.Delay(delaymillis);

                iteration++;
                runtime = DateTimeOffset.Now - startTime;
            }
        }