コード例 #1
0
        public void WriteToStringWriterWithArgsTests()
        {
            try
            {
                // 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);
                }
            }
            finally
            {
                InternalLogger.Reset();
            }
        }
コード例 #2
0
        /// <summary>
        /// Used to (re)initialize target when attaching it to another RTB control
        /// </summary>
        /// <param name="form">form owning textboxControl</param>
        /// <param name="textboxControl">a new control to attach to</param>
        private void AttachToControl(Form form, RichTextBox textboxControl)
        {
            InternalLogger.Info("Attaching target {0} to textbox {1}.{2}", this.Name, form.Name, textboxControl.Name);
            DetachFromControl();
            this.TargetForm        = form;
            this.TargetRichTextBox = textboxControl;

#if LINKS_SUPPORTED
            if (this.SupportLinks)
            {
                this.TargetRichTextBox.DetectUrls   = false;
                this.TargetRichTextBox.LinkClicked += TargetRichTextBox_LinkClicked;
            }
#endif

            //OnReattach?
            switch (messageRetention)
            {
            case RichTextBoxTargetMessageRetentionStrategy.None:
                break;

            case RichTextBoxTargetMessageRetentionStrategy.All:
                if (lastLoggedTextBoxControl != textboxControl)     //don't log to same RTB as befre, because it already has everything. Happens in case of config reload, see https://github.com/NLog/NLog.Windows.Forms/pull/22
                {
                    lock (messageQueueLock)
                    {
                        foreach (MessageInfo messageInfo in messageQueue)
                        {
                            DoSendMessageToTextbox(messageInfo.Message, messageInfo.Rule, messageInfo.LogEvent);
                        }
                    }
                }
                break;

            case RichTextBoxTargetMessageRetentionStrategy.OnlyMissed:
                lock (messageQueueLock)
                {
                    while (messageQueue.Count > 0)
                    {
                        MessageInfo messageInfo = messageQueue.Dequeue();
                        DoSendMessageToTextbox(messageInfo.Message, messageInfo.Rule, messageInfo.LogEvent);
                    }
                }
                break;

            default:
                HandleError("Unexpected retention strategy {0}", messageRetention);
                break;
            }
        }
コード例 #3
0
        private void ScrollToCurrentItem()
        {
            if (Element.ListLayout == HorizontalListViewLayout.Grid || Control.NumberOfItemsInSection(0) == 0)
            {
                return;
            }

            InternalLogger.Info($"ScrollToCurrentItem( Element.CurrentIndex = {Element.CurrentIndex} )");
            _isInternalScroll = true;
            Control.ScrollToItem(
                NSIndexPath.FromRowSection(Element.CurrentIndex, 0),
                UICollectionViewScrollPosition.Left,
                false);
        }
コード例 #4
0
ファイル: RabbitMQTarget.cs プロジェクト: wonea/Nlog.RabbitMQ
        private void ShutdownAmqp(IConnection connection, ShutdownEventArgs reason)
        {
            if (reason.ReplyCode != 200 /* Constants.ReplySuccess*/)
            {
                InternalLogger.Warn("RabbitMQTarget(Name={0}): Connection shutdown. ReplyCode={1}, ReplyText={2}", Name, reason.ReplyCode, reason.ReplyText);
            }
            else
            {
                InternalLogger.Info("RabbitMQTarget(Name={0}): Connection shutdown. ReplyCode={1}, ReplyText={2}", Name, reason.ReplyCode, reason.ReplyText);
            }

            lock (SyncRoot)
            {
                if (connection != null && ReferenceEquals(connection, _Connection))
                {
                    var model = _Model;

                    _Connection = null;
                    _Model      = null;

                    try
                    {
                        if (model != null && model.IsOpen &&
                            reason.ReplyCode != 504 &&                             //Constants.ChannelError
                            reason.ReplyCode != 320                                //Constants.ConnectionForced
                            )
                        {
                            model.Abort();                             //model.Close();
                        }
                    }
                    catch (Exception e)
                    {
                        InternalLogger.Error(e, "RabbitMQTarget(Name={0}): Could not close model: {1}", Name, e.Message);
                    }

                    try
                    {
                        if (connection.IsOpen)
                        {
                            connection.Close(reason.ReplyCode, reason.ReplyText, 1000);
                            connection.Abort(1000);                             // you get 2 seconds to shut down!
                        }
                    }
                    catch (Exception e)
                    {
                        InternalLogger.Error(e, "RabbitMQTarget(Name={0}): Could not close connection: {1}", Name, e.Message);
                    }
                }
            }
        }
