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

            InternalLogger.LogLevel         = LogLevel.Trace;
            InternalLogger.IncludeTimestamp = false;
            InternalLogger.LogToConsole     = true;

            {
                StringWriter consoleOutWriter1 = new StringWriter()
                {
                    NewLine = "\n"
                };

                // Redirect the console output to a StringWriter.
                Console.SetOut(consoleOutWriter1);

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

                TestWriter(expected, consoleOutWriter1);
            }

            //
            // Redirect the console output to another StringWriter.
            {
                StringWriter consoleOutWriter2 = new StringWriter()
                {
                    NewLine = "\n"
                };
                Console.SetOut(consoleOutWriter2);

                // Invoke Log(LogLevel, string) for every log level.
                InternalLogger.Log(LogLevel.Warn, "WWW");
                InternalLogger.Log(LogLevel.Error, "EEE");
                InternalLogger.Log(LogLevel.Fatal, "FFF");
                InternalLogger.Log(LogLevel.Trace, "TTT");
                InternalLogger.Log(LogLevel.Debug, "DDD");
                InternalLogger.Log(LogLevel.Info, "III");

                TestWriter(expected, consoleOutWriter2);
            }
        }
        private void WriteLogEntries(IList <LogEntry> logEntries, object continuationList)
        {
            bool withinTaskLimit = Interlocked.Increment(ref _pendingTaskCount) <= TaskPendingLimit;

            try
            {
                if (!withinTaskLimit)
                {
                    // The task queue has become too long. We will throttle, and wait for the task-queue to become shorter
                    InternalLogger.Debug("GoogleStackdriver(Name={0}): Throttle started because {1} tasks are pending", Name, _pendingTaskCount);
                    for (int i = -100; i < TimeoutSeconds * 1000; i += 100)
                    {
                        withinTaskLimit = _prevTask?.Wait(100, _cancelTokenSource.Token) ?? true; // Throttle
                        if (withinTaskLimit)
                        {
                            _pendingTaskCount = 1;  // All pending tasks has completed
                            break;
                        }
                        if (Interlocked.Read(ref _pendingTaskCount) < TaskPendingLimit)
                        {
                            withinTaskLimit = true;  // Some pending tasks has completed
                            break;
                        }
                    }
                    if (!withinTaskLimit)
                    {
                        // The tasks queue is not moving. We start a new task queue and ignores the old one
                        InternalLogger.Info("GoogleStackdriver(Name={0}): Throttle timeout but {1} tasks are still pending", Name, _pendingTaskCount);
                    }
                }

                if (withinTaskLimit && _prevTask != null)
                {
                    _prevTask = _prevTask.ContinueWith(_writeLogEntriesBegin, logEntries, _cancelTokenSource.Token);
                }
                else
                {
                    _prevTask = WriteLogEntriesBegin(null, logEntries);
                }

                _prevTask = _prevTask.ContinueWith(_writeLogEntriesCompleted, continuationList);
            }
            catch (Exception ex)
            {
                Interlocked.Decrement(ref _pendingTaskCount);
                InternalLogger.Error(ex, "GoogleStackdriver(Name={0}): Failed to begin writing {1} LogEntries", Name, logEntries.Count);
                throw;
            }
        }
Example #3
0
        public ShadowView(Context context, View shadowSource, float cornerRadius, string tag = null)
            : base(context)
        {
            _renderScript = RenderScript.Create(context);
            _weakSource   = new JniWeakReference <View>(shadowSource);

            _cache = BitmapCache.Instance;

            _shadeInfos   = new Dictionary <Shade, ShadeInfo>();
            _cornerRadius = cornerRadius;

            LogTag = !string.IsNullOrEmpty(tag) ? $"{nameof(ShadowView)}@{tag}" : nameof(ShadowView);

            InternalLogger.Debug(LogTag, () => $"ShadowView(): {++instanceCount} instances");
        }
