コード例 #1
0
ファイル: InternalLoggerTests.cs プロジェクト: zmidl/NLog
        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";

            using (var loggerScope = new InternalLoggerScope(true))
            {
                InternalLogger.LogLevel         = LogLevel.Trace;
                InternalLogger.IncludeTimestamp = false;
                InternalLogger.LogToConsole     = true;

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

                    // Redirect the console output to a StringWriter.
                    loggerScope.SetConsoleOutput(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"
                    };
                    loggerScope.SetConsoleOutput(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);
                }

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

                    // Redirect the console output to a StringWriter.
                    loggerScope.SetConsoleOutput(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);
                }
            }
        }
コード例 #2
0
ファイル: DatabaseTarget.cs プロジェクト: zhouweiaccp/NLog
        protected override void InitializeTarget()
        {
            base.InitializeTarget();

#pragma warning disable 618
            if (UseTransactions.HasValue)
#pragma warning restore 618
            {
                InternalLogger.Warn("DatabaseTarget(Name={0}): UseTransactions property is obsolete and will not be used - will be removed in NLog 6", Name);
            }

            bool   foundProvider = false;
            string providerName  = string.Empty;

#if !NETSTANDARD
            if (!string.IsNullOrEmpty(ConnectionStringName))
            {
                // read connection string and provider factory from the configuration file
                var cs = ConnectionStringsSettings[ConnectionStringName];
                if (cs == null)
                {
                    throw new NLogConfigurationException($"Connection string '{ConnectionStringName}' is not declared in <connectionStrings /> section.");
                }

                if (!string.IsNullOrEmpty(cs.ConnectionString?.Trim()))
                {
                    ConnectionString = SimpleLayout.Escape(cs.ConnectionString.Trim());
                }
                providerName = cs.ProviderName?.Trim() ?? string.Empty;
            }
#endif

            if (ConnectionString != null)
            {
                try
                {
                    var connectionString          = BuildConnectionString(LogEventInfo.CreateNullEvent());
                    var dbConnectionStringBuilder = new DbConnectionStringBuilder {
                        ConnectionString = connectionString
                    };
                    if (dbConnectionStringBuilder.TryGetValue("provider connection string", out var connectionStringValue))
                    {
                        // Special Entity Framework Connection String
                        if (dbConnectionStringBuilder.TryGetValue("provider", out var providerValue))
                        {
                            // Provider was overriden by ConnectionString
                            providerName = providerValue.ToString()?.Trim() ?? string.Empty;
                        }

                        // ConnectionString was overriden by ConnectionString :)
                        ConnectionString = SimpleLayout.Escape(connectionStringValue.ToString());
                    }
                }
                catch (Exception ex)
                {
#if !NETSTANDARD
                    if (!string.IsNullOrEmpty(ConnectionStringName))
                    {
                        InternalLogger.Warn(ex, "DatabaseTarget(Name={0}): DbConnectionStringBuilder failed to parse '{1}' ConnectionString", Name, ConnectionStringName);
                    }
                    else
#endif
                    InternalLogger.Warn(ex, "DatabaseTarget(Name={0}): DbConnectionStringBuilder failed to parse ConnectionString", Name);
                }
            }

#if !NETSTANDARD
            if (string.IsNullOrEmpty(providerName))
            {
                string dbProvider = DBProvider?.Trim() ?? string.Empty;
                if (!string.IsNullOrEmpty(dbProvider))
                {
                    foreach (DataRow row in DbProviderFactories.GetFactoryClasses().Rows)
                    {
                        var invariantname = (string)row["InvariantName"];
                        if (string.Equals(invariantname, dbProvider, StringComparison.OrdinalIgnoreCase))
                        {
                            providerName = invariantname;
                            break;
                        }
                    }
                }
            }

            if (!string.IsNullOrEmpty(providerName))
            {
                try
                {
                    ProviderFactory = DbProviderFactories.GetFactory(providerName);
                    foundProvider   = true;
                }
                catch (Exception ex)
                {
                    InternalLogger.Error(ex, "DatabaseTarget(Name={0}): DbProviderFactories failed to get factory from ProviderName={1}", Name, providerName);
                    throw;
                }
            }
#endif

            if (!foundProvider)
            {
                try
                {
                    SetConnectionType();
                    if (ConnectionType == null)
                    {
                        InternalLogger.Warn("DatabaseTarget(Name={0}): No ConnectionType created from DBProvider={1}", Name, DBProvider);
                    }
                }
                catch (Exception ex)
                {
                    InternalLogger.Error(ex, "DatabaseTarget(Name={0}): Failed to create ConnectionType from DBProvider={1}", Name, DBProvider);
                    throw;
                }
            }
        }
コード例 #3
0
        private void ParseExtensionsElement(NLogXmlElement extensionsElement, string baseDirectory)
        {
            extensionsElement.AssertName("extensions");

            foreach (var addElement in extensionsElement.Elements("add"))
            {
                string prefix = addElement.GetOptionalAttribute("prefix", null);

                if (prefix != null)
                {
                    prefix = prefix + ".";
                }

                string type = StripOptionalNamespacePrefix(addElement.GetOptionalAttribute("type", null));
                if (type != null)
                {
                    this.configurationItemFactory.RegisterType(Type.GetType(type, true), prefix);
                }

                string assemblyFile = addElement.GetOptionalAttribute("assemblyFile", null);
                if (assemblyFile != null)
                {
                    try
                    {
#if SILVERLIGHT
                        var      si           = Application.GetResourceStream(new Uri(assemblyFile, UriKind.Relative));
                        var      assemblyPart = new AssemblyPart();
                        Assembly asm          = assemblyPart.Load(si.Stream);
#else
                        string fullFileName = Path.Combine(baseDirectory, assemblyFile);
                        InternalLogger.Info("Loading assembly file: {0}", fullFileName);

                        Assembly asm = Assembly.LoadFrom(fullFileName);
#endif
                        this.configurationItemFactory.RegisterItemsFromAssembly(asm, prefix);
                    }
                    catch (Exception exception)
                    {
                        if (exception.MustBeRethrown())
                        {
                            throw;
                        }

                        InternalLogger.Error("Error loading extensions: {0}", exception);
                        if (LogManager.ThrowExceptions)
                        {
                            throw new NLogConfigurationException("Error loading extensions: " + assemblyFile, exception);
                        }
                    }

                    continue;
                }

                string assemblyName = addElement.GetOptionalAttribute("assembly", null);
                if (assemblyName != null)
                {
                    try
                    {
                        InternalLogger.Info("Loading assembly name: {0}", assemblyName);
#if SILVERLIGHT
                        var      si           = Application.GetResourceStream(new Uri(assemblyName + ".dll", UriKind.Relative));
                        var      assemblyPart = new AssemblyPart();
                        Assembly asm          = assemblyPart.Load(si.Stream);
#else
                        Assembly asm = Assembly.Load(assemblyName);
#endif

                        this.configurationItemFactory.RegisterItemsFromAssembly(asm, prefix);
                    }
                    catch (Exception exception)
                    {
                        if (exception.MustBeRethrown())
                        {
                            throw;
                        }

                        InternalLogger.Error("Error loading extensions: {0}", exception);
                        if (LogManager.ThrowExceptions)
                        {
                            throw new NLogConfigurationException("Error loading extensions: " + assemblyName, exception);
                        }
                    }

                    continue;
                }
            }
        }
コード例 #4
0
        protected override void Write(LogEventInfo logEvent)
        {
            try
            {
                var log = new Log();
                log.Time    = logEvent.TimeStamp;
                log.Message = CleanseLogMessage.Cleanse(logEvent.FormattedMessage);

                log.Logger = logEvent.LoggerName;

                if (log.Logger.StartsWith("NzbDrone."))
                {
                    log.Logger = log.Logger.Remove(0, 9);
                }

                if (logEvent.Exception != null)
                {
                    if (string.IsNullOrWhiteSpace(log.Message))
                    {
                        log.Message = logEvent.Exception.Message;
                    }
                    else
                    {
                        log.Message += ": " + logEvent.Exception.Message;
                    }

                    log.Exception     = logEvent.Exception.ToString();
                    log.ExceptionType = logEvent.Exception.GetType().ToString();
                }

                log.Level = logEvent.Level.Name;

                var sqlCommand = new SQLiteCommand(INSERT_COMMAND, _connection);

                sqlCommand.Parameters.Add(new SQLiteParameter("Message", DbType.String)
                {
                    Value = log.Message
                });
                sqlCommand.Parameters.Add(new SQLiteParameter("Time", DbType.DateTime)
                {
                    Value = log.Time.ToUniversalTime()
                });
                sqlCommand.Parameters.Add(new SQLiteParameter("Logger", DbType.String)
                {
                    Value = log.Logger
                });
                sqlCommand.Parameters.Add(new SQLiteParameter("Exception", DbType.String)
                {
                    Value = log.Exception
                });
                sqlCommand.Parameters.Add(new SQLiteParameter("ExceptionType", DbType.String)
                {
                    Value = log.ExceptionType
                });
                sqlCommand.Parameters.Add(new SQLiteParameter("Level", DbType.String)
                {
                    Value = log.Level
                });

                sqlCommand.ExecuteNonQuery();
            }
            catch (SQLiteException ex)
            {
                InternalLogger.Error(ex, "Unable to save log event to database");
                throw;
            }
        }