コード例 #5
0
        public void TestMinLevelSwitch_lambda(string rawLogLevel, int count)
        {
            Action log = () =>
            {
                InternalLogger.Fatal(() => "L1");
                InternalLogger.Error(() => "L2");
                InternalLogger.Warn(() => "L3");
                InternalLogger.Info(() => "L4");
                InternalLogger.Debug(() => "L5");
                InternalLogger.Trace(() => "L6");
            };

            TestMinLevelSwitch_inner(rawLogLevel, count, log);
        }
コード例 #6
0
 /// <summary>
 /// This method must be called by the UI element in charge of displaying data.
 /// Per example, on android, a scroll listener can reference this paginator as an IInfiniteListLoader and call it from OnScroll.
 /// The call to this method is nearly transparent as it returns immediately and doesn't block the caller.
 /// (benchmarked as 4 ticks for a call (10 000 ticks == 1ms)).
 /// </summary>
 public void OnScroll(int lastVisibleIndex)
 {
     TaskMonitor <bool> .Create(
         ShouldLoadNextPage(lastVisibleIndex),
         whenSuccessfullyCompleted : (task, shouldLoad) =>
     {
         if (shouldLoad)
         {
             InternalLogger.Info($"Scrolled: loading more (max index of visible item {lastVisibleIndex})");
             int pageToLoad = lastVisibleIndex / PageSize + 2;
             LoadPage(pageToLoad, calledFromScroll: true);
         }
     });
 }
コード例 #7
0
        /// <summary>
        ///     Stops the watching.
        /// </summary>
        public void StopWatching()
        {
            lock (this)
            {
                foreach (var watcher in watchers)
                {
                    InternalLogger.Info("Stopping file watching for path '{0}' filter '{1}'", watcher.Path, watcher.Filter);
                    watcher.EnableRaisingEvents = false;
                    watcher.Dispose();
                }

                watchers.Clear();
            }
        }
コード例 #8
0
        /// <summary>
        /// Initializes the configuration.
        /// </summary>
        /// <param name="reader"><see cref="XmlReader"/> containing the configuration section.</param>
        /// <param name="fileName">Name of the file that contains the element (to be used as a base for including other files).</param>
        /// <param name="ignoreErrors">Ignore any errors during configuration.</param>
        private void Initialize(XmlReader reader, string fileName, bool ignoreErrors)
        {
            try
            {
                reader.MoveToContent();
                var content = new NLogXmlElement(reader);
                if (fileName != null)
                {
                    InternalLogger.Info("Configuring from an XML element in {0}...", fileName);
#if SILVERLIGHT
                    string key = fileName;
#else
                    string key = Path.GetFullPath(fileName);
#endif
                    this.visitedFile[key] = true;

                    this.originalFileName = fileName;
                    this.ParseTopLevel(content, Path.GetDirectoryName(fileName));
                }
                else
                {
                    this.ParseTopLevel(content, null);
                }
            }
            catch (Exception exception)
            {
                if (exception.MustBeRethrown())
                {
                    throw;
                }

                NLogConfigurationException ConfigException = new NLogConfigurationException("Exception occurred when loading configuration from " + fileName, exception);

                if (!ignoreErrors)
                {
                    if (LogManager.ThrowExceptions)
                    {
                        throw ConfigException;
                    }
                    else
                    {
                        InternalLogger.Error("Error in Parsing Configuration File. Exception : {0}", ConfigException);
                    }
                }
                else
                {
                    InternalLogger.Error("Error in Parsing Configuration File. Exception : {0}", ConfigException);
                }
            }
        }