Example #4
0
        protected override void OnLayout(bool changed, int l, int t, int r, int b)
        {
            base.OnLayout(changed, l, t, r, b);

            InternalLogger.Debug(_tag, () => $"OnLayout( {l}l, {t}t, {r}r, {b}b )");

            var children = GetChildAt(1);

            if (children == null)
            {
                return;
            }

            _shadowView?.Layout(children.MeasuredWidth, children.MeasuredHeight);
        }
        public void Log()
        {
            lock (_cacheLock)
            {
                var stringBuilder = new StringBuilder();
                stringBuilder.AppendLine();
                stringBuilder.AppendLine($"BitmapCache: {_cache.Count} bitmaps");
                foreach (var keyValue in _cache)
                {
                    stringBuilder.AppendLine($"    {keyValue.Key}:{keyValue.Value.ReferenceCount:00}");
                }

                InternalLogger.Debug(LogTag, () => stringBuilder.ToString());
            }
        }
Example #6
0
        private void DisposeBitmap(Shade shade)
        {
#if DEBUG
            var stopWatch = new Stopwatch();
            stopWatch.Start();
#endif
            InternalLogger.Debug(LogTag, () => $"DisposeBitmap( shade: {shade} )");
            var shadeInfo = _shadeInfos[shade];
            _shadeInfos.Remove(shade);

            _cache.Remove(shadeInfo.Hash);
#if DEBUG
            LogPerf(LogTag, stopWatch);
#endif
        }
        public Bitmap Add(string hash, Func <Bitmap> create)
        {
            InternalLogger.Debug(LogTag, () => $"Add( hash: {hash} )");
            lock (_cacheLock)
            {
                if (_cache.TryGetValue(hash, out var bucket))
                {
                    bucket.ReferenceCount++;
                    InternalLogger.Debug(LogTag, () => $"Reference count: {bucket.ReferenceCount}");
                    return(bucket.Value);
                }

                return(Create(hash, create));
            }
        }
        /// <summary>
        /// Renders the specified ASP.NET Session value 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 DoAppend(StringBuilder builder, LogEventInfo logEvent)
        {
            if (this.Variable == null)
            {
                return;
            }

            var context = HttpContextAccessor.HttpContext;

            if (context?.Session == null)
            {
                InternalLogger.Debug("Session is null");
                return;
            }
#if !ASP_NET_CORE
            var value = PropertyReader.GetValue(Variable, k => context.Session[k], EvaluateAsNestedProperties);
#else
            if (context.Items == null || context.Features.Get <ISessionFeature>()?.Session == null)
            {
                return;
            }

            //because session.get / session.getstring also creating log messages in some cases, this could lead to stackoverflow issues.
            //We remember on the context.Items that we are looking up a session value so we prevent stackoverflows
            if (context.Items.ContainsKey(NLogRetrievingSessionValue))
            {
                return;
            }

            context.Items[NLogRetrievingSessionValue] = true;
            object value;
            try
            {
                value = PropertyReader.GetValue(Variable, k => context.Session.GetString(k), EvaluateAsNestedProperties);
            }
            catch (Exception ex)
            {
                InternalLogger.Warn(ex, "Retrieving session value failed. ");
                return;
            }
            finally
            {
                context.Items.Remove(NLogRetrievingSessionValue);
            }
#endif
            var formatProvider = GetFormatProvider(logEvent, Culture);
            builder.Append(Convert.ToString(value, formatProvider));
        }