コード例 #5
0
        private NLogEvents TranslateLogEvents(IList <AsyncLogEventInfo> logEvents)
        {
            if (logEvents.Count == 0 && !LogManager.ThrowExceptions)
            {
                InternalLogger.Error("LogReceiverServiceTarget(Name={0}): LogEvents array is empty, sending empty event...", Name);
                return(new NLogEvents());
            }

            string clientID = string.Empty;

            if (ClientId != null)
            {
                clientID = ClientId.Render(logEvents[0].LogEvent);
            }

            var networkLogEvents = new NLogEvents
            {
                ClientName  = clientID,
                LayoutNames = new StringCollection(),
                Strings     = new StringCollection(),
                BaseTimeUtc = logEvents[0].LogEvent.TimeStamp.ToUniversalTime().Ticks
            };

            var stringTable = new Dictionary <string, int>();

            for (int i = 0; i < Parameters.Count; ++i)
            {
                networkLogEvents.LayoutNames.Add(Parameters[i].Name);
            }

            if (IncludeEventProperties)
            {
                for (int i = 0; i < logEvents.Count; ++i)
                {
                    var ev = logEvents[i].LogEvent;
                    MergeEventProperties(ev);

                    if (ev.HasProperties)
                    {
                        // add all event-level property names in 'LayoutNames' collection.
                        foreach (var prop in ev.Properties)
                        {
                            string propName = prop.Key as string;
                            if (propName != null)
                            {
                                if (!networkLogEvents.LayoutNames.Contains(propName))
                                {
                                    networkLogEvents.LayoutNames.Add(propName);
                                }
                            }
                        }
                    }
                }
            }

            networkLogEvents.Events = new NLogEvent[logEvents.Count];
            for (int i = 0; i < logEvents.Count; ++i)
            {
                AsyncLogEventInfo ev = logEvents[i];
                networkLogEvents.Events[i] = TranslateEvent(ev.LogEvent, networkLogEvents, stringTable);
            }

            return(networkLogEvents);
        }
コード例 #6
0
        protected override void Write(LogEventInfo logEvent)
        {
            var uncompressedMessage = GetMessage(logEvent);
            var message             = CompressMessage(uncompressedMessage);

            var routingKey = RenderLogEvent(Topic, logEvent);

            if (routingKey.IndexOf("{0}") >= 0)
            {
                routingKey = routingKey.Replace("{0}", logEvent.Level.Name);
            }

            var model         = _Model;
            var modelExchange = _ModelExchange;

            if (model == null || !model.IsOpen)
            {
                StartConnection(_Connection, Timeout, true);
                model         = _Model;
                modelExchange = _ModelExchange;
            }

            var basicProperties = GetBasicProperties(logEvent, model);

            if (model == null || !model.IsOpen)
            {
                if (!AddUnsent(routingKey, basicProperties, message))
                {
                    throw new InvalidOperationException("LogEvent discarded because RabbitMQ instance is offline and reached MaxBuffer");
                }
                return;
            }

            bool restartConnection = true;

            try
            {
                CheckUnsent(model, modelExchange);
                Publish(model, message, basicProperties, routingKey, modelExchange);
                restartConnection = false;
            }
            catch (IOException e)
            {
                InternalLogger.Error(e, "RabbitMQTarget(Name={0}): Could not send to RabbitMQ instance: {1}", Name, e.Message);
                if (!AddUnsent(routingKey, basicProperties, message))
                {
                    throw;
                }
            }
            catch (ObjectDisposedException e)
            {
                InternalLogger.Error(e, "RabbitMQTarget(Name={0}): Could not send to RabbitMQ instance: {1}", Name, e.Message);
                if (!AddUnsent(routingKey, basicProperties, message))
                {
                    throw;
                }
            }
            catch (Exception e)
            {
                restartConnection = false;                    // Skip connection reconnect, maybe the LogEvent is broken, or maybe halfway there
                InternalLogger.Error(e, "RabbitMQTarget(Name={0}): Could not send to RabbitMQ instance: {1}", Name, e.Message);
                throw;
            }
            finally
            {
                if (restartConnection)
                {
                    StartConnection(_Connection, Math.Min(500, Timeout), true);
                }
            }
        }