コード例 #9
0
        /// <summary>
        /// Initializes the configuration.
        /// </summary>
        /// <param name="reader"><see cref="XmlReader"/> containing the configuration section.</param>
        /// <param name="fileName">Name of the file that contains the element (to be used as a base for including other files).</param>
        /// <param name="ignoreErrors">Ignore any errors during configuration.</param>
        private void Initialize(XmlReader reader, string fileName, bool ignoreErrors)
        {
            try
            {
                InitializeSucceeded = null;
                reader.MoveToContent();
                var content = new NLogXmlElement(reader);
                if (fileName != null)
                {
                    this.originalFileName = fileName;
                    this.ParseTopLevel(content, fileName, autoReloadDefault: false);

                    InternalLogger.Info("Configured from an XML element in {0}...", fileName);
                }
                else
                {
                    this.ParseTopLevel(content, null, autoReloadDefault: false);
                }
                InitializeSucceeded = true;

                this.CheckUnusedTargets();
            }
            catch (Exception exception)
            {
                InitializeSucceeded = false;
                if (exception.MustBeRethrown())
                {
                    throw;
                }

                NLogConfigurationException ConfigException = new NLogConfigurationException("Exception occurred when loading configuration from " + fileName, exception);

                if (!ignoreErrors)
                {
                    if (LogManager.ThrowExceptions)
                    {
                        throw ConfigException;
                    }
                    else
                    {
                        InternalLogger.Error("Error in Parsing Configuration File. Exception : {0}", ConfigException);
                    }
                }
                else
                {
                    InternalLogger.Error("Error in Parsing Configuration File. Exception : {0}", ConfigException);
                }
            }
        }
コード例 #10
0
        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;
            }
        }
コード例 #11
0
        internal Core(string[] args)
        {
            Console.Title = $"Initializing...";
            Logger        = InternalLogger.GetOrCreateLogger <Core>(this, nameof(Core));
            OS.Init(true);
            RuntimeSpanCounter.Restart();
            File.WriteAllText("version.txt", Constants.Version?.ToString());

            ParseStartupArguments();

            if (File.Exists(Constants.TraceLogFile))
            {
                File.Delete(Constants.TraceLogFile);
            }

            Config = new CoreConfig(this);
            Config.LoadAsync().Wait();
            IsUpdatesAllowed = !NoUpdates && Config.AutoUpdates;
            Config.LocalIP   = Helpers.GetLocalIpAddress()?.ToString() ?? "-Invalid-";
            Config.PublicIP  = Helpers.GetPublicIP()?.ToString() ?? "-Invalid-";

            if (!IsNetworkAvailable)
            {
                Logger.Warn("No Internet connection.");
                Logger.Info($"Starting offline mode...");
            }

            Pins = new PinsWrapper(
                Config.GpioConfiguration.OutputModePins,
                Config.GpioConfiguration.InputModePins,
                Constants.BcmGpioPins,
                Config.GpioConfiguration.RelayPins,
                Config.GpioConfiguration.InfraredSensorPins,
                Config.GpioConfiguration.SoundSensorPins
                );

            Controller   = new GpioCore(Pins, this, Config.GpioConfiguration.GpioSafeMode);
            ModuleLoader = new ModuleLoader();
            RestServer   = new RestCore(Config.RestServerPort, Config.Debug);

            JobManager.AddJob(() => SetConsoleTitle(), (s) => s.WithName("ConsoleUpdater").ToRunEvery(1).Seconds());
            Logger.CustomLog(FiggleFonts.Ogre.Render("LUNA"), ConsoleColor.Green);
            Logger.CustomLog($"---------------- Starting Luna v{Constants.Version} ----------------", ConsoleColor.Blue);
            IsBaseInitiationCompleted = true;
            PostInitiation().Wait();
            InternalConfigWatcher = new ConfigWatcher(this);
            InternalModuleWatcher = new ModuleWatcher(this);
            InitiationCompleted   = true;
        }
コード例 #12
0
        public void WriteToConsoleErrorTests()
        {
            // 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.LogToConsoleError = true;

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

                // Redirect the console output to a StringWriter.
                Console.SetError(consoleWriter1);

                // 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, consoleWriter1);
            }

            {
                //
                // Redirect the console output to another StringWriter.

                StringWriter consoleWriter2 = new StringWriter()
                {
                    NewLine = "\n"
                };
                Console.SetError(consoleWriter2);

                // 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, consoleWriter2);
            }
        }
