public void Apply(int waitingLogEntries, Action <int> nonDiscardActionWithTimeout, Action discardAction)
        {
            if (Strategy == ThrottlingStrategy.None || waitingLogEntries < Limit)
            {
                nonDiscardActionWithTimeout(Timeout.Infinite);
                return;
            }

            if (Strategy == ThrottlingStrategy.Discard)
            {
                InternalLogger.Warn("[Syslog] Applied discard throttling strategy");
                discardAction();
                return;
            }

            ApplyDeferment(waitingLogEntries);
            nonDiscardActionWithTimeout(CalculateTimeout(waitingLogEntries));
        }
Beispiel #2
0
 private void TidyUp()
 {
     try
     {
         if (isReady)
         {
             Terminate();
         }
     }
     catch (Exception exception)
     {
         InternalLogger.Warn(exception, "[Syslog] Terminate failed");
     }
     finally
     {
         isReady = false;
     }
 }
        /// <summary>
        /// Evaluates the expression.
        /// </summary>
        /// <param name="context">Evaluation context.</param>
        /// <returns>Expression result.</returns>
        public object Evaluate(LogEventInfo context)
        {
            try
            {
                return(this.EvaluateNode(context));
            }
            catch (Exception exception)
            {
                InternalLogger.Warn(exception, "Exception occurred when evaluating condition");

                if (exception.MustBeRethrownImmediately())
                {
                    throw;
                }

                throw new ConditionEvaluationException("Exception occurred when evaluating condition", exception);
            }
        }
        protected override void CloseTarget()
        {
            InternalLogger.Warn("Closing {0} target", nameof(AzureBlobStorageLogTarget));
            var result = _log.ShutdownAsync().GetAwaiter().GetResult();

            if (!result.Succeeded)
            {
                InternalLogger.Error(
                    result.Exception,
                    "Failed to shutdown {0} target appropriately. Error: {1}",
                    nameof(AzureBlobStorageLogTarget),
                    result.Diagnostics ?? result.ErrorMessage ?? string.Empty);
            }
            else
            {
                InternalLogger.Info("Closed {0} target successfully", nameof(AzureBlobStorageLogTarget));
            }
        }
        protected override void Write(IList <AsyncLogEventInfo> logEvents)
        {
            if (!AuthTokenResolved())
            {
                InternalLogger.Warn("auth token not resolved. skipping log entry.");
                return;
            }

            InternalLogger.Debug($"Sending {logEvents.Count} entries to endpoint: {Endpoint}");

            using (var ms = new MemoryStream())
            {
                using (var gzip = new GZipStream(ms, CompressionMode.Compress, true))
                {
                    using (var sw = new StreamWriter(gzip, _encoding, 1024, true))
                    {
                        using (var jw = new JsonTextWriter(sw))
                        {
                            var ser = JsonSerializer.Create(_logEntrySerializerSettings);

                            foreach (var asyncLogEvent in logEvents)
                            {
                                try
                                {
                                    SerializeLogEntry(jw, ser, asyncLogEvent.LogEvent);

                                    asyncLogEvent.Continuation(null);
                                }
                                catch (Exception ex)
                                {
                                    InternalLogger.Error(ex, "Error writing Splunk log event");

                                    asyncLogEvent.Continuation(ex);
                                }
                            }
                        }
                    }
                }

                ms.Position = 0;

                SendToEventCollector(ms);
            }
        }