コード例 #7
0
        private Logger GetLogger(LoggerCacheKey cacheKey)
        {
            lock (this.syncRoot)
            {
                Logger existingLogger = loggerCache.Retrieve(cacheKey);
                if (existingLogger != null)
                {
                    // Logger is still in cache and referenced.
                    return(existingLogger);
                }

                Logger newLogger;

                if (cacheKey.ConcreteType != null && cacheKey.ConcreteType != typeof(Logger))
                {
                    var fullName = cacheKey.ConcreteType.FullName;
                    try
                    {
                        //creating instance of static class isn't possible, and also not wanted (it cannot inherited from Logger)
                        if (cacheKey.ConcreteType.IsStaticClass())
                        {
                            var errorMessage = string.Format("GetLogger / GetCurrentClassLogger is '{0}' as loggerType can be a static class and should inherit from Logger",
                                                             fullName);
                            InternalLogger.Error(errorMessage);
                            if (ThrowExceptions)
                            {
                                throw new NLogRuntimeException(errorMessage);
                            }
                            newLogger = CreateDefaultLogger(ref cacheKey);
                        }
                        else
                        {
                            var instance = FactoryHelper.CreateInstance(cacheKey.ConcreteType);
                            newLogger = instance as Logger;
                            if (newLogger == null)
                            {
                                //well, it's not a Logger, and we should return a Logger.

                                var errorMessage = string.Format("GetLogger / GetCurrentClassLogger got '{0}' as loggerType which doesn't inherit from Logger", fullName);
                                InternalLogger.Error(errorMessage);
                                if (ThrowExceptions)
                                {
                                    throw new NLogRuntimeException(errorMessage);
                                }

                                // Creating default instance of logger if instance of specified type cannot be created.
                                newLogger = CreateDefaultLogger(ref cacheKey);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        if (ex.MustBeRethrown())
                        {
                            throw;
                        }

                        var errorMessage = string.Format("GetLogger / GetCurrentClassLogger. Cannot create instance of type '{0}'. It should have an default contructor. ", fullName);
                        if (ThrowExceptions)
                        {
                            throw new NLogRuntimeException(errorMessage, ex);
                        }

                        InternalLogger.Error(errorMessage + ". Exception : {0}", ex);

                        // Creating default instance of logger if instance of specified type cannot be created.
                        newLogger = CreateDefaultLogger(ref cacheKey);
                    }
                }
                else
                {
                    newLogger = new Logger();
                }

                if (cacheKey.ConcreteType != null)
                {
                    newLogger.Initialize(cacheKey.Name, this.GetConfigurationForLogger(cacheKey.Name, this.Configuration), this);
                }

                // TODO: Clarify what is the intention when cacheKey.ConcreteType = null.
                //      At the moment, a logger typeof(Logger) will be created but the ConcreteType
                //      will remain null and inserted into the cache.
                //      Should we set cacheKey.ConcreteType = typeof(Logger) for default loggers?

                loggerCache.InsertOrUpdate(cacheKey, newLogger);
                return(newLogger);
            }
        }
コード例 #8
0
 /// <summary>
 /// Logs an exception using the internal logger class.
 /// </summary>
 /// <param name="ex">The ex to log to the internal logger.</param>
 private void LogException(Exception ex)
 {
     InternalLogger.Error("Unable to send Sentry request: {0}", ex.Message);
 }
コード例 #9
0
        private void ProcessPendingEvents(object state)
        {
            bool?wroteFullBatchSize = false;

            AsyncContinuation[] continuations;
            bool lockTaken = false;

            try
            {
                if (TimeToSleepBetweenBatches <= 0)
                {
                    Monitor.Enter(this.lockObject);
                    lockTaken = true;
                }

                lock (this.continuationQueueLock)
                {
                    continuations = this.flushAllContinuations.Count > 0
                        ? this.flushAllContinuations.ToArray()
                        : new AsyncContinuation[] { null };
                    this.flushAllContinuations.Clear();
                }

                if (this.WrappedTarget == null)
                {
                    InternalLogger.Error("AsyncWrapper '{0}': WrappedTarget is NULL", this.Name);
                    return;
                }

                for (int x = 0; x < continuations.Length; x++)
                {
                    var continuation = continuations[x];

                    int count = this.BatchSize;
                    if (continuation != null)
                    {
                        count = -1; // Dequeue all
                    }

                    AsyncLogEventInfo[] logEventInfos = this.RequestQueue.DequeueBatch(count);
                    if (logEventInfos.Length == 0)
                    {
                        wroteFullBatchSize = null;    // Nothing to write
                    }
                    else if (logEventInfos.Length == BatchSize)
                    {
                        wroteFullBatchSize = true;
                    }

                    if (InternalLogger.IsTraceEnabled || continuation != null)
                    {
                        InternalLogger.Trace("AsyncWrapper '{0}': Flushing {1} events.", this.Name, logEventInfos.Length);
                    }

                    if (continuation != null)
                    {
                        // write all events, then flush, then call the continuation
                        this.WrappedTarget.WriteAsyncLogEvents(logEventInfos, ex => this.WrappedTarget.Flush(continuation));
                    }
                    else
                    {
                        // just write all events
                        this.WrappedTarget.WriteAsyncLogEvents(logEventInfos);
                    }
                }
            }
            catch (Exception exception)
            {
                wroteFullBatchSize = false; // Something went wrong, lets throttle retry

                InternalLogger.Error(exception, "AsyncWrapper '{0}': Error in lazy writer timer procedure.", this.Name);

                if (exception.MustBeRethrown())
                {
                    throw;
                }
            }
            finally
            {
                if (TimeToSleepBetweenBatches <= 0 && wroteFullBatchSize == true)
                {
                    this.StartInstantWriterTimer(); // Found full batch, fast schedule to take next batch (within lock to avoid pile up)
                }
                if (lockTaken)
                {
                    Monitor.Exit(this.lockObject);
                }

                if (TimeToSleepBetweenBatches <= 0)
                {
                    // If queue was not empty, then more might have arrived while writing the first batch
                    // Uses throttled timer here, so we can process in batches (faster)
                    if (wroteFullBatchSize.HasValue && !wroteFullBatchSize.Value)
                    {
                        this.StartLazyWriterTimer();    // Queue was not empty, more might have come (Skip expensive RequestQueue-check)
                    }
                    else if (!wroteFullBatchSize.HasValue)
                    {
                        if (this.RequestQueue.RequestCount > 0)
                        {
                            this.StartLazyWriterTimer();    // Queue was checked as empty, but now we have more
                        }
                        else
                        {
                            lock (this.continuationQueueLock)
                                if (this.flushAllContinuations.Count > 0)
                                {
                                    this.StartLazyWriterTimer();
                                }                                   // Flush queue was checked as empty, but now we have more
                        }
                    }
                }
                else
                {
                    this.StartLazyWriterTimer();
                }
            }
        }
コード例 #10
0
        private void SendBatch(IEnumerable <LogEventInfo> logEvents)
        {
            //Checks target is initialized and not disposed
            if (_client == null)
            {
                throw new ObjectDisposedException("AwsSqsTarget", "AmazonSQSClient for AwsSqsTarget is NULL. Target may not have been initialized or was disposed.");
            }

            //Create batch of messages
            List <Amazon.SQS.Model.SendMessageBatchRequestEntry> sendMesssageReqs = new List <Amazon.SQS.Model.SendMessageBatchRequestEntry>();

            int id = 0;

            foreach (var logEvent in logEvents)
            {
                //Renders the message using the current layout
                Amazon.SQS.Model.SendMessageBatchRequestEntry batchReqEntry = new Amazon.SQS.Model.SendMessageBatchRequestEntry();


                batchReqEntry.DelaySeconds = DelaySeconds;
                batchReqEntry.MessageBody  = this.Layout.Render(logEvent);
                batchReqEntry.Id           = id.ToString();


                //Write message attributes
                batchReqEntry.MessageAttributes.Add("Logger", new Amazon.SQS.Model.MessageAttributeValue()
                {
                    StringValue = logEvent.LoggerName, DataType = "String"
                });
                batchReqEntry.MessageAttributes.Add("Level", new Amazon.SQS.Model.MessageAttributeValue()
                {
                    StringValue = logEvent.Level.ToString(), DataType = "String"
                });
                batchReqEntry.MessageAttributes.Add("SequenceID", new Amazon.SQS.Model.MessageAttributeValue()
                {
                    StringValue = logEvent.SequenceID.ToString(), DataType = "Number"
                });


                //Other LogEventInfo Properties ...

                //logEvent.Parameters;
                //logEvent.Properties;
                //logEvent.Message;
                //logEvent.FormattedMessage;
                //logEvent.TimeStamp;
                //logEvent.Exception;
                //logEvent.FormatProvider;
                //logEvent.HasStackTrace;
                //logEvent.StackTrace;
                //logEvent.UserStackFrame;
                //logEvent.UserStackFrameNumber;



                sendMesssageReqs.Add(batchReqEntry);

                id++; //increment message id;
            }


            //Sends the batch of messages
            Amazon.SQS.Model.SendMessageBatchRequest batchReq = new Amazon.SQS.Model.SendMessageBatchRequest(QueueUrl, sendMesssageReqs);
            var result = _client.SendMessageBatchAsync(batchReq).ConfigureAwait(false).GetAwaiter().GetResult();


            //Check result for failed messages
            if (result.Failed.Count > 0)
            {
                var m = result.Failed.Count.ToString() + " messages sent to Amazon SQS failed. See internal NLog log for details.";

                InternalLogger.Error(m);

                foreach (var f in result.Failed)
                {
                    InternalLogger.Error("Message failed to send. Code = " + f.Code
                                         + ", Id = " + f.Id
                                         + ", SenderFault = " + f.SenderFault.ToString()
                                         + ", Message = " + f.Message);
                }

                if (ThrowExceptions)
                {
                    throw new Exception(m);
                }
            }
        }
コード例 #11
0
        public string FormPayload(AsyncLogEventInfo ev)
        {
            var logEvent = ev.LogEvent;

            //var document = GetAllProperties(logEvent);
            //document.Add("date", logEvent.TimeStamp);
            //document.Add("level", logEvent.Level.Name);
            //document.Add("message", RenderLogEvent(Layout, logEvent));

            var document = new Dictionary <string, object>
            {
                { "date", logEvent.TimeStamp },
                { "level", logEvent.Level.Name },
                { "message", RenderLogEvent(Layout, logEvent) }
            };

            if (Source != null)
            {
                document.Add("ddsource", Source);
            }
            if (Service != null)
            {
                document.Add("service", Service);
            }
            if (Host != null)
            {
                document.Add("host", Host);
            }
            if (Tags != null)
            {
                document.Add("ddtags", Tags);
            }

            if (logEvent.Exception != null)
            {
                var jsonString = JsonConvert.SerializeObject(logEvent.Exception, _jsonSerializerSettings.Value);
                var ex         = JsonConvert.DeserializeObject <ExpandoObject>(jsonString);
                document.Add("exception", ex.ReplaceDotInKeys());
            }

            foreach (var field in Fields)
            {
                var renderedField = RenderLogEvent(field.Layout, logEvent);

                if (string.IsNullOrWhiteSpace(renderedField))
                {
                    continue;
                }

                try
                {
                    document[field.Name] =
                        renderedField.ToSystemType(field.LayoutType, logEvent.FormatProvider, JsonSerializer);
                }
                catch (Exception ex)
                {
                    _jsonSerializer = null; // Reset as it might now be in bad state
                    InternalLogger.Error(ex, "ElasticSearch: Error while formatting field: {0}", field.Name);
                }
            }

            if (IncludeAllProperties && logEvent.HasProperties)
            {
                foreach (var p in logEvent.Properties)
                {
                    var propertyKey = p.Key.ToString();
                    if (_excludedProperties.Contains(propertyKey))
                    {
                        continue;
                    }
                    if (document.ContainsKey(propertyKey))
                    {
                        continue;
                    }

                    document[propertyKey] = p.Value;
                }
            }

            var result = JsonConvert.SerializeObject(document, Formatting.None, Settings);

            return(result);
        }
コード例 #12
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ConditionMethodExpression" /> class.
        /// </summary>
        /// <param name="conditionMethodName">Name of the condition method.</param>
        /// <param name="methodInfo"><see cref="MethodInfo"/> of the condition method.</param>
        /// <param name="methodParameters">The method parameters.</param>
        public ConditionMethodExpression(string conditionMethodName, MethodInfo methodInfo, IEnumerable <ConditionExpression> methodParameters)
        {
            this.MethodInfo          = methodInfo;
            this.conditionMethodName = conditionMethodName;
            this.MethodParameters    = new List <ConditionExpression>(methodParameters).AsReadOnly();

            ParameterInfo[] formalParameters = this.MethodInfo.GetParameters();
            if (formalParameters.Length > 0 && formalParameters[0].ParameterType == typeof(LogEventInfo))
            {
                this.acceptsLogEvent = true;
            }

            int actualParameterCount = this.MethodParameters.Count;

            if (this.acceptsLogEvent)
            {
                actualParameterCount++;
            }

            // Count the number of required and optional parameters
            int requiredParametersCount = 0;
            int optionalParametersCount = 0;

            foreach (var param in formalParameters)
            {
                if (param.IsOptional)
                {
                    ++optionalParametersCount;
                }
                else
                {
                    ++requiredParametersCount;
                }
            }

            if (!((actualParameterCount >= requiredParametersCount) && (actualParameterCount <= formalParameters.Length)))
            {
                string message;

                if (optionalParametersCount > 0)
                {
                    message = string.Format(
                        CultureInfo.InvariantCulture,
                        "Condition method '{0}' requires between {1} and {2} parameters, but passed {3}.",
                        conditionMethodName,
                        requiredParametersCount,
                        formalParameters.Length,
                        actualParameterCount);
                }
                else
                {
                    message = string.Format(
                        CultureInfo.InvariantCulture,
                        "Condition method '{0}' requires {1} parameters, but passed {2}.",
                        conditionMethodName,
                        requiredParametersCount,
                        actualParameterCount);
                }
                InternalLogger.Error(message);
                throw new ConditionParseException(message);
            }

            this.lateBoundMethod = Internal.ReflectionHelpers.CreateLateBoundMethod(MethodInfo);
            if (formalParameters.Length > MethodParameters.Count)
            {
                this.lateBoundMethodDefaultParameters = new object[formalParameters.Length - MethodParameters.Count];
                for (int i = MethodParameters.Count; i < formalParameters.Length; ++i)
                {
                    ParameterInfo param = formalParameters[i];
                    this.lateBoundMethodDefaultParameters[i - MethodParameters.Count] = param.DefaultValue;
                }
            }
            else
            {
                this.lateBoundMethodDefaultParameters = null;
            }
        }
コード例 #13
0
ファイル: InternalLoggerTests.cs プロジェクト: zmidl/NLog
        public void WriteToStringWriterTests()
        {
            try
            {
                // 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");

                    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");
                    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, writer2);
                }
                {
                    //
                    // 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");

                    TestWriter(expected, writer2);
                }
            }
            finally
            {
                InternalLogger.Reset();
            }
        }