コード例 #13
0
        private void AllocateBitmap(int measuredWidth, int measuredHeight)
        {
            InternalLogger.Info($"AllocateBitmap( width: {measuredWidth}, height: {measuredHeight} )");

            int nonRoundedScaledWidth  = DownScaleSize(measuredWidth);
            int nonRoundedScaledHeight = DownScaleSize(measuredHeight);

            int scaledWidth  = RoundSize(nonRoundedScaledWidth);
            int scaledHeight = RoundSize(nonRoundedScaledHeight);

            roundingHeightScaleFactor = (float)nonRoundedScaledHeight / scaledHeight;
            roundingWidthScaleFactor  = (float)nonRoundedScaledWidth / scaledWidth;

            internalBitmap = Bitmap.CreateBitmap(scaledWidth, scaledHeight, blurAlgorithm.GetSupportedBitmapConfig());
        }
コード例 #14
0
        public override int FindTargetSnapPosition(RecyclerView.LayoutManager layoutManager, int velocityX, int velocityY)
        {
            var targetSnapPosition = base.FindTargetSnapPosition(layoutManager, velocityX, velocityY);

            InternalLogger.Info($"FindTargetSnapPosition() : {targetSnapPosition}");

            if (WeakNativeView.TryGetTarget(out var target))
            {
                target.IsSnapHelperBusy = targetSnapPosition == -1;
                target.CurrentSnapIndex = targetSnapPosition > -1 ? targetSnapPosition : target.CurrentSnapIndex;
                System.Diagnostics.Debug.WriteLine($">>>>>> CurrentSnapIndex: {target.CurrentSnapIndex}");
            }

            return(targetSnapPosition);
        }
コード例 #15
0
        public override int[] CalculateDistanceToFinalSnap(RecyclerView.LayoutManager layoutManager, View targetView)
        {
            int[] result = new int[2];

            result[0] = layoutManager.CanScrollHorizontally()
                ? DistanceToStart(targetView, GetHorizontalHelper(layoutManager))
                : 0;

            result[1] = layoutManager.CanScrollVertically()
                ? DistanceToStart(targetView, GetVerticalHelper(layoutManager))
                : 0;

            InternalLogger.Info($"CalculateDistanceToFinalSnap()");
            return(result);
        }
コード例 #16
0
        /// <inheritdoc />
        public void Handle(IMessageContext messageContext)
        {
            var handlerMethods = (EventHandlerMethodWithObject[])
                                 messageContext.Items[EventHandlerLocatorMiddleware.HandlerMethodsKey];
            var handlerObjects = new object[handlerMethods.Length];

            for (int i = 0; i < handlerMethods.Length; i++)
            {
                object handler = null;
                // Event already implements Handle method within it.
                if (handlerMethods[i].Method.DeclaringType == messageContext.Content.GetType())
                {
                    handler = messageContext.Content;
                }
                if (handler == null && handlerMethods[i].Object != null)
                {
                    handler = handlerMethods[i].Object;
                }
                if (handler == null)
                {
                    try
                    {
                        if (UseInternalObjectResolver)
                        {
                            handler = CreateHandlerWithCache(handlerMethods[i].Method.DeclaringType,
                                                             messageContext.ServiceProvider, Id);
                        }
                        else
                        {
                            handler = messageContext.ServiceProvider.GetService(handlerMethods[i].Method.DeclaringType);
                        }
                    }
                    catch (Exception ex)
                    {
                        InternalLogger.Info(string.Format(Properties.Strings.ExceptionOnResolve,
                                                          handlerMethods[i].Method.Name, ex), nameof(EventHandlerExecutorMiddleware));
                    }
                }
                if (handler == null)
                {
                    InternalLogger.Warn(string.Format(Properties.Strings.CannotResolveHandler,
                                                      handlerMethods[i].Method.Name), nameof(EventHandlerExecutorMiddleware));
                }
                handlerObjects[i] = handler;
            }

            messageContext.Items[HandlerObjectKey] = handlerObjects;
        }