Beispiel #6
0
        public void WriteToStringWriterWithArgsTests()
        {
            // Expected result is the same for both types of method invocation.
            const string expected = "Warn WWW 0\nError EEE 0, 1\nFatal FFF 0, 1, 2\nTrace TTT 0, 1, 2\nDebug DDD 0, 1\nInfo III 0\n";

            InternalLogger.LogLevel         = LogLevel.Trace;
            InternalLogger.IncludeTimestamp = false;
            {
                StringWriter writer1 = new StringWriter()
                {
                    NewLine = "\n"
                };
                InternalLogger.LogWriter = writer1;

                // Named (based on LogLevel) public methods.
                InternalLogger.Warn("WWW {0}", 0);
                InternalLogger.Error("EEE {0}, {1}", 0, 1);
                InternalLogger.Fatal("FFF {0}, {1}, {2}", 0, 1, 2);
                InternalLogger.Trace("TTT {0}, {1}, {2}", 0, 1, 2);
                InternalLogger.Debug("DDD {0}, {1}", 0, 1);
                InternalLogger.Info("III {0}", 0);

                TestWriter(expected, writer1);
            }
            {
                //
                // Reconfigure the LogWriter.

                StringWriter writer2 = new StringWriter()
                {
                    NewLine = "\n"
                };
                InternalLogger.LogWriter = writer2;

                // Invoke Log(LogLevel, string) for every log level.
                InternalLogger.Log(LogLevel.Warn, "WWW {0}", 0);
                InternalLogger.Log(LogLevel.Error, "EEE {0}, {1}", 0, 1);
                InternalLogger.Log(LogLevel.Fatal, "FFF {0}, {1}, {2}", 0, 1, 2);
                InternalLogger.Log(LogLevel.Trace, "TTT {0}, {1}, {2}", 0, 1, 2);
                InternalLogger.Log(LogLevel.Debug, "DDD {0}, {1}", 0, 1);
                InternalLogger.Log(LogLevel.Info, "III {0}", 0);
                TestWriter(expected, writer2);
            }
        }
Beispiel #7
0
        /// <summary>
        /// Create the mailmessage with the addresses, properties and body.
        /// </summary>
        private MailMessage CreateMailMessage(LogEventInfo lastEvent, string body)
        {
            var msg          = new MailMessage();
            var renderedFrom = this.From == null ? null : this.From.Render(lastEvent);

            if (string.IsNullOrEmpty(renderedFrom))
            {
                throw new NLogRuntimeException(RequiredPropertyIsEmptyFormat, "From");
            }
            msg.From = new MailAddress(renderedFrom);

            var addedTo  = AddAddresses(msg.To, this.To, lastEvent);
            var addedCc  = AddAddresses(msg.CC, this.CC, lastEvent);
            var addedBcc = AddAddresses(msg.Bcc, this.Bcc, lastEvent);

            if (!addedTo && !addedCc && !addedBcc)
            {
                throw new NLogRuntimeException(RequiredPropertyIsEmptyFormat, "To/Cc/Bcc");
            }

            msg.Subject      = this.Subject == null ? string.Empty : this.Subject.Render(lastEvent).Trim();
            msg.BodyEncoding = this.Encoding;
            msg.IsBodyHtml   = this.Html;

            if (this.Priority != null)
            {
                var renderedPriority = this.Priority.Render(lastEvent);
                try
                {
                    msg.Priority = (MailPriority)Enum.Parse(typeof(MailPriority), renderedPriority, true);
                }
                catch
                {
                    InternalLogger.Warn("Could not convert '{0}' to MailPriority, valid values are Low, Normal and High. Using normal priority as fallback.");
                    msg.Priority = MailPriority.Normal;
                }
            }
            msg.Body = body;
            if (msg.IsBodyHtml && ReplaceNewlineWithBrTagInHtml && msg.Body != null)
            {
                msg.Body = msg.Body.Replace(EnvironmentHelper.NewLine, "<br/>");
            }
            return(msg);
        }