コード例 #14
0
ファイル: InternalLoggerTests.cs プロジェクト: zmidl/NLog
        public void ExceptionTests()
        {
            using (new InternalLoggerScope())
            {
                InternalLogger.LogLevel         = LogLevel.Trace;
                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 WWW1" + prefix + ex1 + Environment.NewLine +
                        "Error EEE1" + prefix + ex2 + Environment.NewLine +
                        "Fatal FFF1" + prefix + ex3 + Environment.NewLine +
                        "Trace TTT1" + prefix + ex4 + Environment.NewLine +
                        "Debug DDD1" + prefix + ex5 + Environment.NewLine +
                        "Info III1" + Environment.NewLine;

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

                    // Redirect the console output to a StringWriter.
                    InternalLogger.LogWriter = consoleOutWriter;

                    // Named (based on LogLevel) public methods.

                    InternalLogger.Warn(ex1, "WWW1");
                    InternalLogger.Error(ex2, "EEE1");
                    InternalLogger.Fatal(ex3, "FFF1");
                    InternalLogger.Trace(ex4, "TTT1");
                    InternalLogger.Debug(ex5, "DDD1");
                    InternalLogger.Info(ex6, "III1");

                    consoleOutWriter.Flush();
                    var strings = consoleOutWriter.ToString();

                    Assert.Equal(expected, strings);
                }
                {
                    string expected =
                        "Warn WWW2" + prefix + ex1 + Environment.NewLine +
                        "Error EEE2" + prefix + ex2 + Environment.NewLine +
                        "Fatal FFF2" + prefix + ex3 + Environment.NewLine +
                        "Trace TTT2" + prefix + ex4 + Environment.NewLine +
                        "Debug DDD2" + prefix + ex5 + Environment.NewLine +
                        "Info III2" + Environment.NewLine;

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

                    // Redirect the console output to a StringWriter.
                    InternalLogger.LogWriter = consoleOutWriter;

                    // Named (based on LogLevel) public methods.

                    InternalLogger.Warn(ex1, () => "WWW2");
                    InternalLogger.Error(ex2, () => "EEE2");
                    InternalLogger.Fatal(ex3, () => "FFF2");
                    InternalLogger.Trace(ex4, () => "TTT2");
                    InternalLogger.Debug(ex5, () => "DDD2");
                    InternalLogger.Info(ex6, () => "III2");

                    consoleOutWriter.Flush();
                    var strings = consoleOutWriter.ToString();
                    Assert.Equal(expected, strings);
                }
                {
                    string expected =
                        "Warn WWW3" + prefix + ex1 + Environment.NewLine +
                        "Error EEE3" + prefix + ex2 + Environment.NewLine +
                        "Fatal FFF3" + prefix + ex3 + Environment.NewLine +
                        "Trace TTT3" + prefix + ex4 + Environment.NewLine +
                        "Debug DDD3" + prefix + ex5 + Environment.NewLine +
                        "Info III3" + Environment.NewLine;

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

                    // Redirect the console output to a StringWriter.
                    InternalLogger.LogWriter = consoleOutWriter;

                    // Named (based on LogLevel) public methods.

                    InternalLogger.Log(ex1, LogLevel.Warn, "WWW3");
                    InternalLogger.Log(ex2, LogLevel.Error, "EEE3");
                    InternalLogger.Log(ex3, LogLevel.Fatal, "FFF3");
                    InternalLogger.Log(ex4, LogLevel.Trace, "TTT3");
                    InternalLogger.Log(ex5, LogLevel.Debug, "DDD3");
                    InternalLogger.Log(ex6, LogLevel.Info, "III3");

                    consoleOutWriter.Flush();
                    var strings = consoleOutWriter.ToString();
                    Assert.Equal(expected, strings);
                }
                {
                    string expected =
                        "Warn WWW4" + prefix + ex1 + Environment.NewLine +
                        "Error EEE4" + prefix + ex2 + Environment.NewLine +
                        "Fatal FFF4" + prefix + ex3 + Environment.NewLine +
                        "Trace TTT4" + prefix + ex4 + Environment.NewLine +
                        "Debug DDD4" + prefix + ex5 + Environment.NewLine +
                        "Info III4" + Environment.NewLine;

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

                    // Redirect the console output to a StringWriter.
                    InternalLogger.LogWriter = consoleOutWriter;

                    // Named (based on LogLevel) public methods.

                    InternalLogger.Log(ex1, LogLevel.Warn, () => "WWW4");
                    InternalLogger.Log(ex2, LogLevel.Error, () => "EEE4");
                    InternalLogger.Log(ex3, LogLevel.Fatal, () => "FFF4");
                    InternalLogger.Log(ex4, LogLevel.Trace, () => "TTT4");
                    InternalLogger.Log(ex5, LogLevel.Debug, () => "DDD4");
                    InternalLogger.Log(ex6, LogLevel.Info, () => "III4");

                    var strings = consoleOutWriter.ToString();
                    Assert.Equal(expected, strings);
                }
            }
        }
コード例 #15
0
        public void VerifyInternalLoggerLevelFilter(bool?internalLogToTrace, bool?logToTrace)
        {
            foreach (LogLevel logLevelConfig in LogLevel.AllLevels)
            {
                var mockTraceListener = SetupTestConfiguration <MockTraceListener>(logLevelConfig, internalLogToTrace, logToTrace);

                List <string> expected = new List <string>();

                string input = "Logger1 Hello";
                expected.Add(input);
                InternalLogger.Trace(input);
                InternalLogger.Debug(input);
                InternalLogger.Info(input);
                InternalLogger.Warn(input);
                InternalLogger.Error(input);
                InternalLogger.Fatal(input);
                input += "No.{0}";
                expected.Add(string.Format(input, 1));
                InternalLogger.Trace(input, 1);
                InternalLogger.Debug(input, 1);
                InternalLogger.Info(input, 1);
                InternalLogger.Warn(input, 1);
                InternalLogger.Error(input, 1);
                InternalLogger.Fatal(input, 1);
                input += ", We come in {1}";
                expected.Add(string.Format(input, 1, "Peace"));
                InternalLogger.Trace(input, 1, "Peace");
                InternalLogger.Debug(input, 1, "Peace");
                InternalLogger.Info(input, 1, "Peace");
                InternalLogger.Warn(input, 1, "Peace");
                InternalLogger.Error(input, 1, "Peace");
                InternalLogger.Fatal(input, 1, "Peace");
                input += " and we are {2} to god";
                expected.Add(string.Format(input, 1, "Peace", true));
                InternalLogger.Trace(input, 1, "Peace", true);
                InternalLogger.Debug(input, 1, "Peace", true);
                InternalLogger.Info(input, 1, "Peace", true);
                InternalLogger.Warn(input, 1, "Peace", true);
                InternalLogger.Error(input, 1, "Peace", true);
                InternalLogger.Fatal(input, 1, "Peace", true);
                input += ", Please don't {3}";
                expected.Add(string.Format(input, 1, "Peace", true, null));
                InternalLogger.Trace(input, 1, "Peace", true, null);
                InternalLogger.Debug(input, 1, "Peace", true, null);
                InternalLogger.Info(input, 1, "Peace", true, null);
                InternalLogger.Warn(input, 1, "Peace", true, null);
                InternalLogger.Error(input, 1, "Peace", true, null);
                InternalLogger.Fatal(input, 1, "Peace", true, null);
                input += " the {4}";
                expected.Add(string.Format(input, 1, "Peace", true, null, "Messenger"));
                InternalLogger.Trace(input, 1, "Peace", true, null, "Messenger");
                InternalLogger.Debug(input, 1, "Peace", true, null, "Messenger");
                InternalLogger.Info(input, 1, "Peace", true, null, "Messenger");
                InternalLogger.Warn(input, 1, "Peace", true, null, "Messenger");
                InternalLogger.Error(input, 1, "Peace", true, null, "Messenger");
                InternalLogger.Fatal(input, 1, "Peace", true, null, "Messenger");
                Assert.Equal(expected.Count * (LogLevel.Fatal.Ordinal - logLevelConfig.Ordinal + 1), mockTraceListener.Messages.Count);
                for (int i = 0; i < expected.Count; ++i)
                {
                    int msgCount = LogLevel.Fatal.Ordinal - logLevelConfig.Ordinal + 1;
                    for (int j = 0; j < msgCount; ++j)
                    {
                        Assert.Contains(expected[i], mockTraceListener.Messages.First());
                        mockTraceListener.Messages.RemoveAt(0);
                    }
                }
                Assert.Empty(mockTraceListener.Messages);
            }
        }