コード例 #17
0
ファイル: RabbitMQ.cs プロジェクト: mnjstwins/NLog.RabbitMQ-1
        private void CheckUnsent()
        {
            var count = _UnsentMessages.Count;

            for (var i = 0; i < count; i++)
            {
                var tuple = _UnsentMessages[i];
                InternalLogger.Info("publishing unsent message: {0}.", tuple);
                Publish(tuple.Item1, tuple.Item2, tuple.Item3);
            }

            if (count > 0)
            {
                _UnsentMessages.Clear();
            }
        }
コード例 #18
0
        internal bool GenerateDefaultConfig()
        {
            Logger.Info("Generating default config...");
            if (!Directory.Exists(Constants.ConfigDirectory))
            {
                Directory.CreateDirectory(Constants.ConfigDirectory);
            }

            if (File.Exists(Constants.CoreConfigPath))
            {
                return(true);
            }

            SaveAsync().RunSynchronously();
            return(true);
        }
コード例 #19
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);
            }
        }
コード例 #20
0
        /// <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);
        }
コード例 #21
0
            private void UpdateCurrentIndex(
                CollectionViewRenderer nativeView,
                CancellationToken token)
            {
                if (token.IsCancellationRequested)
                {
                    return;
                }

                if (nativeView?.LinearLayoutManager == null || _element == null)
                {
                    return;
                }

                nativeView._isCurrentIndexUpdateBackfire = true;
                try
                {
                    int newIndex = -1;
                    if (_element.SnapStyle != SnapStyle.None)
                    {
                        newIndex = nativeView.CurrentSnapIndex;
                    }
                    else
                    {
                        newIndex = nativeView.LinearLayoutManager.FindFirstCompletelyVisibleItemPosition();
                        if (newIndex == -1)
                        {
                            newIndex = nativeView.LinearLayoutManager.FindFirstVisibleItemPosition();
                        }
                    }

                    if (newIndex == -1)
                    {
                        InternalLogger.Warn(
                            "Failed to find the current index: UpdateCurrentIndex returns nothing");
                        return;
                    }

                    _element.CurrentIndex = newIndex;
                    InternalLogger.Info($"CurrentIndex: {_element.CurrentIndex}");
                }
                finally
                {
                    nativeView._isCurrentIndexUpdateBackfire = false;
                }
            }
コード例 #22
0
 /// <summary>
 /// Constructs a new instance of <see cref="XmlLoggingConfiguration" />
 /// class and reads the configuration from the specified config file.
 /// </summary>
 /// <param name="fileName">Configuration file to be read.</param>
 /// <param name="ignoreErrors">Ignore any errors during configuration.</param>
 public XmlLoggingConfiguration(string fileName, bool ignoreErrors)
 {
     InternalLogger.Info("Configuring from {0}...", fileName);
     _originalFileName = fileName;
     try
     {
         ConfigureFromFile(fileName);
     }
     catch (Exception ex)
     {
         InternalLogger.Error("Error {0}...", ex);
         if (!ignoreErrors)
         {
             throw new NLogConfigurationException("Exception occured when loading configuration from '" + fileName + "'", ex);
         }
     }
 }
コード例 #23
0
            private void OnItemReplaced(int itemIndex, object newItem)
            {
                InternalLogger.Info($"OnItemReplaced( itemIndex: {itemIndex} )");
                using var h = new Handler(Looper.MainLooper);
                h.Post(
                    () =>
                {
                    if (_isDisposed)
                    {
                        return;
                    }

                    _dataSource[itemIndex] = newItem;

                    NotifyItemChanged(itemIndex);
                });
            }
コード例 #24
0
        internal void Dump()
        {
            InternalLogger.Debug("--- NLog configuration dump. ---");
            InternalLogger.Debug("Targets:");
            foreach (var target in targets.Values)
            {
                InternalLogger.Info("{0}", target);
            }

            InternalLogger.Debug("Rules:");
            foreach (var rule in LoggingRules)
            {
                InternalLogger.Info("{0}", rule);
            }

            InternalLogger.Debug("--- End of NLog configuration dump ---");
        }