Beispiel #8
0
        protected override void Write(AsyncLogEventInfo logEvent)
        {
            GetConnection();
            InternalLogger.Trace("Fluentd (Name={0}): Sending to address: '{1}:{2}'", Name, this.Host, this.Port);
            var record     = new Dictionary <string, string>();
            var logMessage = GetFormattedMessage(logEvent.LogEvent);

            record.Add("message", logMessage);
            try
            {
                this.emitter.Pack(logEvent.LogEvent.TimeStamp, this.Tag, record);
            }
            catch (Exception ex)
            {
                InternalLogger.Warn("Fluentd Emit - " + ex.ToString());

                throw;  // Notify NLog of failure
            }
        }
        private Task ProcessQueueAsync(MessageBuilder messageBuilder, TaskCompletionSource <object> tcs)
        {
            if (token.IsCancellationRequested)
            {
                tcs.SetCanceled();
                return(tcs.Task);
            }

            try
            {
                var asyncLogEventInfo = queue.Take(token);
                var logEventMsgSet    = new LogEventMsgSet(asyncLogEventInfo, buffer, messageBuilder, messageTransmitter);
                logEventMsgSet
                .Build(layout)
                .SendAsync(token)
                .ContinueWith(t =>
                {
                    var exception = t.Exception;
                    if (token.IsCancellationRequested || t.IsCanceled)
                    {
                        InternalLogger.Debug("[Syslog] Task canceled");
                        tcs.SetCanceled();
                        return;
                    }
                    if (exception != null)     // t.IsFaulted is true
                    {
                        InternalLogger.Warn(exception.GetBaseException(), "[Syslog] Task faulted");
                    }
                    else
                    {
                        InternalLogger.Debug("[Syslog] Successfully handled message '{0}'", logEventMsgSet);
                    }
                    ProcessQueueAsync(messageBuilder, tcs);
                }, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Current);

                return(tcs.Task);
            }
            catch (Exception exception)
            {
                tcs.SetException(exception);
                return(tcs.Task);
            }
        }
Beispiel #10
0
        /// <summary>
        /// Writes the specified log event to the wrapped target, retrying and pausing in case of an error.
        /// </summary>
        /// <param name="logEvent">The log event.</param>
        protected override void Write(AsyncLogEventInfo logEvent)
        {
            AsyncContinuation continuation = null;
            int counter = 0;

            continuation = ex =>
            {
                if (ex == null)
                {
                    logEvent.Continuation(null);
                    return;
                }

                int retryNumber = Interlocked.Increment(ref counter);
                InternalLogger.Warn("Error while writing to '{0}': {1}. Try {2}/{3}", WrappedTarget, ex, retryNumber, RetryCount);

                // exceeded retry count
                if (retryNumber >= RetryCount)
                {
                    InternalLogger.Warn("Too many retries. Aborting.");
                    logEvent.Continuation(ex);
                    return;
                }

                // sleep and try again (Check every 100 ms if target have been closed)
                for (int i = 0; i < RetryDelayMilliseconds;)
                {
                    int retryDelay = Math.Min(100, RetryDelayMilliseconds - i);
                    Thread.Sleep(retryDelay);
                    i += retryDelay;
                    if (!IsInitialized)
                    {
                        InternalLogger.Warn("Target closed. Aborting.");
                        logEvent.Continuation(ex);
                        return;
                    }
                }

                WrappedTarget.WriteAsyncLogEvent(logEvent.LogEvent.WithContinuation(continuation));
            };

            WrappedTarget.WriteAsyncLogEvent(logEvent.LogEvent.WithContinuation(continuation));
        }