Example #9
0
 private bool TaskCreation(AsyncLogEventInfo logEvent)
 {
     try
     {
         if (_cancelTokenSource.IsCancellationRequested)
         {
             logEvent.Continuation(null);
             return(false);
         }
         if (logEvent.LogEvent == null)
         {
             InternalLogger.Debug("{0} Flush Completed", this.Name);
             logEvent.Continuation(null);
             return(false);
         }
         var newTask = WriteAsyncTask(logEvent.LogEvent, _cancelTokenSource.Token);
         if (newTask == null)
         {
             InternalLogger.Debug("{0} WriteAsync returned null", this.Name);
         }
         else
         {
             lock (this.SyncRoot)
             {
                 _previousTask = newTask;
                 _previousTask.ContinueWith(_taskCompletion, logEvent.Continuation, _cancelTokenSource.Token);
                 if (_previousTask.Status == TaskStatus.Created)
                 {
                     _previousTask.Start(TaskScheduler.Default);
                 }
             }
             return(true);
         }
     }
     catch (Exception ex)
     {
         try
         {
             InternalLogger.Error(ex, "{0} WriteAsync failed on creation", this.Name);
             logEvent.Continuation(ex);
         }
         catch
         {
             // Don't wanna die
         }
     }
     return(false);
 }
Example #10
0
        protected override void Write(LogEventInfo logEvent)
        {
            if (logEvent == null || logEvent.Exception == null)
            {
                return;
            }

            InternalLogger.Debug("Sending Exception to api.exceptron.com. Process Name: {0}", Process.GetCurrentProcess().ProcessName);

            try
            {
                var exceptionData = new ExceptionData
                {
                    Exception = logEvent.Exception,
                    Component = logEvent.LoggerName,
                    Message   = logEvent.FormattedMessage,
                };

                if (UserId != null)
                {
                    exceptionData.UserId = UserId.Render(logEvent);
                }

                if (logEvent.Level <= LogLevel.Info)
                {
                    exceptionData.Severity = ExceptionSeverity.None;
                }
                else if (logEvent.Level <= LogLevel.Warn)
                {
                    exceptionData.Severity = ExceptionSeverity.Warning;
                }
                else if (logEvent.Level <= LogLevel.Error)
                {
                    exceptionData.Severity = ExceptionSeverity.Error;
                }
                else if (logEvent.Level <= LogLevel.Fatal)
                {
                    exceptionData.Severity = ExceptionSeverity.Fatal;
                }

                ExceptronClient.SubmitException(exceptionData);
            }
            catch (Exception e)
            {
                InternalLogger.Warn("Unable to report exception. {0}", e);
                throw;
            }
        }