コード例 #25
0
        internal void ReloadConfigOnTimer(object state)
        {
            LoggingConfiguration configurationToReload = (LoggingConfiguration)state;

            InternalLogger.Info("Reloading configuration...");
            lock (this)
            {
                if (_reloadTimer != null)
                {
                    _reloadTimer.Dispose();
                    _reloadTimer = null;
                }

                _watcher.StopWatching();
                try
                {
                    if (Configuration != configurationToReload)
                    {
                        throw new Exception("Config changed in between. Not reloading.");
                    }

                    LoggingConfiguration newConfig = configurationToReload.Reload();
                    if (newConfig != null)
                    {
                        Configuration = newConfig;
                        if (ConfigurationReloaded != null)
                        {
                            ConfigurationReloaded(true, null);
                        }
                    }
                    else
                    {
                        throw new Exception("Configuration.Reload() returned null. Not reloading.");
                    }
                }
                catch (Exception ex)
                {
                    _watcher.Watch(configurationToReload.FileNamesToWatch);
                    if (ConfigurationReloaded != null)
                    {
                        ConfigurationReloaded(false, ex);
                    }
                }
            }
        }
コード例 #26
0
        public void WriteToStringWriterTests()
        {
            // 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;

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

            InternalLogger.LogWriter = writer1;

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

            Assert.True(writer1.ToString() == expected);

            //
            // 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");
            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");

            Assert.True(writer2.ToString() == expected);
        }
コード例 #27
0
        /// <summary>
        /// Initializes the configuration.
        /// </summary>
        /// <param name="reader"><see cref="XmlReader"/> containing the configuration section.</param>
        /// <param name="fileName">Name of the file that contains the element (to be used as a base for including other files).</param>
        /// <param name="ignoreErrors">Ignore any errors during configuration.</param>
        private void Initialize(XmlReader reader, string fileName, bool ignoreErrors)
        {
            try
            {
                InitializeSucceeded = null;
                reader.MoveToContent();
                var content = new NLogXmlElement(reader);
                if (fileName != null)
                {
                    this.originalFileName = fileName;
                    this.ParseTopLevel(content, fileName, autoReloadDefault: false);

                    InternalLogger.Info("Configured from an XML element in {0}...", fileName);
                }
                else
                {
                    this.ParseTopLevel(content, null, autoReloadDefault: false);
                }
                InitializeSucceeded = true;

                // Automatically reconfigure existing pools as soon as the configuration has been loaded
                this.PoolConfiguration.ReconfigurePools(this.PoolFactory);

                this.CheckUnusedTargets();
            }
            catch (Exception exception)
            {
                InitializeSucceeded = false;
                if (exception.MustBeRethrownImmediately())
                {
                    throw;
                }

                var configurationException = new NLogConfigurationException("Exception occurred when loading configuration from " + fileName, exception);
                InternalLogger.Error(configurationException, "Error in Parsing Configuration File.");

                if (!ignoreErrors)
                {
                    if (exception.MustBeRethrown())
                    {
                        throw configurationException;
                    }
                }
            }
        }
コード例 #28
0
ファイル: RabbitMQ.cs プロジェクト: xtrakTD/DigestTestSuite
        protected override void Write(LogEventInfo logEvent)
        {
            if (_messageQueue.Count >= MaxMessageCount)
            {
                InternalLogger.Info(string.Format("Сообщение не будет обработано [{0}]", Layout.Render(logEvent)));

                return;
            }
            _messageQueue.Enqueue(new Message
            {
                Payload  = Layout.Render(logEvent),
                Topic    = Topic.Render(logEvent),
                Exchange = Exchange.Render(logEvent)
            });


            CreateWorker();
        }
コード例 #29
0
 /// <summary>
 /// Initializes the target.
 /// </summary>
 protected override void InitializeTarget()
 {
     PauseLogging = false;
     if (DetectConsoleAvailable)
     {
         string reason;
         PauseLogging = !ConsoleTargetHelper.IsConsoleAvailable(out reason);
         if (PauseLogging)
         {
             InternalLogger.Info("Console has been detected as turned off. Disable DetectConsoleAvailable to skip detection. Reason: {0}", reason);
         }
     }
     base.InitializeTarget();
     if (Header != null)
     {
         this.WriteToOutput(Header.Render(LogEventInfo.CreateNullEvent()));
     }
 }
コード例 #30
0
        protected override void CloseTarget()
        {
            InternalLogger.Warn("Closing {0} target", nameof(AzureBlobStorageLogTarget));
            var result = _log.ShutdownAsync().Result;

            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));
            }
        }