Beispiel #11
0
        private bool TryLoadLoggingConfiguration(LogFactory logFactory, string configFile, out LoggingConfiguration config)
        {
            try
            {
#if SILVERLIGHT && !WINDOWS_PHONE
                Uri configFileUri = new Uri(configFile, UriKind.Relative);
                if (Application.GetResourceStream(configFileUri) != null)
                {
                    config = LoadXmlLoggingConfiguration(logFactory, configFile);
                    return(true);    // File exists, and maybe the config is valid, stop search
                }
#else
                if (File.Exists(configFile))
                {
                    config = LoadXmlLoggingConfiguration(logFactory, configFile);
                    return(true);    // File exists, and maybe the config is valid, stop search
                }
#endif
            }
            catch (IOException ex)
            {
                InternalLogger.Warn(ex, "Skipping invalid config file location: {0}", configFile);
            }
            catch (UnauthorizedAccessException ex)
            {
                InternalLogger.Warn(ex, "Skipping inaccessible config file location: {0}", configFile);
            }
            catch (SecurityException ex)
            {
                InternalLogger.Warn(ex, "Skipping inaccessible config file location: {0}", configFile);
            }
            catch (Exception ex)
            {
                InternalLogger.Error(ex, "Failed loading from config file location: {0}", configFile);
                if (ex.MustBeRethrown())
                {
                    throw;
                }
            }

            config = null;
            return(false);   // No valid file found
        }
Beispiel #12
0
        /// <summary>
        /// Executes the received command by first parsing it then executing with the parsed values.
        /// </summary>
        /// <param name="command">The command<see cref="string"/></param>
        /// <returns>The <see cref="bool"/></returns>
        private static async Task <bool> ExecuteCommandAsync(string?command)
        {
            if (!InitCompleted)
            {
                Logger.Warn("Shell isn't initiated properly.");
                ShellIO.Error("Shell is offline!");
                return(false);
            }

            if (string.IsNullOrEmpty(command))
            {
                Logger.Trace("Command is null.");
                ShellIO.Error("Command empty or invalid.");
                return(false);
            }

            CurrentCommand = command;
            return(await ParseCommandAsync(command).ConfigureAwait(false));
        }
Beispiel #13
0
 /// <summary>
 /// Prefills command handlers. We cannot do it in runtime because there can be race conditions
 /// during initialization. Much simple just do that once on application start.
 /// </summary>
 protected override void Initialize()
 {
     // Precache all non-generic types with command handlers.
     commandHandlers = Assemblies.SelectMany(a => a.GetTypes())
                       .Where(t =>
                              HandlerSearchMethod == HandlerSearchMethod.ClassAttribute ?
                              t.GetTypeInfo().GetCustomAttribute <CommandHandlersAttribute>() != null :
                              t.Name.EndsWith("Handlers"))
                       .SelectMany(t => t.GetTypeInfo().GetMethods())
                       .Where(m => m.GetParameters().Length > 0)
                       .Where(m => m.Name.StartsWith(HandlerPrefix))
                       .ToArray();
     if (!commandHandlers.Any())
     {
         var assembliesStr = string.Join(",", Assemblies.Select(a => a.FullName));
         InternalLogger.Warn(string.Format(Properties.Strings.NoHandlersInAssembly, assembliesStr),
                             nameof(CommandHandlerLocatorMiddleware));
     }
 }