Example #11
0
        /// <summary>
        /// (re-)create a event source, if it isn't there. Works only with fixed sourcenames.
        /// </summary>
        /// <param name="fixedSource">sourcenaam. If source is not fixed (see <see cref="SimpleLayout.IsFixedText"/>, then pass <c>null</c> or emptystring.</param>
        /// <param name="alwaysThrowError">always throw an Exception when there is an error</param>
        private void CreateEventSourceIfNeeded(string fixedSource, bool alwaysThrowError)
        {
            if (string.IsNullOrEmpty(fixedSource))
            {
                InternalLogger.Debug("Skipping creation of event source because it contains layout renderers");
                //we can only create event sources if the source is fixed (no layout)
                return;
            }

            // if we throw anywhere, we remain non-operational
            try
            {
                if (EventLog.SourceExists(fixedSource, this.MachineName))
                {
                    string currentLogName = EventLog.LogNameFromSourceName(fixedSource, this.MachineName);
                    if (!currentLogName.Equals(this.Log, StringComparison.CurrentCultureIgnoreCase))
                    {
                        // re-create the association between Log and Source
                        EventLog.DeleteEventSource(fixedSource, this.MachineName);
                        var eventSourceCreationData = new EventSourceCreationData(fixedSource, this.Log)
                        {
                            MachineName = this.MachineName
                        };

                        EventLog.CreateEventSource(eventSourceCreationData);
                    }
                }
                else
                {
                    var eventSourceCreationData = new EventSourceCreationData(fixedSource, this.Log)
                    {
                        MachineName = this.MachineName
                    };

                    EventLog.CreateEventSource(eventSourceCreationData);
                }
            }
            catch (Exception exception)
            {
                InternalLogger.Error("Error when connecting to EventLog: {0}", exception);
                if (alwaysThrowError || exception.MustBeRethrown())
                {
                    throw;
                }

                throw;
            }
        }
        private bool TryLoadLoggingConfiguration(LogFactory logFactory, string configFile, out LoggingConfiguration config)
        {
            try
            {
#if SILVERLIGHT && !WINDOWS_PHONE
                Uri configFileUri      = new Uri(configFile, UriKind.Relative);
                var streamResourceInfo = Application.GetResourceStream(configFileUri);
                if (streamResourceInfo != null)
                {
                    InternalLogger.Debug("Loading config from Resource {0}", configFileUri);
                    using (var xmlReader = XmlReader.Create(streamResourceInfo.Stream))
                    {
                        config = LoadXmlLoggingConfiguration(xmlReader, null, logFactory);
                        return(true);
                    }
                }
#else
                if (_appEnvironment.FileExists(configFile))
                {
                    config = LoadXmlLoggingConfigurationFile(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
        }
Example #13
0
        public void TestNotEquals()
        {
            var logEvent1           = new LogEventInfo(LogLevel.Debug, "logger1", "message1");
            AsyncContinuation cont1 = new AsyncContinuation(exception => { });
            AsyncContinuation cont2 = new AsyncContinuation(exception => { InternalLogger.Debug("test"); });
            var async1 = new AsyncLogEventInfo(logEvent1, cont1);
            var async2 = new AsyncLogEventInfo(logEvent1, cont2);

            Assert.False(async1.Equals(async2));
            Assert.False(async1 == async2);
            Assert.True(async1 != async2);

            //2 delegates will return the same hashcode, https://stackoverflow.com/questions/6624151/why-do-2-delegate-instances-return-the-same-hashcode
            //and that isn't really bad, so ignore this
            //   Assert.NotEqual(async1.GetHashCode(), async2.GetHashCode());
        }
Example #14
0
        protected override void OnSizeChanged(int w, int h, int oldw, int oldh)
        {
            base.OnSizeChanged(w, h, oldw, oldh);

            if (w <= MinimumSize || h <= MinimumSize)
            {
                return;
            }

            if (_weakSource.TryGetTarget(out var source) && (w != oldw || h != oldh))
            {
                InternalLogger.Debug(LogTag, () => $"OnSizeChanged( {source.MeasuredWidth}w, {source.MeasuredHeight}h )");

                RefreshBitmaps();
            }
        }
Example #15
0
        /// <summary>
        /// Registers the specified target object under a given name.
        /// </summary>
        /// <param name="name">
        /// Name of the target.
        /// </param>
        /// <param name="target">
        /// The target object.
        /// </param>
        /// <exception cref="ArgumentException">when <paramref name="name"/> is <see langword="null"/></exception>
        /// <exception cref="ArgumentNullException">when <paramref name="target"/> is <see langword="null"/></exception>
        public void AddTarget(string name, Target target)
        {
            if (name == null)
            {
                // TODO: NLog 5 - The ArgumentException should be changed to ArgumentNullException for name parameter.
                throw new ArgumentException("Target name cannot be null", "name");
            }

            if (target == null)
            {
                throw new ArgumentNullException("target");
            }

            InternalLogger.Debug("Registering target {0}: {1}", name, target.GetType().FullName);
            _targets[name] = target;
        }
        protected override void OnAttachedToWindow()
        {
            InternalLogger.Debug($"BlurView@{GetHashCode()}", $"OnAttachedToWindow()");
            base.OnAttachedToWindow();

            var mDecorView = GetRootView();

            if (mDecorView == null)
            {
                SetRootView(GetActivityDecorView());
            }
            else
            {
                OnAttached(mDecorView);
            }
        }
Example #17
0
        /// <summary>
        /// Renders the ASP.NET Session ID 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 DoAppend(StringBuilder builder, LogEventInfo logEvent)
        {
            var context = HttpContextAccessor.HttpContext;

            if (context?.Session == null)
            {
                InternalLogger.Debug("aspnet-sessionid - HttpContext Session is null");
                return;
            }

#if !ASP_NET_CORE
            builder.Append(context.Session.SessionID);
#else
            builder.Append(context.Session.Id);
#endif
        }
Example #18
0
 /// <summary>
 /// Closes all targets and releases any unmanaged resources.
 /// </summary>
 public void Close()
 {
     InternalLogger.Debug("Closing logging configuration...");
     foreach (Target target in _aliveTargets)
     {
         try
         {
             InternalLogger.Debug("Closing target {1} ({0})", target.Name, target.GetType().FullName);
             target.Close();
         }
         catch (Exception ex)
         {
             InternalLogger.Error("Error while closing target: {0} {1}", target.Name, ex);
         }
     }
 }
        private void CreateShadowController(UIView shadowSource, Shadows formsElement)
        {
            Layer.BackgroundColor = new CGColor(0, 0, 0, 0);
            Layer.MasksToBounds   = false;

            _shadowsLayer = new CALayer {
                MasksToBounds = false
            };
            Layer.InsertSublayer(_shadowsLayer, 0);

            _shadowsController = new iOSShadowsController(shadowSource, _shadowsLayer, formsElement.CornerRadius);
            _shadowsController.UpdateShades(formsElement.Shades);

            instanceCount++;
            InternalLogger.Debug(_tag, () => $"Create ShadowView => {instanceCount} instances");
        }
Example #20
0
 private static void SafeAddHiddenAssembly(string assemblyName, bool logOnException = true)
 {
     try
     {
         InternalLogger.Trace("Hide {0}", assemblyName);
         var assembly = Assembly.Load(new AssemblyName(assemblyName));
         LogManager.AddHiddenAssembly(assembly);
     }
     catch (Exception ex)
     {
         if (logOnException)
         {
             InternalLogger.Debug(ex, "Hiding assembly {0} failed. This could influence the ${callsite}", assemblyName);
         }
     }
 }
Example #21
0
 private void WriteDebugMessages(string message, Exception e)
 {
     message = LE + message;
     if (!this.Debug)
     {
         return;
     }
     string[] messages = { message, e.ToString() };
     foreach (var msg in messages)
     {
         System.Diagnostics.Debug.WriteLine(msg);
         Console.Error.WriteLine(msg);
         //Log to NLog's internal logger also
         InternalLogger.Debug(msg);
     }
 }
        /// <summary>
        /// Builds the default configuration item factory.
        /// </summary>
        /// <returns>Default factory.</returns>
        private static ConfigurationItemFactory BuildDefaultFactory()
        {
            var nlogAssembly = typeof(ILogger).Assembly;
            var factory      = new ConfigurationItemFactory(nlogAssembly);

            factory.RegisterExtendedItems();
#if !SILVERLIGHT
            var assemblyLocation = Path.GetDirectoryName(new Uri(nlogAssembly.CodeBase).LocalPath);
            if (assemblyLocation == null)
            {
                InternalLogger.Warn("No auto loading because Nlog.dll location is unknown");
                return(factory);
            }

            var extensionDlls = Directory.GetFiles(assemblyLocation, "NLog*.dll")
                                .Select(Path.GetFileName)
                                .Where(x => !x.Equals("NLog.dll", StringComparison.OrdinalIgnoreCase))
                                .Where(x => !x.Equals("NLog.UnitTests.dll", StringComparison.OrdinalIgnoreCase))
                                .Where(x => !x.Equals("NLog.Extended.dll", StringComparison.OrdinalIgnoreCase))
                                .Select(x => Path.Combine(assemblyLocation, x));

            InternalLogger.Debug("Start auto loading, location: {0}", assemblyLocation);
            foreach (var extensionDll in extensionDlls)
            {
                InternalLogger.Info("Auto loading assembly file: {0}", extensionDll);
                var success = false;
                try
                {
                    var extensionAssembly = Assembly.LoadFrom(extensionDll);
                    InternalLogger.LogAssemblyVersion(extensionAssembly);
                    factory.RegisterItemsFromAssembly(extensionAssembly);
                    success = true;
                }
                catch (Exception)
                {
                    InternalLogger.Warn("Auto loading assembly file: {0} failed! Skipping this file.", extensionDll);
                }
                if (success)
                {
                    InternalLogger.Info("Auto loading assembly file: {0} succeeded!", extensionDll);
                }
            }
            InternalLogger.Debug("Auto loading done");
#endif

            return(factory);
        }
Example #23
0
        private bool TryGetBody(HttpRequest httpRequest, long?contentLength, out Stream body)
        {
            body = null;
            if (contentLength <= 0)
            {
                return(false);
            }

            if (MaxContentLength > 0 && contentLength > MaxContentLength)
            {
                InternalLogger.Debug("AspNetRequestPostedBody: body stream is too big. ContentLength={0}", contentLength);
                return(false);
            }

            body = GetBodyStream(httpRequest);

            if (body == null)
            {
                InternalLogger.Debug("AspNetRequestPostedBody: body stream was null");
                return(false);
            }

            if (!body.CanRead)
            {
                InternalLogger.Debug("AspNetRequestPostedBody: body stream has been closed");
                return(false);
            }

            if (!body.CanSeek)
            {
                if (!TryEnableBuffering(httpRequest, contentLength, out body))
                {
                    return(false);
                }
            }
            else
            {
                if (MaxContentLength > 0 && !contentLength.HasValue && body.Length > MaxContentLength)
                {
                    InternalLogger.Debug("AspNetRequestPostedBody: body stream too big. Body.Length={0}", body.Length);
                    body = null;
                    return(false);
                }
            }

            return(true);
        }
Example #24
0
        /// <summary>
        /// Enqueues another item. If the queue is overflown the appropriate
        /// action is taken as specified by <see cref="OnOverflow"/>.
        /// </summary>
        /// <param name="logEventInfo">The log event info.</param>
        /// <returns>Queue was empty before enqueue</returns>
        public bool Enqueue(AsyncLogEventInfo logEventInfo)
        {
            lock (this)
            {
                if (this.logEventInfoQueue.Count >= this.RequestLimit)
                {
                    InternalLogger.Debug("Async queue is full");
                    switch (this.OnOverflow)
                    {
                    case AsyncTargetWrapperOverflowAction.Discard:
                        InternalLogger.Debug("Discarding one element from queue");
                        var dequeued = this.logEventInfoQueue.Dequeue();
                        if (BufferOverflowed != null)
                        {
                            BufferOverflowed.Invoke(this.OnOverflow, this.RequestLimit, this.logEventInfoQueue.Count, dequeued);
                        }
                        break;

                    case AsyncTargetWrapperOverflowAction.Grow:
                        InternalLogger.Debug("The overflow action is Grow, adding element anyway");
                        if (BufferOverflowed != null)
                        {
                            BufferOverflowed.Invoke(this.OnOverflow, this.RequestLimit, this.logEventInfoQueue.Count, logEventInfo);
                        }
                        break;

                    case AsyncTargetWrapperOverflowAction.Block:
                        while (this.logEventInfoQueue.Count >= this.RequestLimit)
                        {
                            InternalLogger.Debug("Blocking because the overflow action is Block...");
                            if (BufferOverflowed != null)
                            {
                                BufferOverflowed.Invoke(this.OnOverflow, this.RequestLimit, this.logEventInfoQueue.Count, logEventInfo);
                            }
                            System.Threading.Monitor.Wait(this);
                            InternalLogger.Trace("Entered critical section.");
                        }

                        InternalLogger.Trace("Limit ok.");
                        break;
                    }
                }

                this.logEventInfoQueue.Enqueue(logEventInfo);
                return(this.logEventInfoQueue.Count == 1);
            }
        }
        protected override void Write(LogEventInfo logEvent)
        {
            var connectionString = ConnectionString.Render(logEvent);

            if (_client == null || !string.Equals(_connectionString, connectionString, System.StringComparison.OrdinalIgnoreCase))
            {
                _client = CloudStorageAccount.Parse(connectionString).CreateCloudBlobClient();
                InternalLogger.Debug("Initialized connection to {0}", connectionString);
            }

            string containerName = Container.Render(logEvent);
            string blobName      = BlobName.Render(logEvent);

            if (_container == null || _container.Name != containerName)
            {
                _container = _client.GetContainerReference(containerName);
                InternalLogger.Debug("Got container reference to {0}", containerName);

                if (_container.CreateIfNotExists())
                {
                    InternalLogger.Debug("Created container {0}", containerName);
                }

                _blob = null;
            }

            if (_blob == null || _blob.Name != blobName)
            {
                _blob = _container.GetAppendBlobReference(blobName);

                if (!_blob.Exists())
                {
                    try
                    {
                        _blob.Properties.ContentType = "text/plain";
                        _blob.CreateOrReplace(AccessCondition.GenerateIfNotExistsCondition());
                        InternalLogger.Debug("Created blob: {0}", blobName);
                    }
                    catch (StorageException ex) when(ex.RequestInformation.HttpStatusCode == (int)HttpStatusCode.Conflict)
                    {
                        // to be expected
                    }
                }
            }

            _blob.AppendText(Layout.Render(logEvent) + "\r\n", Encoding.UTF8);
        }
        private void ParseIncludeElement(NLogXmlElement includeElement, string baseDirectory, bool autoReloadDefault)
        {
            includeElement.AssertName("include");

            string newFileName = includeElement.GetRequiredAttribute("file");

            try
            {
                newFileName = this.ExpandSimpleVariables(newFileName);
                newFileName = SimpleLayout.Evaluate(newFileName);
                if (baseDirectory != null)
                {
                    newFileName = Path.Combine(baseDirectory, newFileName);
                }

#if SILVERLIGHT
                newFileName = newFileName.Replace("\\", "/");
                if (Application.GetResourceStream(new Uri(newFileName, UriKind.Relative)) != null)
#else
                if (File.Exists(newFileName))
#endif
                {
                    InternalLogger.Debug("Including file '{0}'", newFileName);
                    this.ConfigureFromFile(newFileName, autoReloadDefault);
                }
                else
                {
                    throw new FileNotFoundException("Included file not found: " + newFileName);
                }
            }
            catch (Exception exception)
            {
                InternalLogger.Error(exception, "Error when including '{0}'.", newFileName);

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

                if (includeElement.GetOptionalBooleanAttribute("ignoreErrors", false))
                {
                    return;
                }

                throw new NLogConfigurationException("Error when including: " + newFileName, exception);
            }
        }
Example #27
0
        public void ExceptionTests()
        {
            using (new InternalLoggerScope())
            {
                InternalLogger.LogLevel         = LogLevel.Trace;
                InternalLogger.LogToConsole     = true;
                InternalLogger.IncludeTimestamp = false;

                var ex1 = new Exception("e1");
                var ex2 = new Exception("e2", new Exception("inner"));
                var ex3 = new NLogConfigurationException("config error");
                var ex4 = new NLogConfigurationException("config error", ex2);
                var ex5 = new PathTooLongException();
                ex5.Data["key1"] = "value1";
                Exception ex6 = null;

                const string prefix   = " Exception: ";
                string       expected =
                    "Warn WWW" + prefix + ex1 + Environment.NewLine +
                    "Error EEE" + prefix + ex2 + Environment.NewLine +
                    "Fatal FFF" + prefix + ex3 + Environment.NewLine +
                    "Trace TTT" + prefix + ex4 + Environment.NewLine +
                    "Debug DDD" + prefix + ex5 + Environment.NewLine +
                    "Info III" + Environment.NewLine;

                StringWriter consoleOutWriter = new StringWriter()
                {
                    NewLine = Environment.NewLine
                };

                // Redirect the console output to a StringWriter.
                Console.SetOut(consoleOutWriter);

                // Named (based on LogLevel) public methods.

                InternalLogger.Warn(ex1, "WWW");
                InternalLogger.Error(ex2, "EEE");
                InternalLogger.Fatal(ex3, "FFF");
                InternalLogger.Trace(ex4, "TTT");
                InternalLogger.Debug(ex5, "DDD");
                InternalLogger.Info(ex6, "III");

                consoleOutWriter.Flush();
                var strings = consoleOutWriter.ToString();
                Assert.Equal(expected, strings);
            }
        }
Example #28
0
        /// <summary>
        /// Initializes a new instance of the <see cref="BaseMutexFileAppender" /> class.
        /// </summary>
        /// <param name="fileName">Name of the file.</param>
        /// <param name="createParameters">The create parameters.</param>
        protected BaseMutexFileAppender(string fileName, ICreateFileParameters createParameters)
            : base(fileName, createParameters)
        {
            if (createParameters.IsArchivingEnabled)
            {
                if (PlatformDetector.SupportsSharableMutex)
                {
#if SupportsMutex
                    ArchiveMutex = CreateArchiveMutex();
#endif
                }
                else
                {
                    InternalLogger.Debug("Mutex for file archive not supported");
                }
            }
        }
        /// <summary>
        /// Enqueues another item. If the queue is overflown the appropriate
        /// action is taken as specified by <see cref="AsyncRequestQueueBase.OnOverflow"/>.
        /// </summary>
        /// <param name="logEventInfo">The log event info.</param>
        /// <returns>Queue was empty before enqueue</returns>
        public override bool Enqueue(AsyncLogEventInfo logEventInfo)
        {
            long currentCount  = Interlocked.Increment(ref _count);
            bool queueWasEmpty = currentCount == 1;  // Inserted first item in empty queue

            if (currentCount > RequestLimit)
            {
                InternalLogger.Debug("Async queue is full");
                switch (OnOverflow)
                {
                case AsyncTargetWrapperOverflowAction.Discard:
                {
                    do
                    {
                        if (_logEventInfoQueue.TryDequeue(out var lostItem))
                        {
                            InternalLogger.Debug("Discarding one element from queue");
                            queueWasEmpty = Interlocked.Decrement(ref _count) == 1 || queueWasEmpty;
                            OnLogEventDropped(lostItem.LogEvent);
                            break;
                        }
                        currentCount  = Interlocked.Read(ref _count);
                        queueWasEmpty = true;
                    } while (currentCount > RequestLimit);
                }
                break;

                case AsyncTargetWrapperOverflowAction.Block:
                {
                    WaitForBelowRequestLimit();
                    queueWasEmpty = true;
                }
                break;

                case AsyncTargetWrapperOverflowAction.Grow:
                {
                    InternalLogger.Debug("The overflow action is Grow, adding element anyway");
                    OnLogEventQueueGrows(currentCount);
                    RequestLimit *= 2;
                }
                break;
                }
            }
            _logEventInfoQueue.Enqueue(logEventInfo);
            return(queueWasEmpty);
        }
 internal static HttpRequestBase TryGetRequest(this HttpContextBase context)
 {
     try
     {
         var request = context?.Request;
         if (request == null)
         {
             InternalLogger.Debug("HttpContext Request Lookup returned null");
         }
         return(request);
     }
     catch (HttpException ex)
     {
         InternalLogger.Debug(ex, "HttpContext Request Lookup failed.");
         return(null);
     }
 }