コード例 #16
0
        private void UpdateEventLogSource()
        {
            if (!_needEventLogSourceUpdate)
            {
                return;
            }

            lock (this)
            {
                _operational = false;

                // if we throw anywhere, we remain non-operational

                try
                {
                    if (!_needEventLogSourceUpdate)
                    {
                        return;
                    }

                    if (EventLog.SourceExists(_sourceName, _machineName))
                    {
                        string currentLogName = EventLog.LogNameFromSourceName(_sourceName, _machineName);
                        if (currentLogName != _logName)
                        {
                            // re-create the association between Log and Source
                            EventLog.DeleteEventSource(_sourceName, _machineName);
#if DOTNET_2_0
                            EventSourceCreationData escd = new EventSourceCreationData(_sourceName, _logName);
                            escd.MachineName = _machineName;
                            EventLog.CreateEventSource(escd);
#else
                            EventLog.CreateEventSource(_sourceName, _logName, _machineName);
#endif
                        }
                        else
                        {
                            // ok, Source registered and associated with the correct Log
                        }
                    }
                    else
                    {
#if DOTNET_2_0
                        EventSourceCreationData escd = new EventSourceCreationData(_sourceName, _logName);
                        escd.MachineName = _machineName;
                        EventLog.CreateEventSource(escd);
#else
                        // source doesn't exist, register it.
                        EventLog.CreateEventSource(_sourceName, _logName, _machineName);
#endif
                    }
                    // mark the configuration as operational
                    _operational = true;
                }
                catch (Exception ex)
                {
                    InternalLogger.Error("Error when connecting to EventLog: {0}", ex);
                }
                finally
                {
                    _needEventLogSourceUpdate = false;
                }
            }
        }
コード例 #17
0
 private void AwsLogLibraryAlert(object sender, AWSLoggerCore.LogLibraryEventArgs e)
 {
     InternalLogger.Error(e.Exception, "AWSTarget(Name={0}) - CloudWatch Network Error - ServiceUrl={1}", Name, e.ServiceUrl);
 }
コード例 #18
0
ファイル: FileTarget.cs プロジェクト: shalang/NLog
            public void AddToArchive(string archiveFileName, string fileName, bool createDirectoryIfNotExists)
            {
                if (MaxArchiveFileToKeep < 1)
                {
                    InternalLogger.Warn("AddToArchive is called. Even though the MaxArchiveFiles is set to less than 1");

                    return;
                }

                if (!File.Exists(fileName))
                {
                    InternalLogger.Error("Error while trying to archive, Source File : {0} Not found.", fileName);

                    return;
                }

                while (archiveFileEntryQueue.Count >= MaxArchiveFileToKeep)
                {
                    string oldestArchivedFileName = archiveFileEntryQueue.Dequeue();

                    try
                    {
                        File.Delete(oldestArchivedFileName);
                    }
                    catch (Exception exceptionThrown)
                    {
                        InternalLogger.Warn("Can't Delete Old Archive File : {0} , Exception : {1}", oldestArchivedFileName, exceptionThrown);
                    }
                }


                String archiveFileNamePattern = archiveFileName;

                if (archiveFileEntryQueue.Contains(archiveFileName))
                {
                    InternalLogger.Trace("Archive File {0} seems to be already exist. Trying with Different File Name..", archiveFileName);

                    int NumberToStartWith = 1;

                    archiveFileNamePattern = Path.GetFileNameWithoutExtension(archiveFileName) + ".{#}" + Path.GetExtension(archiveFileName);

                    while (File.Exists(ReplaceNumber(archiveFileNamePattern, NumberToStartWith)))
                    {
                        InternalLogger.Trace("Archive File {0} seems to be already exist, too. Trying with Different File Name..", archiveFileName);
                        NumberToStartWith++;
                    }
                }

                try
                {
                    File.Move(fileName, archiveFileNamePattern);
                }
                catch (DirectoryNotFoundException)
                {
                    if (createDirectoryIfNotExists)
                    {
                        InternalLogger.Trace("Directory For Archive File is not created. Creating it..");

                        try
                        {
                            Directory.CreateDirectory(Path.GetDirectoryName(archiveFileName));

                            File.Move(fileName, archiveFileNamePattern);
                        }
                        catch (Exception ExceptionThrown)
                        {
                            InternalLogger.Error("Can't create Archive File Directory , Exception : {0}", ExceptionThrown);
                            throw;
                        }
                    }
                    else
                    {
                        throw;
                    }
                }
                catch (Exception ExceptionThrown)
                {
                    InternalLogger.Error("Can't Archive File : {0} , Exception : {1}", fileName, ExceptionThrown);

                    throw;
                }

                archiveFileEntryQueue.Enqueue(archiveFileName);
            }