Beispiel #14
0
        /// <summary>
        /// Handles that scheduled task has completed (succesfully or failed), and starts the next pending task
        /// </summary>
        /// <param name="completedTask">Task just completed</param>
        /// <param name="continuation">AsyncContinuation to notify of success or failure</param>
        private void TaskCompletion(Task completedTask, object continuation)
        {
            try
            {
                if (ReferenceEquals(completedTask, _previousTask))
                {
                    if (TaskTimeoutSeconds > 0)
                    {
                        _taskTimeoutTimer.Change(Timeout.Infinite, Timeout.Infinite);
                    }
                }
                else
                {
                    if (!IsInitialized)
                    {
                        return;
                    }
                }

                if (completedTask.IsCanceled)
                {
                    if (completedTask.Exception != null)
                    {
                        InternalLogger.Warn(completedTask.Exception, "{0} WriteAsyncTask was cancelled", this.Name);
                    }
                    else
                    {
                        InternalLogger.Info("{0} WriteAsyncTask was cancelled", this.Name);
                    }
                }
                else if (completedTask.Exception != null)
                {
                    InternalLogger.Warn(completedTask.Exception, "{0} WriteAsyncTask failed on completion", this.Name);
                }

                var asyncContinuation = (AsyncContinuation)continuation;
                asyncContinuation(completedTask.Exception);
            }
            finally
            {
                TaskStartNext(completedTask);
            }
        }
        private Task ProcessQueueAsync(MessageBuilder messageBuilder, TaskCompletionSource <object> tcs)
        {
            if (token.IsCancellationRequested)
            {
                return(tcs.CanceledTask());
            }

            try
            {
                var asyncLogEventInfo = queue.Take(token);
                SignalFlushCompletionWhenIsMarker(asyncLogEventInfo);
                var logEventMsgSet = new LogEventMsgSet(asyncLogEventInfo, buffer, messageBuilder, messageTransmitter);

                logEventMsgSet
                .Build(layout)
                .SendAsync(token)
                .ContinueWith(t =>
                {
                    if (t.IsCanceled)
                    {
                        InternalLogger.Debug("Task canceled");
                        tcs.SetCanceled();
                        return;
                    }
                    if (t.Exception != null)     // t.IsFaulted is true
                    {
                        InternalLogger.Warn(t.Exception.GetBaseException(), "Task faulted");
                    }
                    else
                    {
                        InternalLogger.Debug("Successfully sent message '{0}'", logEventMsgSet);
                    }
                    ProcessQueueAsync(messageBuilder, tcs);
                }, token, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Current);

                return(tcs.Task);
            }
            catch (Exception exception)
            {
                return(tcs.FailedTask(exception));
            }
        }
Beispiel #16
0
        private void SetupMailMessage(MailMessage msg, LogEventInfo logEvent)
        {
            msg.From = new MailAddress(this.From.Render(logEvent));
            foreach (string mail in this.To.Render(logEvent).Split(';'))
            {
                msg.To.Add(mail);
            }

            if (this.Bcc != null)
            {
                foreach (string mail in this.Bcc.Render(logEvent).Split(';'))
                {
                    msg.Bcc.Add(mail);
                }
            }

            if (this.CC != null)
            {
                foreach (string mail in this.CC.Render(logEvent).Split(';'))
                {
                    msg.CC.Add(mail);
                }
            }

            msg.Subject      = this.Subject.Render(logEvent).Trim();
            msg.BodyEncoding = this.Encoding;
            msg.IsBodyHtml   = this.Html;

            if (this.Priority != null)
            {
                var renderedPriority = this.Priority.Render(logEvent);
                try
                {
                    msg.Priority = (MailPriority)Enum.Parse(typeof(MailPriority), renderedPriority, true);
                }
                catch
                {
                    InternalLogger.Warn("Could not convert '{0}' to MailPriority, valid values are Low, Normal and High. Using normal priority as fallback.");
                    msg.Priority = MailPriority.Normal;
                }
            }
        }
        /// <summary>
        /// Split the string and then compile into list of Rendering formats.
        /// </summary>
        /// <param name="formatSpecifier"></param>
        /// <returns></returns>
        private static List <ExceptionRenderingFormat> CompileFormat(string formatSpecifier)
        {
            List <ExceptionRenderingFormat> formats = new List <ExceptionRenderingFormat>();

            string[] parts = formatSpecifier.Replace(" ", string.Empty).Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);

            foreach (string s in parts)
            {
                ExceptionRenderingFormat renderingFormat;
                if (_formatsMapping.TryGetValue(s, out renderingFormat))
                {
                    formats.Add(renderingFormat);
                }
                else
                {
                    InternalLogger.Warn("Unknown exception data target: {0}", s);
                }
            }
            return(formats);
        }