コード例 #19
0
        /// <summary>
        /// Never throws
        /// </summary>
        private void StartConnection(IConnection oldConnection, int timeoutMilliseconds, bool checkInitialized)
        {
            if (!ReferenceEquals(oldConnection, _Connection) && (_Model?.IsOpen ?? false))
            {
                return;
            }

            var t = Task.Run(() =>
            {
                // Do not lock on SyncRoot, as we are waiting on this task while holding SyncRoot-lock
                lock (_sync)
                {
                    if (checkInitialized && !IsInitialized)
                    {
                        return;
                    }

                    if (!ReferenceEquals(oldConnection, _Connection) && (_Model?.IsOpen ?? false))
                    {
                        return;
                    }

                    InternalLogger.Info("RabbitMQTarget(Name={0}): Connection attempt started...", Name);
                    oldConnection = _Connection ?? oldConnection;
                    if (oldConnection != null)
                    {
                        var shutdownEvenArgs = new ShutdownEventArgs(ShutdownInitiator.Application, 504 /*Constants.ChannelError*/,
                                                                     "Model not open to RabbitMQ instance", null);
                        ShutdownAmqp(oldConnection, shutdownEvenArgs);
                    }

                    IModel model           = null;
                    IConnection connection = null;
                    string exchange        = null;

                    try
                    {
                        var factory = GetConnectionFac(out exchange, out var exchangeType, out var clientProvidedName);
                        connection  = string.IsNullOrEmpty(clientProvidedName) ? factory.CreateConnection() : factory.CreateConnection(clientProvidedName);
                        connection.ConnectionShutdown += (s, e) => ShutdownAmqp(ReferenceEquals(_Connection, connection) ? connection : null, e);

                        try
                        {
                            model = connection.CreateModel();
                        }
                        catch (Exception e)
                        {
                            InternalLogger.Error(e, "RabbitMQTarget(Name={0}): Could not create model, {1}", Name, e.Message);
                            throw;
                        }

                        if (model != null && !Passive)
                        {
                            try
                            {
                                model.ExchangeDeclare(exchange, exchangeType, Durable);
                            }
                            catch (Exception e)
                            {
                                InternalLogger.Error(e, string.Format("RabbitMQTarget(Name={0}): Could not declare exchange={1}. Error={2}", Name, exchange, e.Message));
                                throw;
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        var shutdownConnection = connection;
                        connection             = null;

                        if (shutdownConnection == null)
                        {
                            InternalLogger.Error(e, string.Format("RabbitMQTarget(Name={0}): Could not connect to Rabbit instance: {1}", Name, e.Message));
                        }
                        else
                        {
                            model?.Dispose();
                            model = null;
                            shutdownConnection.Close(TimeSpan.FromMilliseconds(1000));
                            shutdownConnection.Abort(TimeSpan.FromMilliseconds(1000));
                        }
                    }
                    finally
                    {
                        if (connection != null && model != null)
                        {
                            if ((_Model?.IsOpen ?? false))
                            {
                                InternalLogger.Info("RabbitMQTarget(Name={0}): Connection attempt completed succesfully, but not needed", Name);
                            }
                            else
                            {
                                _Connection    = connection;
                                _Model         = model;
                                _ModelExchange = exchange;
                                InternalLogger.Info("RabbitMQTarget(Name={0}): Connection attempt completed succesfully", Name);
                            }
                        }
                    }
                }
            });

            var completedTask = Task.WhenAny(t, Task.Delay(TimeSpan.FromMilliseconds(timeoutMilliseconds))).ConfigureAwait(false).GetAwaiter().GetResult();

            if (!ReferenceEquals(completedTask, t))
            {
                InternalLogger.Warn("RabbitMQTarget(Name={0}): Starting connection-task timed out, continuing", Name);
            }
            else if (completedTask.Exception != null)
            {
                InternalLogger.Error(completedTask.Exception, "RabbitMQTarget(Name={0}): Starting connection-task failed: {0}", Name, completedTask.Exception.Message);
            }
        }
コード例 #20
0
ファイル: NetworkTarget.cs プロジェクト: zsybupt/NLog
        /// <summary>
        /// Sends the
        /// rendered logging event over the network optionally concatenating it with a newline character.
        /// </summary>
        /// <param name="logEvent">The logging event.</param>
        protected override void Write(AsyncLogEventInfo logEvent)
        {
            string address = RenderLogEvent(Address, logEvent.LogEvent);

            InternalLogger.Trace("NetworkTarget(Name={0}): Sending to address: '{1}'", Name, address);

            byte[] bytes = GetBytesToWrite(logEvent.LogEvent);

            if (KeepConnection)
            {
                LinkedListNode <NetworkSender> senderNode;
                try
                {
                    senderNode = GetCachedNetworkSender(address);
                }
                catch (Exception ex)
                {
                    InternalLogger.Error(ex, "NetworkTarget(Name={0}): Failed to create sender to address: '{1}'", Name, address);
                    throw;
                }

                ChunkedSend(
                    senderNode.Value,
                    bytes,
                    ex =>
                {
                    if (ex != null)
                    {
                        InternalLogger.Error(ex, "NetworkTarget(Name={0}): Error when sending.", Name);
                        ReleaseCachedConnection(senderNode);
                    }

                    logEvent.Continuation(ex);
                });
            }
            else
            {
                NetworkSender sender;
                LinkedListNode <NetworkSender> linkedListNode;

                lock (_openNetworkSenders)
                {
                    //handle too many connections
                    var tooManyConnections = _openNetworkSenders.Count >= MaxConnections;

                    if (tooManyConnections && MaxConnections > 0)
                    {
                        switch (OnConnectionOverflow)
                        {
                        case NetworkTargetConnectionsOverflowAction.DiscardMessage:
                            InternalLogger.Warn("NetworkTarget(Name={0}): Discarding message otherwise to many connections.", Name);
                            logEvent.Continuation(null);
                            return;

                        case NetworkTargetConnectionsOverflowAction.AllowNewConnnection:
                            InternalLogger.Debug("NetworkTarget(Name={0}): Too may connections, but this is allowed", Name);
                            break;

                        case NetworkTargetConnectionsOverflowAction.Block:
                            while (_openNetworkSenders.Count >= MaxConnections)
                            {
                                InternalLogger.Debug("NetworkTarget(Name={0}): Blocking networktarget otherwhise too many connections.", Name);
                                Monitor.Wait(_openNetworkSenders);
                                InternalLogger.Trace("NetworkTarget(Name={0}): Entered critical section.", Name);
                            }

                            InternalLogger.Trace("NetworkTarget(Name={0}): Limit ok.", Name);
                            break;
                        }
                    }

                    try
                    {
                        sender = CreateNetworkSender(address);
                    }
                    catch (Exception ex)
                    {
                        InternalLogger.Error(ex, "NetworkTarget(Name={0}): Failed to create sender to address: '{1}'", Name, address);
                        throw;
                    }

                    linkedListNode = _openNetworkSenders.AddLast(sender);
                }
                ChunkedSend(
                    sender,
                    bytes,
                    ex =>
                {
                    lock (_openNetworkSenders)
                    {
                        TryRemove(_openNetworkSenders, linkedListNode);
                        if (OnConnectionOverflow == NetworkTargetConnectionsOverflowAction.Block)
                        {
                            Monitor.PulseAll(_openNetworkSenders);
                        }
                    }

                    if (ex != null)
                    {
                        InternalLogger.Error(ex, "NetworkTarget(Name={0}): Error when sending.", Name);
                    }

                    sender.Close(ex2 => { });
                    logEvent.Continuation(ex);
                });
            }
        }
コード例 #21
0
        /// <summary>
        /// Timer callback method that will log the stats.
        /// </summary>
        /// <param name="o">mandatory object parameter. (Not used)</param>
        private void ReportStats(object o)
        {
            StringBuilder builder = null;

            try
            {
                PoolConfiguration configuration = (PoolConfiguration)o;

                builder = this.Get <StringBuilderPool, StringBuilder>().Get();

                builder.Append(StatsPoolNameChars, 0, StatsPoolNameChars.Length);
                builder.Append('|');
                builder.Append(StatsPoolSizeChars, 0, StatsPoolSizeChars.Length);
                builder.Append('|');
                builder.Append(StatsObjectsInPoolChars, 0, StatsObjectsInPoolChars.Length);
                builder.Append('|');
                builder.Append(StatsInUseChars, 0, StatsInUseChars.Length);
                builder.Append('|');
                builder.Append(StatsGivenOutChars, 0, StatsGivenOutChars.Length);
                builder.Append('|');
                builder.Append(StatsThrownAwayChars, 0, StatsThrownAwayChars.Length);
                builder.Append('|');
                builder.Append(StatsNewLine, 0, StatsNewLine.Length);

                foreach (var pool in this.pools)
                {
                    pool.WriteStatsTo(builder);
                }

                if (configuration.ResetPoolStatisticsAfterReporting)
                {
                    lock (this.pools)
                    {
                        foreach (var pool in this.pools)
                        {
                            pool.ResetStats();
                        }
                    }
                }

                if (!string.IsNullOrEmpty(configuration.PoolStatisticsLoggerName))
                {
                    LogManager.GetLogger(configuration.PoolStatisticsLoggerName).Info(builder.ToString());
                }
                else
                {
                    InternalLogger.Info(builder.ToString());
                }
                this.statsTimer.Change(configuration.OutputPoolStatisticsInterval * 1000, Timeout.Infinite);
            }
            catch (Exception e)
            {
                InternalLogger.Error("Error occured while reporting pool statistics:{0}", e);
            }
            finally
            {
                if (builder != null)
                {
                    try
                    {
                        this.PutBack(builder);
                    }
                    catch (Exception e)
                    {
                        InternalLogger.Error("Error occured while putting back string builder slim into the pool:{0}", e);
                    }
                }
            }
        }
コード例 #22
0
        protected override void Write(LogEventInfo logEvent)
        {
            if (logEvent == null)
            {
                return;
            }

            GraylogMessageBuilder messageBuilder = new GraylogMessageBuilder()
                                                   .WithProperty("short_message", logEvent.FormattedMessage)
                                                   .WithProperty("host", Host)
                                                   .WithLevel(logEvent.Level)
                                                   .WithCustomProperty("logger_name", logEvent.LoggerName);

            if (!string.IsNullOrEmpty(Facility))
            {
                messageBuilder.WithCustomProperty("facility", Facility);
            }

            var properties = GetAllProperties(logEvent);

            foreach (var property in properties)
            {
                try
                {
                    if (!string.IsNullOrEmpty(property.Key))
                    {
                        if (Convert.GetTypeCode(property.Value) != TypeCode.Object)
                        {
                            messageBuilder.WithCustomProperty(property.Key, property.Value);
                        }
                        else
                        {
                            messageBuilder.WithCustomProperty(property.Key, property.Value?.ToString());
                        }
                    }
                }
#pragma warning disable CA1031 // Do not catch general exception types
                catch (Exception ex)
#pragma warning restore CA1031 // Do not catch general exception types
                {
                    InternalLogger.Error(ex, "GraylogHttp(Name={0}): Fail to handle LogEvent Properties", Name);
                }
            }

            if (logEvent.Exception != null)
            {
                if (!string.IsNullOrEmpty(logEvent.Exception.Message))
                {
                    messageBuilder.WithCustomProperty("_exception_message", logEvent.Exception.Message);
                }
                if (!string.IsNullOrEmpty(logEvent.Exception.StackTrace))
                {
                    messageBuilder.WithCustomProperty("_exception_stack_trace", logEvent.Exception.StackTrace);
                }
            }

            try
            {
                _policy.Execute(() =>
                {
                    var content = new StringContent(messageBuilder.Render(logEvent.TimeStamp), Encoding.UTF8, "application/json");
                    return(_httpClient.PostAsync(_requestAddress, content).Result.EnsureSuccessStatusCode());
                });
            }
            catch (BrokenCircuitException)
            {
                InternalLogger.Error(
                    "GraylogHttp(Name={0}): The Graylog server seems to be inaccessible, the log messages were not sent to the server.",
                    Name);
            }
        }
コード例 #23
0
        private void ParseIncludeElement(ILoggingConfigurationElement includeElement, string baseDirectory, bool autoReloadDefault)
        {
            includeElement.AssertName("include");

            string newFileName = includeElement.GetRequiredValue("file", "nlog");

            var ignoreErrors = includeElement.GetOptionalBooleanValue("ignoreErrors", false);

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

#if SILVERLIGHT && !WINDOWS_PHONE
                newFileName = newFileName.Replace("\\", "/");
                if (Application.GetResourceStream(new Uri(fullNewFileName, UriKind.Relative)) != null)
#else
                if (File.Exists(fullNewFileName))
#endif
                {
                    InternalLogger.Debug("Including file '{0}'", fullNewFileName);
                    ConfigureFromFile(fullNewFileName, autoReloadDefault);
                }
                else
                {
                    //is mask?

                    if (newFileName.Contains("*"))
                    {
                        ConfigureFromFilesByMask(baseDirectory, newFileName, autoReloadDefault);
                    }
                    else
                    {
                        if (ignoreErrors)
                        {
                            //quick stop for performances
                            InternalLogger.Debug("Skipping included file '{0}' as it can't be found", fullNewFileName);
                            return;
                        }

                        throw new FileNotFoundException("Included file not found: " + fullNewFileName);
                    }
                }
            }
            catch (Exception exception)
            {
                if (exception.MustBeRethrownImmediately())
                {
                    throw;
                }

                var configurationException = new NLogConfigurationException(exception, "Error when including '{0}'.", newFileName);
                InternalLogger.Error(exception, configurationException.Message);
                if (!ignoreErrors)
                {
                    throw configurationException;
                }
            }
        }
コード例 #24
0
ファイル: RabbitMQTarget.cs プロジェクト: SSM416/SDK
        protected override void Write(LogEventInfo logEvent)
        {
            IBasicProperties basicProperties = this.GetBasicProperties(logEvent);

            byte[] message = this.GetMessage(logEvent);
            byte[] array   = this.CompressMessage(message);
            string topic   = this.GetTopic(logEvent);
            IModel model   = this._Model;
            bool   flag    = model == null || !model.IsOpen;

            if (flag)
            {
                this.StartConnection(this._Connection, this.Timeout, true);
                model = this._Model;
            }
            bool flag2 = model == null || !model.IsOpen;

            if (flag2)
            {
                bool flag3 = !this.AddUnsent(topic, basicProperties, array);
                if (flag3)
                {
                    throw new InvalidOperationException("LogEvent discarded because RabbitMQ instance is offline and reached MaxBuffer");
                }
            }
            else
            {
                bool flag4 = true;
                try
                {
                    this.CheckUnsent(model);
                    this.Publish(model, array, basicProperties, topic);
                    flag4 = false;
                }
                catch (IOException ex)
                {
                    InternalLogger.Error(ex, "RabbitMQTarget(Name={0}): Could not send to RabbitMQ instance: {1}", new object[]
                    {
                        base.Name,
                        ex.Message
                    });
                    bool flag5 = !this.AddUnsent(topic, basicProperties, array);
                    if (flag5)
                    {
                        throw;
                    }
                }
                catch (ObjectDisposedException ex2)
                {
                    InternalLogger.Error(ex2, "RabbitMQTarget(Name={0}): Could not send to RabbitMQ instance: {1}", new object[]
                    {
                        base.Name,
                        ex2.Message
                    });
                    bool flag6 = !this.AddUnsent(topic, basicProperties, array);
                    if (flag6)
                    {
                        throw;
                    }
                }
                catch (Exception ex3)
                {
                    flag4 = false;
                    InternalLogger.Error(ex3, "RabbitMQTarget(Name={0}): Could not send to RabbitMQ instance: {1}", new object[]
                    {
                        base.Name,
                        ex3.Message
                    });
                    throw;
                }
                finally
                {
                    bool flag7 = flag4;
                    if (flag7)
                    {
                        this.StartConnection(this._Connection, Math.Min(500, this.Timeout), true);
                    }
                }
            }
        }
コード例 #25
0
        private void Send(NLogEvents events, IList <AsyncLogEventInfo> asyncContinuations, AsyncContinuation flushContinuations)
        {
            if (!OnSend(events, asyncContinuations))
            {
                if (flushContinuations != null)
                {
                    flushContinuations(null);
                }
                return;
            }

#if WCF_SUPPORTED
            var client = CreateLogReceiver();

            client.ProcessLogMessagesCompleted += (sender, e) =>
            {
                if (e.Error != null)
                {
                    InternalLogger.Error(e.Error, "LogReceiverServiceTarget(Name={0}): Error while sending", Name);
                }

                // report error to the callers
                for (int i = 0; i < asyncContinuations.Count; ++i)
                {
                    asyncContinuations[i].Continuation(e.Error);
                }

                if (flushContinuations != null)
                {
                    flushContinuations(e.Error);
                }

                // send any buffered events
                SendBufferedEvents(null);
            };

            inCall = true;
#if SILVERLIGHT
            if (!Deployment.Current.Dispatcher.CheckAccess())
            {
                Deployment.Current.Dispatcher.BeginInvoke(() => client.ProcessLogMessagesAsync(events));
            }
            else
            {
                client.ProcessLogMessagesAsync(events);
            }
#else
            client.ProcessLogMessagesAsync(events);
#endif
#else
            var client = new SoapLogReceiverClient(this.EndpointAddress);
            this.inCall = true;
            client.BeginProcessLogMessages(
                events,
                result =>
            {
                Exception exception = null;

                try
                {
                    client.EndProcessLogMessages(result);
                }
                catch (Exception ex)
                {
                    InternalLogger.Error(ex, "LogReceiverServiceTarget(Name={0}): Error while sending", Name);
                    if (ex.MustBeRethrownImmediately())
                    {
                        throw;          // Throwing exceptions here will crash the entire application (.NET 2.0 behavior)
                    }

                    exception = ex;
                }

                // report error to the callers
                for (int i = 0; i < asyncContinuations.Count; ++i)
                {
                    asyncContinuations[i].Continuation(exception);
                }

                if (flushContinuations != null)
                {
                    flushContinuations(exception);
                }

                // send any buffered events
                this.SendBufferedEvents(null);
            },
                null);
#endif
        }
コード例 #26
0
ファイル: RabbitMQTarget.cs プロジェクト: SSM416/SDK
        private void StartConnection(IConnection oldConnection, int timeoutMilliseconds, bool checkInitialized)
        {
            bool arg_3F_0;

            if (oldConnection != this._Connection)
            {
                IModel expr_30 = this._Model;
                arg_3F_0 = (expr_30 != null && expr_30.IsOpen);
            }
            else
            {
                arg_3F_0 = false;
            }
            bool flag = arg_3F_0;

            if (!flag)
            {
                Task task = Task.Factory.StartNew(delegate
                {
                    object sync = this._sync;
                    bool flag3  = false;
                    try
                    {
                        Monitor.Enter(sync, ref flag3);
                        bool flag4 = checkInitialized && !this.IsInitialized;
                        if (!flag4)
                        {
                            bool arg_77_0;
                            if (oldConnection != this._Connection)
                            {
                                IModel expr_68 = this._Model;
                                arg_77_0       = (expr_68 != null && expr_68.IsOpen);
                            }
                            else
                            {
                                arg_77_0 = false;
                            }
                            bool flag5 = arg_77_0;
                            if (!flag5)
                            {
                                InternalLogger.Info <string>("RabbitMQTarget(Name={0}): Connection attempt started...", this.Name);
                                oldConnection = (this._Connection ?? oldConnection);
                                bool flag6    = oldConnection != null;
                                if (flag6)
                                {
                                    ShutdownEventArgs reason = new ShutdownEventArgs(ShutdownInitiator.Application, 504, "Model not open to RabbitMQ instance", null);
                                    this.ShutdownAmqp(oldConnection, reason);
                                }
                                IModel model           = null;
                                IConnection connection = null;
                                try
                                {
                                    connection = this.GetConnectionFac().CreateConnection();
                                    connection.ConnectionShutdown += delegate(object s, ShutdownEventArgs e)
                                    {
                                        this.ShutdownAmqp((this._Connection == connection) ? connection : null, e);
                                    };
                                    try
                                    {
                                        model = connection.CreateModel();
                                    }
                                    catch (Exception ex)
                                    {
                                        IConnection connection3 = connection;
                                        connection = null;
                                        InternalLogger.Error(ex, "RabbitMQTarget(Name={0}): Could not create model, {1}", new object[]
                                        {
                                            this.Name,
                                            ex.Message
                                        });
                                        connection3.Close(1000);
                                        connection3.Abort(1000);
                                    }
                                    bool flag7 = model != null && !this.Passive;
                                    if (flag7)
                                    {
                                        try
                                        {
                                            model.ExchangeDeclare(this.Exchange, this.ExchangeType, this.Durable, false, null);
                                        }
                                        catch (Exception ex2)
                                        {
                                            IConnection connection2 = connection;
                                            connection = null;
                                            InternalLogger.Error(ex2, string.Format("RabbitMQTarget(Name={0}): Could not declare exchange: {1}", this.Name, ex2.Message));
                                            model.Dispose();
                                            model = null;
                                            connection2.Close(1000);
                                            connection2.Abort(1000);
                                        }
                                    }
                                }
                                catch (Exception ex3)
                                {
                                    connection = null;
                                    InternalLogger.Error(ex3, string.Format("RabbitMQTarget(Name={0}): Could not connect to Rabbit instance: {1}", this.Name, ex3.Message));
                                }
                                finally
                                {
                                    bool flag8 = connection != null && model != null;
                                    if (flag8)
                                    {
                                        IModel expr_291 = this._Model;
                                        bool flag9      = expr_291 != null && expr_291.IsOpen;
                                        if (flag9)
                                        {
                                            InternalLogger.Info <string>("RabbitMQTarget(Name={0}): Connection attempt completed succesfully, but not needed", this.Name);
                                        }
                                        else
                                        {
                                            this._Connection = connection;
                                            this._Model      = model;
                                            InternalLogger.Info <string>("RabbitMQTarget(Name={0}): Connection attempt completed succesfully", this.Name);
                                        }
                                    }
                                }
                            }
                        }
                    }
                    finally
                    {
                        if (flag3)
                        {
                            Monitor.Exit(sync);
                        }
                    }
                });
                bool flag2 = !task.Wait(TimeSpan.FromMilliseconds((double)timeoutMilliseconds));
                if (flag2)
                {
                    InternalLogger.Warn <string>("RabbitMQTarget(Name={0}): Starting connection-task timed out, continuing", base.Name);
                }
            }
        }
コード例 #27
0
        /// <summary>
        /// Sends the
        /// rendered logging event over the network optionally concatenating it with a newline character.
        /// </summary>
        /// <param name="logEvent">The logging event.</param>
        protected override void Write(AsyncLogEventInfo logEvent)
        {
            string address = this.Address.Render(logEvent.LogEvent);

            byte[] bytes = this.GetBytesToWrite(logEvent.LogEvent);

            if (this.KeepConnection)
            {
                var senderNode = this.GetCachedNetworkSender(address);

                this.ChunkedSend(
                    senderNode.Value,
                    bytes,
                    ex =>
                {
                    if (ex != null)
                    {
                        InternalLogger.Error(ex, "Error when sending.");
                        this.ReleaseCachedConnection(senderNode);
                    }

                    logEvent.Continuation(ex);
                });
            }
            else
            {
                NetworkSender sender;
                LinkedListNode <NetworkSender> linkedListNode;

                lock (this.openNetworkSenders)
                {
                    //handle too many connections
                    var tooManyConnections = this.openNetworkSenders.Count >= MaxConnections;

                    if (tooManyConnections && MaxConnections > 0)
                    {
                        switch (this.OnConnectionOverflow)
                        {
                        case NetworkTargetConnectionsOverflowAction.DiscardMessage:
                            InternalLogger.Warn("Discarding message otherwise to many connections.");
                            logEvent.Continuation(null);
                            return;

                        case NetworkTargetConnectionsOverflowAction.AllowNewConnnection:
                            InternalLogger.Debug("Too may connections, but this is allowed");
                            break;

                        case NetworkTargetConnectionsOverflowAction.Block:
                            while (this.openNetworkSenders.Count >= this.MaxConnections)
                            {
                                InternalLogger.Debug("Blocking networktarget otherwhise too many connections.");
                                System.Threading.Monitor.Wait(this.openNetworkSenders);
                                InternalLogger.Trace("Entered critical section.");
                            }

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

                    sender = this.SenderFactory.Create(address, MaxQueueSize);
                    sender.Initialize();

                    linkedListNode = this.openNetworkSenders.AddLast(sender);
                }
                this.ChunkedSend(
                    sender,
                    bytes,
                    ex =>
                {
                    lock (this.openNetworkSenders)
                    {
                        TryRemove(this.openNetworkSenders, linkedListNode);
                        if (this.OnConnectionOverflow == NetworkTargetConnectionsOverflowAction.Block)
                        {
                            System.Threading.Monitor.PulseAll(this.openNetworkSenders);
                        }
                    }

                    if (ex != null)
                    {
                        InternalLogger.Error(ex, "Error when sending.");
                    }

                    sender.Close(ex2 => { });
                    logEvent.Continuation(ex);
                });
            }
        }
コード例 #28
0
ファイル: RabbitMQTarget.cs プロジェクト: SSM416/SDK
        private void ShutdownAmqp(IConnection connection, ShutdownEventArgs reason)
        {
            bool flag = reason.ReplyCode != 200;

            if (flag)
            {
                InternalLogger.Warn <string, ushort, string>("RabbitMQTarget(Name={0}): Connection shutdown. ReplyCode={1}, ReplyText={2}", base.Name, reason.ReplyCode, reason.ReplyText);
            }
            else
            {
                InternalLogger.Info <string, ushort, string>("RabbitMQTarget(Name={0}): Connection shutdown. ReplyCode={1}, ReplyText={2}", base.Name, reason.ReplyCode, reason.ReplyText);
            }
            object sync = this._sync;

            lock (sync)
            {
                bool flag3 = connection != null;
                if (flag3)
                {
                    IModel model = null;
                    bool   flag4 = connection == this._Connection;
                    if (flag4)
                    {
                        model            = this._Model;
                        this._Connection = null;
                        this._Model      = null;
                    }
                    try
                    {
                        bool flag5 = reason.ReplyCode == 200 && connection.IsOpen;
                        if (flag5)
                        {
                            if (model != null)
                            {
                                model.Close();
                            }
                        }
                        else if (model != null)
                        {
                            model.Abort();
                        }
                    }
                    catch (Exception ex)
                    {
                        InternalLogger.Error(ex, "RabbitMQTarget(Name={0}): Could not close model: {1}", new object[]
                        {
                            base.Name,
                            ex.Message
                        });
                    }
                    try
                    {
                        bool flag6 = reason.ReplyCode == 200 && connection.IsOpen;
                        if (flag6)
                        {
                            connection.Close(reason.ReplyCode, reason.ReplyText, 1500);
                        }
                        else
                        {
                            connection.Abort(reason.ReplyCode, reason.ReplyText, 1500);
                        }
                    }
                    catch (Exception ex2)
                    {
                        InternalLogger.Error(ex2, "RabbitMQTarget(Name={0}): Could not close connection: {1}", new object[]
                        {
                            base.Name,
                            ex2.Message
                        });
                    }
                }
            }
        }
コード例 #29
0
ファイル: AsyncTaskTarget.cs プロジェクト: zhouweiaccp/NLog
        /// <summary>
        /// Creates new task to handle the writing of the input <see cref="LogEventInfo"/>
        /// </summary>
        /// <param name="logEvent">LogEvent to write</param>
        /// <returns>New Task created [true / false]</returns>
        private bool TaskCreation(AsyncLogEventInfo logEvent)
        {
            try
            {
                if (_cancelTokenSource.IsCancellationRequested)
                {
                    logEvent.Continuation(null);
                    return(false);
                }

                if (logEvent.LogEvent == null)
                {
                    InternalLogger.Debug("{0} Flush Completed", Name);
                    logEvent.Continuation(null);
                    return(false);
                }

                var newTask = WriteAsyncTask(logEvent.LogEvent, _cancelTokenSource.Token);
                if (newTask == null)
                {
                    InternalLogger.Debug("{0} WriteAsyncTask returned null", Name);
                }
                else
                {
                    lock (SyncRoot)
                    {
                        _previousTask = newTask;

                        if (TaskTimeoutSeconds > 0)
                        {
                            _taskTimeoutTimer.Change(TaskTimeoutSeconds * 1000, Timeout.Infinite);
                        }

                        // NOTE - Not using _cancelTokenSource for ContinueWith, or else they will also be cancelled on timeout
#if (SILVERLIGHT && !WINDOWS_PHONE) || NET4_0
                        var continuation = logEvent.Continuation;
                        _previousTask.ContinueWith(completedTask => TaskCompletion(completedTask, continuation));
#else
                        _previousTask.ContinueWith(_taskCompletion, logEvent.Continuation);
#endif
                        if (_previousTask.Status == TaskStatus.Created)
                        {
                            _previousTask.Start(TaskScheduler);
                        }
                    }
                    return(true);
                }
            }
            catch (Exception ex)
            {
                try
                {
                    InternalLogger.Error(ex, "{0} WriteAsyncTask failed on creation", Name);
                    logEvent.Continuation(ex);
                }
                catch
                {
                    // Don't wanna die
                }
            }
            return(false);
        }
コード例 #30
0
        internal void DoInvoke(object[] parameters, AsyncContinuation continuation, HttpWebRequest request, Func <AsyncCallback, IAsyncResult> beginFunc,
                               Func <IAsyncResult, Stream> getStreamFunc)
        {
            Stream postPayload = null;

            if (Protocol == WebServiceProtocol.HttpGet)
            {
                PrepareGetRequest(request);
            }
            else
            {
                if (_activeProtocol.Value == null)
                {
                    _activeProtocol = new KeyValuePair <WebServiceProtocol, HttpPostFormatterBase>(this.Protocol, _postFormatterFactories[this.Protocol](this));
                }
                postPayload = _activeProtocol.Value.PrepareRequest(request, parameters);
            }

            AsyncContinuation sendContinuation =
                ex =>
            {
                if (ex != null)
                {
                    DoInvokeCompleted(continuation, ex);
                    return;
                }

                try
                {
                    request.BeginGetResponse(
                        r =>
                    {
                        try
                        {
                            using (var response = request.EndGetResponse(r))
                            {
                            }

                            DoInvokeCompleted(continuation, null);
                        }
                        catch (Exception ex2)
                        {
                            InternalLogger.Error(ex2, "Error when sending to Webservice: {0}", this.Name);
                            if (ex2.MustBeRethrown())
                            {
                                throw;
                            }

                            DoInvokeCompleted(continuation, ex2);
                        }
                    },
                        null);
                }
                catch (Exception ex2)
                {
                    InternalLogger.Error(ex2, "Error when sending to Webservice: {0}", this.Name);
                    if (ex2.MustBeRethrown())
                    {
                        throw;
                    }

                    DoInvokeCompleted(continuation, ex2);
                }
            };

            if (postPayload != null && postPayload.Length > 0)
            {
                postPayload.Position = 0;
                try
                {
                    pendingManualFlushList.BeginOperation();

                    beginFunc(
                        result =>
                    {
                        try
                        {
                            using (Stream stream = getStreamFunc(result))
                            {
                                WriteStreamAndFixPreamble(postPayload, stream, this.IncludeBOM, this.Encoding);

                                postPayload.Dispose();
                            }

                            sendContinuation(null);
                        }
                        catch (Exception ex)
                        {
                            InternalLogger.Error(ex, "Error when sending to Webservice: {0}", this.Name);
                            if (ex.MustBeRethrown())
                            {
                                throw;
                            }

                            postPayload.Dispose();
                            DoInvokeCompleted(continuation, ex);
                        }
                    });
                }
                catch (Exception ex)
                {
                    InternalLogger.Error(ex, "Error when sending to Webservice: {0}", this.Name);
                    if (ex.MustBeRethrown())
                    {
                        throw;
                    }

                    DoInvokeCompleted(continuation, ex);
                }
            }
            else
            {
                pendingManualFlushList.BeginOperation();
                sendContinuation(null);
            }
        }