Beispiel #18
0
        /// <summary>
        /// Renders the inner message, processes it and appends it to the specified <see cref="StringBuilder" />.
        /// </summary>
        /// <param name="builder">The <see cref="StringBuilder"/> to append the rendered data to.</param>
        /// <param name="logEvent">Logging event.</param>
        protected override void Append(StringBuilder builder, LogEventInfo logEvent)
        {
            if (Inner == null)
            {
                InternalLogger.Warn("{0} has no configured Inner-Layout, so skipping", this);
                return;
            }

            int orgLength = builder.Length;

            try
            {
                RenderInnerAndTransform(logEvent, builder, orgLength);
            }
            catch
            {
                builder.Length = orgLength; // Rewind/Truncate on exception
                throw;
            }
        }
Beispiel #19
0
 /// <summary>
 /// Register NLog.Web.AspNetCore, so so &lt;extension&gt; in NLog's config isn't needed.
 /// </summary>
 internal static void RegisterNLogWebAspNetCore()
 {
     try
     {
         InternalLogger.Debug("Registering NLog.Web.AspNetCore");
         ConfigurationItemFactory.Default.RegisterItemsFromAssembly(typeof(AspNetExtensions).GetTypeInfo().Assembly);
     }
     catch (Exception ex)
     {
         InternalLogger.Error(ex, "Registering NLog.Web.AspNetCore failed");
     }
     try
     {
         LogManager.AddHiddenAssembly(typeof(NLogBuilder).GetTypeInfo().Assembly);
     }
     catch (Exception ex)
     {
         InternalLogger.Warn(ex, "Hidding assembly of {0} failed", nameof(NLogBuilder));
     }
 }
Beispiel #20
0
        void ShadePropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            var shade = (Shade)sender;
            var index = _shadesSource.IndexOf(shade);
            if (index < 0)
            {
                InternalLogger.Warn(LogTag, $"ShadePropertyChanged => shade property {e.PropertyName} changed but we can't find the shade in the source");
                return;
            }

            InternalLogger.Debug(LogTag, () => $"ShadePropertyChanged( shadeIndex: {index}, propertyName: {e.PropertyName} )");
            switch (e.PropertyName)
            {
                case nameof(Shade.BlurRadius):
                case nameof(Shade.Color):
                case nameof(Shade.Offset):
                    UpdateGeometry();
                    break;
            }
        }
        private static JsonSerializerSettings CreateJsonSerializerSettings()
        {
            var jsonSerializerSettings = new JsonSerializerSettings {
                ReferenceLoopHandling = ReferenceLoopHandling.Ignore
            };

            jsonSerializerSettings.Converters.Add(new Newtonsoft.Json.Converters.StringEnumConverter());
            jsonSerializerSettings.Converters.Add(new JsonToStringConverter(typeof(System.Reflection.MemberInfo)));
            jsonSerializerSettings.Converters.Add(new JsonToStringConverter(typeof(System.Reflection.Assembly)));
            jsonSerializerSettings.Converters.Add(new JsonToStringConverter(typeof(System.Reflection.Module)));
            jsonSerializerSettings.Error = (sender, args) =>
            {
                InternalLogger.Warn(args.ErrorContext.Error, "GelfConverter: Error serializing property '{0}', property ignored", args.ErrorContext.Member);
                if (!LogManager.ThrowExceptions)
                {
                    args.ErrorContext.Handled = true;
                }
            };
            return(jsonSerializerSettings);
        }
Beispiel #22
0
 private void TryAddGitRevisionId(Protobuf.Collections.MapField <string, string> labels)
 {
     try
     {
         var gitId = DevTools.Source.V1.SourceContext.AppSourceContext?.Git?.RevisionId;
         if (!String.IsNullOrWhiteSpace(gitId))
         {
             labels.Add(DevTools.Source.V1.SourceContext.GitRevisionIdLogLabel, gitId);
         }
     }
     catch (Exception ex) when(
         ex is SecurityException ||
         ex is InvalidProtocolBufferException ||
         ex is InvalidJsonException ||
         ex is UnauthorizedAccessException)
     {
         // This is best-effort only, exceptions from reading/parsing the source_context.json are ignored.
         InternalLogger.Warn(ex, "GoogleStackdriver(Name={0}): Exception at TryAddGitRevisionId", Name);
     }
 }
        private Mutex CreateArchiveMutex()
        {
            try
            {
                return CreateSharableMutex("FileArchiveLock");
            }
            catch (Exception ex)
            {
                if (ex is SecurityException || ex is UnauthorizedAccessException || ex is NotSupportedException || ex is NotImplementedException || ex is PlatformNotSupportedException)
                {
                    InternalLogger.Warn(ex, "Failed to create global archive mutex: {0}", FileName);
                    return new Mutex();
                }

                InternalLogger.Error(ex, "Failed to create global archive mutex: {0}", FileName);
                if (ex.MustBeRethrown())
                    throw;
                return new Mutex();
            }
        }
        private void FindControlAndSendTheMessage(string logMessage)
        {
            Form form = null;

            if (Form.ActiveForm != null)
            {
                form = Form.ActiveForm;
            }

            if (Application.OpenForms[FormName] != null)
            {
                form = Application.OpenForms[FormName];
            }

            if (form == null)
            {
                InternalLogger.Info("Form {0} not found", FormName);
                return;
            }

            Control control = FormHelper.FindControl(ControlName, form);

            if (control == null)
            {
                InternalLogger.Info("Control {0} on Form {1} not found", ControlName, FormName);
                return;
            }
            try
            {
                control.BeginInvoke(new DelSendTheMessageToFormControl(SendTheMessageToFormControl), control, logMessage);
            }
            catch (Exception ex)
            {
                InternalLogger.Warn(ex.ToString());

                if (LogManager.ThrowExceptions)
                {
                    throw;
                }
            }
        }
Beispiel #25
0
        private static ExceptionDataTarget[] CompileFormat(string formatSpecifier)
        {
            string[] parts       = formatSpecifier.Replace(" ", string.Empty).Split(',');
            var      dataTargets = new List <ExceptionDataTarget>();

            foreach (string s in parts)
            {
                switch (s.ToUpper(CultureInfo.InvariantCulture))
                {
                case "MESSAGE":
                    dataTargets.Add(AppendMessage);
                    break;

                case "TYPE":
                    dataTargets.Add(AppendType);
                    break;

                case "SHORTTYPE":
                    dataTargets.Add(AppendShortType);
                    break;

                case "TOSTRING":
                    dataTargets.Add(AppendToString);
                    break;

                case "METHOD":
                    dataTargets.Add(AppendMethod);
                    break;

                case "STACKTRACE":
                    dataTargets.Add(AppendStackTrace);
                    break;

                default:
                    InternalLogger.Warn("Unknown exception data target: {0}", s);
                    break;
                }
            }

            return(dataTargets.ToArray());
        }
Beispiel #26
0
        private void CompileFormat(string format)
        {
            string[]  parts       = format.Replace(" ", "").Split(',');
            ArrayList dataTargets = new ArrayList();

            foreach (string s in parts)
            {
                switch (s.ToLower())
                {
                case "message":
                    dataTargets.Add(new ExceptionDataTarget(AppendMessage));
                    break;

                case "type":
                    dataTargets.Add(new ExceptionDataTarget(AppendType));
                    break;

                case "shorttype":
                    dataTargets.Add(new ExceptionDataTarget(AppendShortType));
                    break;

                case "tostring":
                    dataTargets.Add(new ExceptionDataTarget(AppendToString));
                    break;

#if !NETCF
                case "stacktrace":
                    dataTargets.Add(new ExceptionDataTarget(AppendStackTrace));
                    break;

                case "method":
                    dataTargets.Add(new ExceptionDataTarget(AppendMethod));
                    break;
#endif
                default:
                    InternalLogger.Warn("Unknown exception data target: {0}", s);
                    break;
                }
            }
            _exceptionDataTargets = (ExceptionDataTarget[])dataTargets.ToArray(typeof(ExceptionDataTarget));
        }
Beispiel #27
0
 /// <summary>
 /// Closes this instance.
 /// </summary>
 public override void Close()
 {
     InternalLogger.Trace("Closing '{0}'", FileName);
     try
     {
         if (fileStream != null)
         {
             fileStream.Dispose();
         }
     }
     catch (Exception ex)
     {
         InternalLogger.Warn(ex, "Failed to close file '{0}'", FileName);
         System.Threading.Thread.Sleep(1);   // Artificial delay to avoid hammering a bad file location
     }
     finally
     {
         fileStream = null;
     }
     FileTouched();
 }
Beispiel #28
0
        internal ILokiTransport GetLokiTransport(Layout endpoint)
        {
            var endpointUri = RenderLogEvent(endpoint, LogEventInfo.CreateNullEvent());

            if (Uri.TryCreate(endpointUri, UriKind.Absolute, out var uri))
            {
                if (uri.Scheme == Uri.UriSchemeHttp || uri.Scheme == Uri.UriSchemeHttps)
                {
                    var lokiHttpClient    = LokiHttpClientFactory(uri);
                    var httpLokiTransport = new HttpLokiTransport(uri, lokiHttpClient);

                    return(httpLokiTransport);
                }
            }

            InternalLogger.Warn("Unable to create a valid Loki Endpoint URI from '{0}'", endpoint);

            var nullLokiTransport = new NullLokiTransport();

            return(nullLokiTransport);
        }
Beispiel #29
0
        /// <summary>
        /// Write to output
        /// </summary>
        /// <param name="textLine">text to be written.</param>
        private void WriteToOutput(string textLine)
        {
            if (_pauseLogging)
            {
                return;
            }

            var output = GetOutput();

            try
            {
                output.WriteLine(textLine);
            }
            catch (IndexOutOfRangeException ex)
            {
                //this is a bug and therefor stopping logging. For docs, see PauseLogging property
                _pauseLogging = true;
                InternalLogger.Warn(ex, "An IndexOutOfRangeException has been thrown and this is probably due to a race condition." +
                                    "Logging to the console will be paused. Enable by reloading the config or re-initialize the targets");
            }
        }
Beispiel #30
0
        /// <summary>
        /// Creates the file stream.
        /// </summary>
        /// <param name="allowFileSharedWriting">If set to <c>true</c> sets the file stream to allow shared writing.</param>
        /// <returns>A <see cref="FileStream"/> object which can be used to write to the file.</returns>
        protected FileStream CreateFileStream(bool allowFileSharedWriting)
        {
            int currentDelay = this.CreateFileParameters.ConcurrentWriteAttemptDelay;

            InternalLogger.Trace("Opening {0} with allowFileSharedWriting={1}", this.FileName, allowFileSharedWriting);
            for (int i = 0; i < this.CreateFileParameters.ConcurrentWriteAttempts; ++i)
            {
                try
                {
                    try
                    {
                        return(this.TryCreateFileStream(allowFileSharedWriting));
                    }
                    catch (DirectoryNotFoundException)
                    {
                        if (!this.CreateFileParameters.CreateDirs)
                        {
                            throw;
                        }

                        Directory.CreateDirectory(Path.GetDirectoryName(this.FileName));
                        return(this.TryCreateFileStream(allowFileSharedWriting));
                    }
                }
                catch (IOException)
                {
                    if (!this.CreateFileParameters.ConcurrentWrites || i + 1 == this.CreateFileParameters.ConcurrentWriteAttempts)
                    {
                        throw; // rethrow
                    }

                    int actualDelay = this.random.Next(currentDelay);
                    InternalLogger.Warn("Attempt #{0} to open {1} failed. Sleeping for {2}ms", i, this.FileName, actualDelay);
                    currentDelay *= 2;
                    System.Threading.Thread.Sleep(actualDelay);
                }
            }

            throw new InvalidOperationException("Should not be reached.");
        }