From 092827902252a11aff3de2b3cbd64be16c13c841 Mon Sep 17 00:00:00 2001 From: Ben Date: Tue, 19 Jul 2022 15:09:05 +0800 Subject: [PATCH 1/2] upgrade log4net to 2.0.14. --- .../log4net/Appender/AdoNetAppender.cs | 2150 ++++++----- .../Appender/AnsiColorTerminalAppender.cs | 1066 +++-- .../log4net/Appender/AppenderCollection.cs | 1581 ++++---- .../log4net/Appender/AppenderSkeleton.cs | 1667 ++++---- .../log4net/Appender/AspNetTraceAppender.cs | 256 +- .../Appender/BufferingAppenderSkeleton.cs | 1214 +++--- .../Appender/BufferingForwardingAppender.cs | 475 ++- .../Appender/ColoredConsoleAppender.cs | 1225 +++--- .../log4net/Appender/ConsoleAppender.cs | 373 +- .../log4net/Appender/DebugAppender.cs | 360 +- .../log4net/Appender/EventLogAppender.cs | 1276 +++--- .../log4net/Appender/FileAppender.cs | 2872 +++++++------- .../log4net/Appender/ForwardingAppender.cs | 497 ++- .../log4net/Appender/IAppender.cs | 148 +- .../log4net/Appender/IBulkAppender.cs | 88 +- .../log4net/Appender/IFlushable.cs | 110 +- .../log4net/Appender/LocalSyslogAppender.cs | 1077 +++--- .../Appender/ManagedColoredConsoleAppender.cs | 623 ++- .../log4net/Appender/MemoryAppender.cs | 380 +- .../log4net/Appender/NetSendAppender.cs | 771 ++-- .../Appender/OutputDebugStringAppender.cs | 227 +- .../log4net/Appender/RemoteSyslogAppender.cs | 1086 +++--- .../log4net/Appender/RemotingAppender.cs | 604 +-- .../log4net/Appender/RollingFileAppender.cs | 3425 +++++++++-------- .../log4net/Appender/SmtpAppender.cs | 1254 +++--- .../log4net/Appender/SmtpPickupDirAppender.cs | 619 ++- .../log4net/Appender/TelnetAppender.cs | 975 +++-- .../log4net/Appender/TextWriterAppender.cs | 917 +++-- .../log4net/Appender/TraceAppender.cs | 386 +- .../log4net/Appender/UdpAppender.cs | 1000 +++-- .../log4net/AssemblyInfo.cs | 287 +- .../log4net/AssemblyVersionInfo.cs | 13 +- .../log4net/Config/AliasDomainAttribute.cs | 132 +- .../Config/AliasRepositoryAttribute.cs | 160 +- .../log4net/Config/BasicConfigurator.cs | 422 +- .../log4net/Config/ConfiguratorAttribute.cs | 213 +- .../log4net/Config/DOMConfigurator.cs | 661 ++-- .../Config/DOMConfiguratorAttribute.cs | 113 +- .../log4net/Config/DomainAttribute.cs | 154 +- .../Log4NetConfigurationSectionHandler.cs | 157 +- .../log4net/Config/PluginAttribute.cs | 327 +- .../log4net/Config/RepositoryAttribute.cs | 237 +- .../SecurityContextProviderAttribute.cs | 235 +- .../log4net/Config/XmlConfigurator.cs | 2176 ++++++----- .../Config/XmlConfiguratorAttribute.cs | 868 +++-- .../log4net/Core/CompactRepositorySelector.cs | 651 ++-- .../log4net/Core/DefaultRepositorySelector.cs | 1709 ++++---- .../log4net/Core/ErrorCode.cs | 132 +- .../log4net/Core/ExceptionEvaluator.cs | 232 +- .../log4net/Core/IAppenderAttachable.cs | 232 +- .../log4net/Core/IErrorHandler.cs | 142 +- .../log4net/Core/IFixingRequired.cs | 108 +- .../log4net/Core/ILogger.cs | 220 +- .../log4net/Core/ILoggerWrapper.cs | 108 +- .../log4net/Core/IOptionHandler.cs | 108 +- .../log4net/Core/IRepositorySelector.cs | 399 +- .../log4net/Core/ITriggeringEventEvaluator.cs | 94 +- .../DotNetNuke.Log4net/log4net/Core/Level.cs | 1128 +++--- .../log4net/Core/LevelCollection.cs | 1505 ++++---- .../log4net/Core/LevelEvaluator.cs | 247 +- .../log4net/Core/LevelMap.cs | 430 +-- .../log4net/Core/LocationInfo.cs | 574 ++- .../log4net/Core/LogException.cs | 192 +- .../log4net/Core/LogImpl.cs | 2519 ++++++------ .../log4net/Core/LoggerManager.cs | 1721 ++++----- .../log4net/Core/LoggerWrapperImpl.cs | 107 +- .../log4net/Core/LoggingEvent.cs | 3211 ++++++++-------- .../log4net/Core/MethodItem.cs | 265 +- .../log4net/Core/SecurityContext.cs | 102 +- .../log4net/Core/SecurityContextProvider.cs | 233 +- .../log4net/Core/StackFrameItem.cs | 311 +- .../log4net/Core/TimeEvaluator.cs | 276 +- .../log4net/Core/WrapperMap.cs | 436 ++- .../AbsoluteTimeDateFormatter.cs | 364 +- .../DateFormatter/DateTimeDateFormatter.cs | 166 +- .../log4net/DateFormatter/IDateFormatter.cs | 102 +- .../DateFormatter/Iso8601DateFormatter.cs | 157 +- .../DateFormatter/SimpleDateFormatter.cs | 145 +- .../log4net/Filter/DenyAllFilter.cs | 115 +- .../log4net/Filter/FilterDecision.cs | 98 +- .../log4net/Filter/FilterSkeleton.cs | 267 +- .../log4net/Filter/IFilter.cs | 194 +- .../log4net/Filter/LevelMatchFilter.cs | 232 +- .../log4net/Filter/LevelRangeFilter.cs | 319 +- .../log4net/Filter/LoggerMatchFilter.cs | 260 +- .../log4net/Filter/MdcFilter.cs | 84 +- .../log4net/Filter/NdcFilter.cs | 107 +- .../log4net/Filter/PropertyFilter.cs | 276 +- .../log4net/Filter/StringMatchFilter.cs | 433 ++- .../log4net/GlobalContext.cs | 153 +- .../DotNetNuke.Log4net/log4net/ILog.cs | 1914 ++++----- .../log4net/Layout/DynamicPatternLayout.cs | 248 +- .../log4net/Layout/ExceptionLayout.cs | 169 +- .../log4net/Layout/ILayout.cs | 232 +- .../log4net/Layout/IRawLayout.cs | 112 +- .../log4net/Layout/Layout2RawLayoutAdapter.cs | 141 +- .../log4net/Layout/LayoutSkeleton.cs | 406 +- .../Pattern/AppDomainPatternConverter.cs | 100 +- .../Pattern/AspNetCachePatternConverter.cs | 150 +- .../Pattern/AspNetContextPatternConverter.cs | 132 +- .../Layout/Pattern/AspNetPatternConverter.cs | 143 +- .../Pattern/AspNetRequestPatternConverter.cs | 168 +- .../Pattern/AspNetSessionPatternConverter.cs | 150 +- .../Layout/Pattern/DatePatternConverter.cs | 338 +- .../Pattern/ExceptionPatternConverter.cs | 264 +- .../Pattern/FileLocationPatternConverter.cs | 102 +- .../Pattern/FullLocationPatternConverter.cs | 98 +- .../Pattern/IdentityPatternConverter.cs | 106 +- .../Layout/Pattern/LevelPatternConverter.cs | 102 +- .../Pattern/LineLocationPatternConverter.cs | 102 +- .../Layout/Pattern/LoggerPatternConverter.cs | 98 +- .../Layout/Pattern/MessagePatternConverter.cs | 102 +- .../Pattern/MethodLocationPatternConverter.cs | 102 +- .../Layout/Pattern/NamedPatternConverter.cs | 303 +- .../Layout/Pattern/NdcPatternConverter.cs | 114 +- .../Layout/Pattern/PatternLayoutConverter.cs | 186 +- .../Pattern/PropertyPatternConverter.cs | 144 +- .../Pattern/RelativeTimePatternConverter.cs | 130 +- .../StackTraceDetailPatternConverter.cs | 161 +- .../Pattern/StackTracePatternConverter.cs | 270 +- .../Layout/Pattern/ThreadPatternConverter.cs | 98 +- .../Pattern/TypeNamePatternConverter.cs | 108 +- .../Pattern/UserNamePatternConverter.cs | 80 +- .../Layout/Pattern/UtcDatePatternConverter.cs | 158 +- .../log4net/Layout/PatternLayout.cs | 2222 ++++++----- .../log4net/Layout/RawLayoutConverter.cs | 157 +- .../log4net/Layout/RawPropertyLayout.cs | 141 +- .../log4net/Layout/RawTimeStampLayout.cs | 113 +- .../log4net/Layout/RawUtcTimeStampLayout.cs | 113 +- .../log4net/Layout/SimpleLayout.cs | 175 +- .../log4net/Layout/XMLLayout.cs | 627 ++- .../log4net/Layout/XMLLayoutBase.cs | 426 +- .../log4net/Layout/XmlLayoutSchemaLog4j.cs | 447 ++- .../log4net/Log4netAssemblyInfo.cs | 8 +- .../DotNetNuke.Log4net/log4net/LogManager.cs | 1596 ++++---- .../log4net/LogicalThreadContext.cs | 260 +- .../DotNetNuke.Log4net/log4net/MDC.cs | 305 +- .../DotNetNuke.Log4net/log4net/NDC.cs | 654 ++-- .../log4net/ObjectRenderer/DefaultRenderer.cs | 582 ++- .../log4net/ObjectRenderer/IObjectRenderer.cs | 114 +- .../log4net/ObjectRenderer/RendererMap.cs | 633 ++- .../log4net/Plugin/IPlugin.cs | 162 +- .../log4net/Plugin/IPluginFactory.cs | 62 +- .../log4net/Plugin/PluginCollection.cs | 1537 ++++---- .../log4net/Plugin/PluginMap.cs | 318 +- .../log4net/Plugin/PluginSkeleton.cs | 239 +- .../Plugin/RemoteLoggingServerPlugin.cs | 435 +-- .../ConfigurationChangedEventArgs.cs | 89 +- .../Hierarchy/DefaultLoggerFactory.cs | 192 +- .../log4net/Repository/Hierarchy/Hierarchy.cs | 1986 +++++----- .../Repository/Hierarchy/ILoggerFactory.cs | 100 +- .../log4net/Repository/Hierarchy/Logger.cs | 1499 ++++---- .../log4net/Repository/Hierarchy/LoggerKey.cs | 227 +- .../Repository/Hierarchy/ProvisionNode.cs | 106 +- .../Repository/Hierarchy/RootLogger.cs | 219 +- .../Hierarchy/XmlHierarchyConfigurator.cs | 2237 ++++++----- .../IBasicRepositoryConfigurator.cs | 98 +- .../log4net/Repository/ILoggerRepository.cs | 655 ++-- .../Repository/IXmlRepositoryConfigurator.cs | 101 +- .../Repository/LoggerRepositorySkeleton.cs | 1186 +++--- .../log4net/ThreadContext.cs | 231 +- .../log4net/Util/AppenderAttachedImpl.cs | 662 ++-- .../log4net/Util/CompositeProperties.cs | 248 +- .../log4net/Util/ContextPropertiesBase.cs | 89 +- .../log4net/Util/ConverterInfo.cs | 176 +- .../log4net/Util/CountingQuietTextWriter.cs | 302 +- .../log4net/Util/CyclicBuffer.cs | 648 ++-- .../log4net/Util/EmptyCollection.cs | 288 +- .../log4net/Util/EmptyDictionary.cs | 598 +-- .../log4net/Util/FormattingInfo.cs | 223 +- .../log4net/Util/GlobalContextProperties.cs | 281 +- .../log4net/Util/ILogExtensions.cs | 2974 +++++++------- .../log4net/Util/LevelMapping.cs | 240 +- .../log4net/Util/LevelMappingEntry.cs | 141 +- .../DotNetNuke.Log4net/log4net/Util/LogLog.cs | 1272 +++--- .../Util/LogicalThreadContextProperties.cs | 465 +-- .../log4net/Util/LogicalThreadContextStack.cs | 698 ++-- .../Util/LogicalThreadContextStacks.cs | 228 +- .../log4net/Util/NativeError.cs | 500 +-- .../log4net/Util/NullDictionaryEnumerator.cs | 336 +- .../log4net/Util/NullEnumerator.cs | 212 +- .../log4net/Util/NullSecurityContext.cs | 137 +- .../log4net/Util/OnlyOnceErrorHandler.cs | 478 ++- .../log4net/Util/OptionConverter.cs | 1285 +++---- .../log4net/Util/PatternConverter.cs | 696 ++-- .../log4net/Util/PatternParser.cs | 753 ++-- .../log4net/Util/PatternString.cs | 950 +++-- .../AppDomainPatternConverter.cs | 98 +- .../AppSettingPatternConverter.cs | 209 +- .../DatePatternConverter.cs | 338 +- .../EnvironmentFolderPathPatternConverter.cs | 176 +- .../EnvironmentPatternConverter.cs | 206 +- .../IdentityPatternConverter.cs | 152 +- .../LiteralPatternConverter.cs | 204 +- .../NewLinePatternConverter.cs | 152 +- .../ProcessIdPatternConverter.cs | 145 +- .../PropertyPatternConverter.cs | 181 +- .../RandomStringPatternConverter.cs | 272 +- .../UserNamePatternConverter.cs | 149 +- .../UtcDatePatternConverter.cs | 148 +- .../log4net/Util/PropertiesDictionary.cs | 567 ++- .../log4net/Util/PropertyEntry.cs | 155 +- .../log4net/Util/ProtectCloseTextWriter.cs | 140 +- .../log4net/Util/QuietTextWriter.cs | 351 +- .../Util/ReadOnlyPropertiesDictionary.cs | 654 ++-- .../log4net/Util/ReaderWriterLock.cs | 341 +- .../log4net/Util/ReusableStringWriter.cs | 166 +- .../log4net/Util/SystemInfo.cs | 2554 ++++++------ .../log4net/Util/SystemStringFormat.cs | 421 +- .../log4net/Util/TextWriterAdapter.cs | 412 +- .../log4net/Util/ThreadContextProperties.cs | 329 +- .../log4net/Util/ThreadContextStack.cs | 722 ++-- .../log4net/Util/ThreadContextStacks.cs | 198 +- .../log4net/Util/Transform.cs | 341 +- .../Util/TypeConverters/BooleanConverter.cs | 149 +- .../ConversionNotSupportedException.cs | 265 +- .../Util/TypeConverters/ConverterRegistry.cs | 541 +-- .../Util/TypeConverters/EncodingConverter.cs | 151 +- .../Util/TypeConverters/IConvertFrom.cs | 118 +- .../log4net/Util/TypeConverters/IConvertTo.cs | 118 +- .../Util/TypeConverters/IPAddressConverter.cs | 273 +- .../TypeConverters/PatternLayoutConverter.cs | 161 +- .../TypeConverters/PatternStringConverter.cs | 247 +- .../Util/TypeConverters/TypeConverter.cs | 167 +- .../TypeConverters/TypeConverterAttribute.cs | 187 +- .../log4net/Util/WindowsSecurityContext.cs | 671 ++-- 226 files changed, 55286 insertions(+), 55627 deletions(-) diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/AdoNetAppender.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/AdoNetAppender.cs index bd710e03838..024a3a594de 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/AdoNetAppender.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/AdoNetAppender.cs @@ -1,1098 +1,1124 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -// SSCLI 1.0 has no support for ADO.NET -#if !SSCLI - -using System; -using System.Collections; -using System.Configuration; -using System.Data; -using System.IO; - -using log4net.Core; -using log4net.Layout; -using log4net.Util; - -namespace log4net.Appender -{ - /// - /// Appender that logs to a database. - /// - /// - /// - /// appends logging events to a table within a - /// database. The appender can be configured to specify the connection - /// string by setting the property. - /// The connection type (provider) can be specified by setting the - /// property. For more information on database connection strings for - /// your specific database see http://www.connectionstrings.com/. - /// - /// - /// Records are written into the database either using a prepared - /// statement or a stored procedure. The property - /// is set to (System.Data.CommandType.Text) to specify a prepared statement - /// or to (System.Data.CommandType.StoredProcedure) to specify a stored - /// procedure. - /// - /// - /// The prepared statement text or the name of the stored procedure - /// must be set in the property. - /// - /// - /// The prepared statement or stored procedure can take a number - /// of parameters. Parameters are added using the - /// method. This adds a single to the - /// ordered list of parameters. The - /// type may be subclassed if required to provide database specific - /// functionality. The specifies - /// the parameter name, database type, size, and how the value should - /// be generated using a . - /// - /// - /// - /// An example of a SQL Server table that could be logged to: - /// - /// CREATE TABLE [dbo].[Log] ( - /// [ID] [int] IDENTITY (1, 1) NOT NULL , - /// [Date] [datetime] NOT NULL , - /// [Thread] [varchar] (255) NOT NULL , - /// [Level] [varchar] (20) NOT NULL , - /// [Logger] [varchar] (255) NOT NULL , - /// [Message] [varchar] (4000) NOT NULL - /// ) ON [PRIMARY] - /// - /// - /// - /// An example configuration to log to the above table: - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// Julian Biddle. - /// Nicko Cadell. - /// Gert Driesen. - /// Lance Nehring. - public class AdoNetAppender : BufferingAppenderSkeleton +// SSCLI 1.0 has no support for ADO.NET +#if !SSCLI + +using System; +using System.Collections; +#if !NETSTANDARD1_3 +using System.Configuration; +#endif +using System.Data; +using System.IO; +#if NETSTANDARD1_3 +using System.Reflection; +#endif + +using log4net.Util; +using log4net.Layout; +using log4net.Core; + +namespace log4net.Appender +{ + /// + /// Appender that logs to a database. + /// + /// + /// + /// appends logging events to a table within a + /// database. The appender can be configured to specify the connection + /// string by setting the property. + /// The connection type (provider) can be specified by setting the + /// property. For more information on database connection strings for + /// your specific database see http://www.connectionstrings.com/. + /// + /// + /// Records are written into the database either using a prepared + /// statement or a stored procedure. The property + /// is set to (System.Data.CommandType.Text) to specify a prepared statement + /// or to (System.Data.CommandType.StoredProcedure) to specify a stored + /// procedure. + /// + /// + /// The prepared statement text or the name of the stored procedure + /// must be set in the property. + /// + /// + /// The prepared statement or stored procedure can take a number + /// of parameters. Parameters are added using the + /// method. This adds a single to the + /// ordered list of parameters. The + /// type may be subclassed if required to provide database specific + /// functionality. The specifies + /// the parameter name, database type, size, and how the value should + /// be generated using a . + /// + /// + /// + /// An example of a SQL Server table that could be logged to: + /// + /// CREATE TABLE [dbo].[Log] ( + /// [ID] [int] IDENTITY (1, 1) NOT NULL , + /// [Date] [datetime] NOT NULL , + /// [Thread] [varchar] (255) NOT NULL , + /// [Level] [varchar] (20) NOT NULL , + /// [Logger] [varchar] (255) NOT NULL , + /// [Message] [varchar] (4000) NOT NULL + /// ) ON [PRIMARY] + /// + /// + /// + /// An example configuration to log to the above table: + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// Julian Biddle + /// Nicko Cadell + /// Gert Driesen + /// Lance Nehring + public class AdoNetAppender : BufferingAppenderSkeleton { - /// - /// Initializes a new instance of the class. - /// - /// - /// Public default constructor to initialize a new instance of this class. - /// - public AdoNetAppender() - { - this.ConnectionType = "System.Data.OleDb.OleDbConnection, System.Data, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; - this.UseTransactions = true; - this.CommandType = System.Data.CommandType.Text; - this.m_parameters = new ArrayList(); - this.ReconnectOnError = false; + /// + /// Initializes a new instance of the class. + /// + /// + /// Public default constructor to initialize a new instance of this class. + /// + public AdoNetAppender() + { + this.ConnectionType = "System.Data.OleDb.OleDbConnection, System.Data, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; + this.UseTransactions = true; + this.CommandType = CommandType.Text; + this.m_parameters = new ArrayList(); + this.ReconnectOnError = false; + } + + /// + /// Gets or sets the database connection string that is used to connect to + /// the database. + /// + /// + /// The database connection string used to connect to the database. + /// + /// + /// + /// The connections string is specific to the connection type. + /// See for more information. + /// + /// + /// Connection string for MS Access via ODBC: + /// "DSN=MS Access Database;UID=admin;PWD=;SystemDB=C:\data\System.mdw;SafeTransactions = 0;FIL=MS Access;DriverID = 25;DBQ=C:\data\train33.mdb" + /// + /// Another connection string for MS Access via ODBC: + /// "Driver={Microsoft Access Driver (*.mdb)};DBQ=C:\Work\cvs_root\log4net-1.2\access.mdb;UID=;PWD=;" + /// + /// Connection string for MS Access via OLE DB: + /// "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Work\cvs_root\log4net-1.2\access.mdb;User Id=;Password=;" + /// + public string ConnectionString + { + get { return this.m_connectionString; } + set { this.m_connectionString = value; } + } + + /// + /// The appSettings key from App.Config that contains the connection string. + /// + public string AppSettingsKey + { + get { return this.m_appSettingsKey; } + set { this.m_appSettingsKey = value; } + } + + /// + /// The connectionStrings key from App.Config that contains the connection string. + /// + /// + /// This property requires at least .NET 2.0. + /// + public string ConnectionStringName + { + get { return this.m_connectionStringName; } + set { this.m_connectionStringName = value; } + } + + /// + /// Gets or sets the type name of the connection + /// that should be created. + /// + /// + /// The type name of the connection. + /// + /// + /// + /// The type name of the ADO.NET provider to use. + /// + /// + /// The default is to use the OLE DB provider. + /// + /// + /// Use the OLE DB Provider. This is the default value. + /// System.Data.OleDb.OleDbConnection, System.Data, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + /// + /// Use the MS SQL Server Provider. + /// System.Data.SqlClient.SqlConnection, System.Data, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + /// + /// Use the ODBC Provider. + /// Microsoft.Data.Odbc.OdbcConnection,Microsoft.Data.Odbc,version=1.0.3300.0,publicKeyToken=b77a5c561934e089,culture=neutral + /// This is an optional package that you can download from + /// http://msdn.microsoft.com/downloads + /// search for ODBC .NET Data Provider. + /// + /// Use the Oracle Provider. + /// System.Data.OracleClient.OracleConnection, System.Data.OracleClient, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + /// This is an optional package that you can download from + /// http://msdn.microsoft.com/downloads + /// search for .NET Managed Provider for Oracle. + /// + public string ConnectionType + { + get { return this.m_connectionType; } + set { this.m_connectionType = value; } + } + + /// + /// Gets or sets the command text that is used to insert logging events + /// into the database. + /// + /// + /// The command text used to insert logging events into the database. + /// + /// + /// + /// Either the text of the prepared statement or the + /// name of the stored procedure to execute to write into + /// the database. + /// + /// + /// The property determines if + /// this text is a prepared statement or a stored procedure. + /// + /// + /// If this property is not set, the command text is retrieved by invoking + /// . + /// + /// + public string CommandText + { + get { return this.m_commandText; } + set { this.m_commandText = value; } + } + + /// + /// Gets or sets the command type to execute. + /// + /// + /// The command type to execute. + /// + /// + /// + /// This value may be either (System.Data.CommandType.Text) to specify + /// that the is a prepared statement to execute, + /// or (System.Data.CommandType.StoredProcedure) to specify that the + /// property is the name of a stored procedure + /// to execute. + /// + /// + /// The default value is (System.Data.CommandType.Text). + /// + /// + public CommandType CommandType + { + get { return this.m_commandType; } + set { this.m_commandType = value; } + } + + /// + /// Should transactions be used to insert logging events in the database. + /// + /// + /// true if transactions should be used to insert logging events in + /// the database, otherwise false. The default value is true. + /// + /// + /// + /// Gets or sets a value that indicates whether transactions should be used + /// to insert logging events in the database. + /// + /// + /// When set a single transaction will be used to insert the buffered events + /// into the database. Otherwise each event will be inserted without using + /// an explicit transaction. + /// + /// + public bool UseTransactions + { + get { return this.m_useTransactions; } + set { this.m_useTransactions = value; } + } + + /// + /// Gets or sets the used to call the NetSend method. + /// + /// + /// The used to call the NetSend method. + /// + /// + /// + /// Unless a specified here for this appender + /// the is queried for the + /// security context to use. The default behavior is to use the security context + /// of the current thread. + /// + /// + public SecurityContext SecurityContext + { + get { return this.m_securityContext; } + set { this.m_securityContext = value; } + } + + /// + /// Should this appender try to reconnect to the database on error. + /// + /// + /// true if the appender should try to reconnect to the database after an + /// error has occurred, otherwise false. The default value is false, + /// i.e. not to try to reconnect. + /// + /// + /// + /// The default behaviour is for the appender not to try to reconnect to the + /// database if an error occurs. Subsequent logging events are discarded. + /// + /// + /// To force the appender to attempt to reconnect to the database set this + /// property to true. + /// + /// + /// When the appender attempts to connect to the database there may be a + /// delay of up to the connection timeout specified in the connection string. + /// This delay will block the calling application's thread. + /// Until the connection can be reestablished this potential delay may occur multiple times. + /// + /// + public bool ReconnectOnError + { + get { return this.m_reconnectOnError; } + set { this.m_reconnectOnError = value; } + } + + /// + /// Gets or sets the underlying . + /// + /// + /// The underlying . + /// + /// + /// creates a to insert + /// logging events into a database. Classes deriving from + /// can use this property to get or set this . Use the + /// underlying returned from if + /// you require access beyond that which provides. + /// + protected IDbConnection Connection + { + get { return this.m_dbConnection; } + set { this.m_dbConnection = value; } } - /// - /// Gets or sets the database connection string that is used to connect to - /// the database. - /// - /// - /// The database connection string used to connect to the database. - /// - /// - /// - /// The connections string is specific to the connection type. - /// See for more information. - /// - /// - /// Connection string for MS Access via ODBC: - /// "DSN=MS Access Database;UID=admin;PWD=;SystemDB=C:\data\System.mdw;SafeTransactions = 0;FIL=MS Access;DriverID = 25;DBQ=C:\data\train33.mdb" - /// - /// Another connection string for MS Access via ODBC: - /// "Driver={Microsoft Access Driver (*.mdb)};DBQ=C:\Work\cvs_root\log4net-1.2\access.mdb;UID=;PWD=;" - /// - /// Connection string for MS Access via OLE DB: - /// "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Work\cvs_root\log4net-1.2\access.mdb;User Id=;Password=;" - /// - public string ConnectionString - { - get { return this.m_connectionString; } - set { this.m_connectionString = value; } - } - - /// - /// Gets or sets the appSettings key from App.Config that contains the connection string. - /// - public string AppSettingsKey - { - get { return this.m_appSettingsKey; } - set { this.m_appSettingsKey = value; } - } - -#if NET_2_0 - /// - /// Gets or sets the connectionStrings key from App.Config that contains the connection string. - /// - /// - /// This property requires at least .NET 2.0. - /// - public string ConnectionStringName - { - get { return this.m_connectionStringName; } - set { this.m_connectionStringName = value; } - } -#endif - - /// - /// Gets or sets the type name of the connection - /// that should be created. - /// - /// - /// The type name of the connection. - /// - /// - /// - /// The type name of the ADO.NET provider to use. - /// - /// - /// The default is to use the OLE DB provider. - /// - /// - /// Use the OLE DB Provider. This is the default value. - /// System.Data.OleDb.OleDbConnection, System.Data, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - /// - /// Use the MS SQL Server Provider. - /// System.Data.SqlClient.SqlConnection, System.Data, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - /// - /// Use the ODBC Provider. - /// Microsoft.Data.Odbc.OdbcConnection,Microsoft.Data.Odbc,version=1.0.3300.0,publicKeyToken=b77a5c561934e089,culture=neutral - /// This is an optional package that you can download from - /// http://msdn.microsoft.com/downloads - /// search for ODBC .NET Data Provider. - /// - /// Use the Oracle Provider. - /// System.Data.OracleClient.OracleConnection, System.Data.OracleClient, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - /// This is an optional package that you can download from - /// http://msdn.microsoft.com/downloads - /// search for .NET Managed Provider for Oracle. - /// - public string ConnectionType - { - get { return this.m_connectionType; } - set { this.m_connectionType = value; } - } - - /// - /// Gets or sets the command text that is used to insert logging events - /// into the database. - /// - /// - /// The command text used to insert logging events into the database. - /// - /// - /// - /// Either the text of the prepared statement or the - /// name of the stored procedure to execute to write into - /// the database. - /// - /// - /// The property determines if - /// this text is a prepared statement or a stored procedure. - /// - /// - /// If this property is not set, the command text is retrieved by invoking - /// . - /// - /// - public string CommandText - { - get { return this.m_commandText; } - set { this.m_commandText = value; } - } - - /// - /// Gets or sets the command type to execute. - /// - /// - /// The command type to execute. - /// - /// - /// - /// This value may be either (System.Data.CommandType.Text) to specify - /// that the is a prepared statement to execute, - /// or (System.Data.CommandType.StoredProcedure) to specify that the - /// property is the name of a stored procedure - /// to execute. - /// - /// - /// The default value is (System.Data.CommandType.Text). - /// - /// - public CommandType CommandType - { - get { return this.m_commandType; } - set { this.m_commandType = value; } - } - - /// - /// Gets or sets a value indicating whether should transactions be used to insert logging events in the database. - /// - /// - /// true if transactions should be used to insert logging events in - /// the database, otherwise false. The default value is true. - /// - /// - /// - /// Gets or sets a value that indicates whether transactions should be used - /// to insert logging events in the database. - /// - /// - /// When set a single transaction will be used to insert the buffered events - /// into the database. Otherwise each event will be inserted without using - /// an explicit transaction. - /// - /// - public bool UseTransactions - { - get { return this.m_useTransactions; } - set { this.m_useTransactions = value; } - } - - /// - /// Gets or sets the used to call the NetSend method. - /// - /// - /// The used to call the NetSend method. - /// - /// - /// - /// Unless a specified here for this appender - /// the is queried for the - /// security context to use. The default behavior is to use the security context - /// of the current thread. - /// - /// - public SecurityContext SecurityContext - { - get { return this.m_securityContext; } - set { this.m_securityContext = value; } - } - - /// - /// Gets or sets a value indicating whether should this appender try to reconnect to the database on error. - /// - /// - /// true if the appender should try to reconnect to the database after an - /// error has occurred, otherwise false. The default value is false, - /// i.e. not to try to reconnect. - /// - /// - /// - /// The default behaviour is for the appender not to try to reconnect to the - /// database if an error occurs. Subsequent logging events are discarded. - /// - /// - /// To force the appender to attempt to reconnect to the database set this - /// property to true. - /// - /// - /// When the appender attempts to connect to the database there may be a - /// delay of up to the connection timeout specified in the connection string. - /// This delay will block the calling application's thread. - /// Until the connection can be reestablished this potential delay may occur multiple times. - /// - /// - public bool ReconnectOnError - { - get { return this.m_reconnectOnError; } - set { this.m_reconnectOnError = value; } + /// + /// Initialize the appender based on the options set + /// + /// + /// + /// This is part of the delayed object + /// activation scheme. The method must + /// be called on this object after the configuration properties have + /// been set. Until is called this + /// object is in an undefined state and must not be used. + /// + /// + /// If any of the configuration properties are modified then + /// must be called again. + /// + /// + public override void ActivateOptions() + { + base.ActivateOptions(); + + if (this.SecurityContext == null) + { + this.SecurityContext = SecurityContextProvider.DefaultProvider.CreateSecurityContext(this); + } + + this.InitializeDatabaseConnection(); + } + + /// + /// Override the parent method to close the database + /// + /// + /// + /// Closes the database command and database connection. + /// + /// + protected override void OnClose() + { + base.OnClose(); + this.DiposeConnection(); + } + + /// + /// Inserts the events into the database. + /// + /// The events to insert into the database. + /// + /// + /// Insert all the events specified in the + /// array into the database. + /// + /// + protected override void SendBuffer(LoggingEvent[] events) + { + if (this.ReconnectOnError && (this.Connection == null || this.Connection.State != ConnectionState.Open)) + { + LogLog.Debug(declaringType, "Attempting to reconnect to database. Current Connection State: " + ((this.Connection == null) ? SystemInfo.NullText : this.Connection.State.ToString())); + + this.InitializeDatabaseConnection(); + } + + // Check that the connection exists and is open + if (this.Connection != null && this.Connection.State == ConnectionState.Open) + { + if (this.UseTransactions) + { + // Create transaction + // NJC - Do this on 2 lines because it can confuse the debugger + using (IDbTransaction dbTran = this.Connection.BeginTransaction()) + { + try + { + this.SendBuffer(dbTran, events); + + // commit transaction + dbTran.Commit(); + } + catch (Exception ex) + { + // rollback the transaction + try + { + dbTran.Rollback(); + } + catch (Exception) + { + // Ignore exception + } + + // Can't insert into the database. That's a bad thing + this.ErrorHandler.Error("Exception while writing to database", ex); + } + } + } + else + { + // Send without transaction + this.SendBuffer(null, events); + } + } + } + + /// + /// Adds a parameter to the command. + /// + /// The parameter to add to the command. + /// + /// + /// Adds a parameter to the ordered list of command parameters. + /// + /// + public void AddParameter(AdoNetAppenderParameter parameter) + { + this.m_parameters.Add(parameter); + } + + + /// + /// Writes the events to the database using the transaction specified. + /// + /// The transaction that the events will be executed under. + /// The array of events to insert into the database. + /// + /// + /// The transaction argument can be null if the appender has been + /// configured not to use transactions. See + /// property for more information. + /// + /// + protected virtual void SendBuffer(IDbTransaction dbTran, LoggingEvent[] events) + { + // string.IsNotNullOrWhiteSpace() does not exist in ancient .NET frameworks + if (this.CommandText != null && this.CommandText.Trim() != string.Empty) + { + using (IDbCommand dbCmd = this.Connection.CreateCommand()) + { + // Set the command string + dbCmd.CommandText = this.CommandText; + + // Set the command type + dbCmd.CommandType = this.CommandType; + // Send buffer using the prepared command object + if (dbTran != null) + { + dbCmd.Transaction = dbTran; + } + + try + { + // prepare the command, which is significantly faster + this.Prepare(dbCmd); + } + catch (Exception) + { + if (dbTran != null) + { + // rethrow exception in transaction mode, cuz now transaction is in failed state + throw; + } + + // ignore prepare exceptions as they can happen without affecting actual logging, eg on npgsql + } + + // run for all events + foreach (LoggingEvent e in events) + { + // No need to clear dbCmd.Parameters, just use existing. + // Set the parameter values + foreach (AdoNetAppenderParameter param in this.m_parameters) + { + param.FormatValue(dbCmd, e); + } + + // Execute the query + dbCmd.ExecuteNonQuery(); + } + } + } + else + { + // create a new command + using (IDbCommand dbCmd = this.Connection.CreateCommand()) + { + if (dbTran != null) + { + dbCmd.Transaction = dbTran; + } + // run for all events + foreach (LoggingEvent e in events) + { + // Get the command text from the Layout + string logStatement = this.GetLogStatement(e); + + LogLog.Debug(declaringType, "LogStatement [" + logStatement + "]"); + + dbCmd.CommandText = logStatement; + dbCmd.ExecuteNonQuery(); + } + } + } } - /// - /// Gets or sets the underlying . - /// - /// - /// The underlying . - /// - /// - /// creates a to insert - /// logging events into a database. Classes deriving from - /// can use this property to get or set this . Use the - /// underlying returned from if - /// you require access beyond that which provides. - /// - protected IDbConnection Connection - { - get { return this.m_dbConnection; } - set { this.m_dbConnection = value; } + /// + /// Prepare entire database command object to be executed. + /// + /// The command to prepare. + protected virtual void Prepare(IDbCommand dbCmd) + { + // npgsql require parameters to prepare command + foreach (AdoNetAppenderParameter parameter in this.m_parameters) + { + parameter.Prepare(dbCmd); + } + + dbCmd.Prepare(); } - /// - /// Initialize the appender based on the options set. - /// - /// - /// - /// This is part of the delayed object - /// activation scheme. The method must - /// be called on this object after the configuration properties have - /// been set. Until is called this - /// object is in an undefined state and must not be used. - /// - /// - /// If any of the configuration properties are modified then - /// must be called again. - /// - /// - public override void ActivateOptions() - { - base.ActivateOptions(); - - if (this.SecurityContext == null) - { - this.SecurityContext = SecurityContextProvider.DefaultProvider.CreateSecurityContext(this); - } - - this.InitializeDatabaseConnection(); + /// + /// Formats the log message into database statement text. + /// + /// The event being logged. + /// + /// This method can be overridden by subclasses to provide + /// more control over the format of the database statement. + /// + /// + /// Text that can be passed to a . + /// + protected virtual string GetLogStatement(LoggingEvent logEvent) + { + if (this.Layout == null) + { + this.ErrorHandler.Error("AdoNetAppender: No Layout specified."); + return string.Empty; + } + else + { + using (var writer = new StringWriter(System.Globalization.CultureInfo.InvariantCulture)) + { + this.Layout.Format(writer, logEvent); + return writer.ToString(); + } + } } - /// - /// Override the parent method to close the database. - /// - /// - /// - /// Closes the database command and database connection. - /// - /// - protected override void OnClose() - { - base.OnClose(); - this.DiposeConnection(); + /// + /// Creates an instance used to connect to the database. + /// + /// + /// This method is called whenever a new IDbConnection is needed (i.e. when a reconnect is necessary). + /// + /// The of the object. + /// The connectionString output from the ResolveConnectionString method. + /// An instance with a valid connection string. + protected virtual IDbConnection CreateConnection(Type connectionType, string connectionString) + { + IDbConnection connection = (IDbConnection)Activator.CreateInstance(connectionType); + connection.ConnectionString = connectionString; + return connection; } - /// - /// Inserts the events into the database. - /// - /// The events to insert into the database. - /// - /// - /// Insert all the events specified in the - /// array into the database. - /// - /// - protected override void SendBuffer(LoggingEvent[] events) - { - if (this.ReconnectOnError && (this.Connection == null || this.Connection.State != ConnectionState.Open)) - { - LogLog.Debug(declaringType, "Attempting to reconnect to database. Current Connection State: " + ((this.Connection == null) ? SystemInfo.NullText : this.Connection.State.ToString())); - - this.InitializeDatabaseConnection(); - } - - // Check that the connection exists and is open - if (this.Connection != null && this.Connection.State == ConnectionState.Open) - { - if (this.UseTransactions) - { - // Create transaction - // NJC - Do this on 2 lines because it can confuse the debugger - using (IDbTransaction dbTran = this.Connection.BeginTransaction()) - { - try - { - this.SendBuffer(dbTran, events); - - // commit transaction - dbTran.Commit(); - } - catch (Exception ex) - { - // rollback the transaction - try - { - dbTran.Rollback(); - } - catch (Exception) - { - // Ignore exception - } - - // Can't insert into the database. That's a bad thing - this.ErrorHandler.Error("Exception while writing to database", ex); - } - } - } - else - { - // Send without transaction - this.SendBuffer(null, events); - } - } + /// + /// Resolves the connection string from the ConnectionString, ConnectionStringName, or AppSettingsKey + /// property. + /// + /// + /// ConnectiongStringName is only supported on .NET 2.0 and higher. + /// + /// Additional information describing the connection string. + /// A connection string used to connect to the database. + protected virtual string ResolveConnectionString(out string connectionStringContext) + { + if (this.ConnectionString != null && this.ConnectionString.Length > 0) + { + connectionStringContext = "ConnectionString"; + return this.ConnectionString; + } + +#if !NETSTANDARD1_3 + if (!String.IsNullOrEmpty(this.ConnectionStringName)) + { + ConnectionStringSettings settings = ConfigurationManager.ConnectionStrings[this.ConnectionStringName]; + if (settings != null) + { + connectionStringContext = "ConnectionStringName"; + return settings.ConnectionString; + } + else + { + throw new LogException("Unable to find [" + this.ConnectionStringName + "] ConfigurationManager.ConnectionStrings item"); + } + } +#endif + + if (this.AppSettingsKey != null && this.AppSettingsKey.Length > 0) + { + connectionStringContext = "AppSettingsKey"; + string appSettingsConnectionString = SystemInfo.GetAppSetting(this.AppSettingsKey); + if (appSettingsConnectionString == null || appSettingsConnectionString.Length == 0) + { + throw new LogException("Unable to find [" + this.AppSettingsKey + "] AppSettings key."); + } + return appSettingsConnectionString; + } + + connectionStringContext = "Unable to resolve connection string from ConnectionString, ConnectionStrings, or AppSettings."; + return string.Empty; } - /// - /// Adds a parameter to the command. - /// - /// The parameter to add to the command. - /// - /// - /// Adds a parameter to the ordered list of command parameters. - /// - /// - public void AddParameter(AdoNetAppenderParameter parameter) - { - this.m_parameters.Add(parameter); + /// + /// Retrieves the class type of the ADO.NET provider. + /// + /// + /// + /// Gets the Type of the ADO.NET provider to use to connect to the + /// database. This method resolves the type specified in the + /// property. + /// + /// + /// Subclasses can override this method to return a different type + /// if necessary. + /// + /// + /// The of the ADO.NET provider + protected virtual Type ResolveConnectionType() + { + try + { +#if NETSTANDARD1_3 + // NETSTANDARD1_3 requires comma separated ConnectionType like `System.Data.SqlClient.SqlConnection, System.Data` to work properly. + return SystemInfo.GetTypeFromString((Assembly)null, ConnectionType, true, false); +#else + return SystemInfo.GetTypeFromString(this.ConnectionType, true, false); +#endif + } + catch (Exception ex) + { + this.ErrorHandler.Error("Failed to load connection type [" + this.ConnectionType + "]", ex); + throw; + } } - /// - /// Writes the events to the database using the transaction specified. - /// - /// The transaction that the events will be executed under. - /// The array of events to insert into the database. - /// - /// - /// The transaction argument can be null if the appender has been - /// configured not to use transactions. See - /// property for more information. - /// - /// - protected virtual void SendBuffer(IDbTransaction dbTran, LoggingEvent[] events) - { - // string.IsNotNullOrWhiteSpace() does not exist in ancient .NET frameworks - if (this.CommandText != null && this.CommandText.Trim() != string.Empty) - { - using (IDbCommand dbCmd = this.Connection.CreateCommand()) - { - // Set the command string - dbCmd.CommandText = this.CommandText; - - // Set the command type - dbCmd.CommandType = this.CommandType; - - // Send buffer using the prepared command object - if (dbTran != null) - { - dbCmd.Transaction = dbTran; - } - - // prepare the command, which is significantly faster - dbCmd.Prepare(); - - // run for all events - foreach (LoggingEvent e in events) - { - // clear parameters that have been set - dbCmd.Parameters.Clear(); - - // Set the parameter values - foreach (AdoNetAppenderParameter param in this.m_parameters) - { - param.Prepare(dbCmd); - param.FormatValue(dbCmd, e); - } - - // Execute the query - dbCmd.ExecuteNonQuery(); - } - } - } - else - { - // create a new command - using (IDbCommand dbCmd = this.Connection.CreateCommand()) - { - if (dbTran != null) - { - dbCmd.Transaction = dbTran; - } - - // run for all events - foreach (LoggingEvent e in events) - { - // Get the command text from the Layout - string logStatement = this.GetLogStatement(e); - - LogLog.Debug(declaringType, "LogStatement [" + logStatement + "]"); - - dbCmd.CommandText = logStatement; - dbCmd.ExecuteNonQuery(); - } - } - } - } - - /// - /// Formats the log message into database statement text. - /// - /// The event being logged. - /// - /// This method can be overridden by subclasses to provide - /// more control over the format of the database statement. - /// - /// - /// Text that can be passed to a . - /// - protected virtual string GetLogStatement(LoggingEvent logEvent) - { - if (this.Layout == null) - { - this.ErrorHandler.Error("AdoNetAppender: No Layout specified."); - return string.Empty; - } - else - { - StringWriter writer = new StringWriter(System.Globalization.CultureInfo.InvariantCulture); - this.Layout.Format(writer, logEvent); - return writer.ToString(); - } - } - - /// - /// Creates an instance used to connect to the database. - /// - /// - /// This method is called whenever a new IDbConnection is needed (i.e. when a reconnect is necessary). - /// - /// The of the object. - /// The connectionString output from the ResolveConnectionString method. - /// An instance with a valid connection string. - protected virtual IDbConnection CreateConnection(Type connectionType, string connectionString) - { - IDbConnection connection = (IDbConnection)Activator.CreateInstance(connectionType); - connection.ConnectionString = connectionString; - return connection; - } - - /// - /// Resolves the connection string from the ConnectionString, ConnectionStringName, or AppSettingsKey - /// property. - /// - /// - /// ConnectiongStringName is only supported on .NET 2.0 and higher. - /// - /// Additional information describing the connection string. - /// A connection string used to connect to the database. - protected virtual string ResolveConnectionString(out string connectionStringContext) - { - if (this.ConnectionString != null && this.ConnectionString.Length > 0) - { - connectionStringContext = "ConnectionString"; - return this.ConnectionString; - } - -#if NET_2_0 - if (!string.IsNullOrEmpty(this.ConnectionStringName)) - { - ConnectionStringSettings settings = ConfigurationManager.ConnectionStrings[this.ConnectionStringName]; - if (settings != null) - { - connectionStringContext = "ConnectionStringName"; - return settings.ConnectionString; - } - else - { - throw new LogException("Unable to find [" + this.ConnectionStringName + "] ConfigurationManager.ConnectionStrings item"); - } - } -#endif - - if (this.AppSettingsKey != null && this.AppSettingsKey.Length > 0) - { - connectionStringContext = "AppSettingsKey"; - string appSettingsConnectionString = SystemInfo.GetAppSetting(this.AppSettingsKey); - if (appSettingsConnectionString == null || appSettingsConnectionString.Length == 0) - { - throw new LogException("Unable to find [" + this.AppSettingsKey + "] AppSettings key."); - } - - return appSettingsConnectionString; - } - - connectionStringContext = "Unable to resolve connection string from ConnectionString, ConnectionStrings, or AppSettings."; - return string.Empty; - } - - /// - /// Retrieves the class type of the ADO.NET provider. - /// - /// - /// - /// Gets the Type of the ADO.NET provider to use to connect to the - /// database. This method resolves the type specified in the - /// property. - /// - /// - /// Subclasses can override this method to return a different type - /// if necessary. - /// - /// - /// The of the ADO.NET provider. - protected virtual Type ResolveConnectionType() - { - try - { - return SystemInfo.GetTypeFromString(this.ConnectionType, true, false); - } - catch (Exception ex) - { - this.ErrorHandler.Error("Failed to load connection type [" + this.ConnectionType + "]", ex); - throw; - } + /// + /// Connects to the database. + /// + private void InitializeDatabaseConnection() + { + string connectionStringContext = "Unable to determine connection string context."; + string resolvedConnectionString = string.Empty; + + try + { + this.DiposeConnection(); + + // Set the connection string + resolvedConnectionString = this.ResolveConnectionString(out connectionStringContext); + + this.Connection = this.CreateConnection(this.ResolveConnectionType(), resolvedConnectionString); + + using (this.SecurityContext.Impersonate(this)) + { + // Open the database connection + this.Connection.Open(); + } + } + catch (Exception e) + { + // Sadly, your connection string is bad. + this.ErrorHandler.Error("Could not open database connection [" + resolvedConnectionString + "]. Connection string context [" + connectionStringContext + "].", e); + + this.Connection = null; + } } - /// - /// Connects to the database. - /// - private void InitializeDatabaseConnection() - { - string connectionStringContext = "Unable to determine connection string context."; - string resolvedConnectionString = string.Empty; - - try - { - this.DiposeConnection(); - - // Set the connection string - resolvedConnectionString = this.ResolveConnectionString(out connectionStringContext); - - this.Connection = this.CreateConnection(this.ResolveConnectionType(), resolvedConnectionString); - - using (this.SecurityContext.Impersonate(this)) - { - // Open the database connection - this.Connection.Open(); - } - } - catch (Exception e) - { - // Sadly, your connection string is bad. - this.ErrorHandler.Error("Could not open database connection [" + resolvedConnectionString + "]. Connection string context [" + connectionStringContext + "].", e); - - this.Connection = null; - } - } - - /// - /// Cleanup the existing connection. - /// - /// - /// Calls the IDbConnection's method. - /// - private void DiposeConnection() - { - if (this.Connection != null) - { - try - { - this.Connection.Close(); - } - catch (Exception ex) - { - LogLog.Warn(declaringType, "Exception while disposing cached connection object", ex); - } - - this.Connection = null; - } + /// + /// Cleanup the existing connection. + /// + /// + /// Calls the IDbConnection's method. + /// + private void DiposeConnection() + { + if (this.Connection != null) + { + try + { + this.Connection.Close(); + } + catch (Exception ex) + { + LogLog.Warn(declaringType, "Exception while disposing cached connection object", ex); + } + + this.Connection = null; + } } - /// - /// The list of objects. - /// - /// - /// - /// The list of objects. - /// - /// + /// + /// The list of objects. + /// + /// + /// + /// The list of objects. + /// + /// protected ArrayList m_parameters; - /// - /// The security context to use for privileged calls. - /// - private SecurityContext m_securityContext; - - /// - /// The that will be used - /// to insert logging events into a database. - /// - private IDbConnection m_dbConnection; - - /// - /// Database connection string. - /// - private string m_connectionString; - - /// - /// The appSettings key from App.Config that contains the connection string. - /// - private string m_appSettingsKey; - -#if NET_2_0 - /// - /// The connectionStrings key from App.Config that contains the connection string. - /// - private string m_connectionStringName; -#endif - - /// - /// String type name of the type name. - /// - private string m_connectionType; - - /// - /// The text of the command. - /// - private string m_commandText; - - /// - /// The command type. - /// - private CommandType m_commandType; - - /// - /// Indicates whether to use transactions when writing to the database. - /// - private bool m_useTransactions; - - /// - /// Indicates whether to reconnect when a connection is lost. - /// + /// + /// The security context to use for privileged calls + /// + private SecurityContext m_securityContext; + + /// + /// The that will be used + /// to insert logging events into a database. + /// + private IDbConnection m_dbConnection; + + /// + /// Database connection string. + /// + private string m_connectionString; + + /// + /// The appSettings key from App.Config that contains the connection string. + /// + private string m_appSettingsKey; + + /// + /// The connectionStrings key from App.Config that contains the connection string. + /// + private string m_connectionStringName; + + /// + /// String type name of the type name. + /// + private string m_connectionType; + + /// + /// The text of the command. + /// + private string m_commandText; + + /// + /// The command type. + /// + private CommandType m_commandType; + + /// + /// Indicates whether to use transactions when writing to the database. + /// + private bool m_useTransactions; + + /// + /// Indicates whether to reconnect when a connection is lost. + /// private bool m_reconnectOnError; - /// - /// The fully qualified type of the AdoNetAppender class. - /// - /// - /// Used by the internal logger to record the Type of the - /// log message. - /// + /// + /// The fully qualified type of the AdoNetAppender class. + /// + /// + /// Used by the internal logger to record the Type of the + /// log message. + /// private static readonly Type declaringType = typeof(AdoNetAppender); - } - - /// - /// Parameter type used by the . - /// - /// - /// - /// This class provides the basic database parameter properties - /// as defined by the interface. - /// - /// This type can be subclassed to provide database specific - /// functionality. The two methods that are called externally are - /// and . - /// - /// - public class AdoNetAppenderParameter + } + + /// + /// Parameter type used by the . + /// + /// + /// + /// This class provides the basic database parameter properties + /// as defined by the interface. + /// + /// This type can be subclassed to provide database specific + /// functionality. The two methods that are called externally are + /// and . + /// + /// + public class AdoNetAppenderParameter { - /// - /// Initializes a new instance of the class. - /// - /// - /// Default constructor for the AdoNetAppenderParameter class. - /// - public AdoNetAppenderParameter() - { - this.Precision = 0; - this.Scale = 0; - this.Size = 0; + /// + /// Initializes a new instance of the class. + /// + /// + /// Default constructor for the AdoNetAppenderParameter class. + /// + public AdoNetAppenderParameter() + { + this.Precision = 0; + this.Scale = 0; + this.Size = 0; } - /// - /// Gets or sets the name of this parameter. - /// - /// - /// The name of this parameter. - /// - /// - /// - /// The name of this parameter. The parameter name - /// must match up to a named parameter to the SQL stored procedure - /// or prepared statement. - /// - /// - public string ParameterName - { - get { return this.m_parameterName; } - set { this.m_parameterName = value; } - } - - /// - /// Gets or sets the database type for this parameter. - /// - /// - /// The database type for this parameter. - /// - /// - /// - /// The database type for this parameter. This property should - /// be set to the database type from the - /// enumeration. See . - /// - /// - /// This property is optional. If not specified the ADO.NET provider - /// will attempt to infer the type from the value. - /// - /// - /// - public DbType DbType - { - get { return this.m_dbType; } - - set - { - this.m_dbType = value; - this.m_inferType = false; - } - } - - /// - /// Gets or sets the precision for this parameter. - /// - /// - /// The precision for this parameter. - /// - /// - /// - /// The maximum number of digits used to represent the Value. - /// - /// - /// This property is optional. If not specified the ADO.NET provider - /// will attempt to infer the precision from the value. - /// - /// - /// - public byte Precision - { - get { return this.m_precision; } - set { this.m_precision = value; } - } - - /// - /// Gets or sets the scale for this parameter. - /// - /// - /// The scale for this parameter. - /// - /// - /// - /// The number of decimal places to which Value is resolved. - /// - /// - /// This property is optional. If not specified the ADO.NET provider - /// will attempt to infer the scale from the value. - /// - /// - /// - public byte Scale - { - get { return this.m_scale; } - set { this.m_scale = value; } - } - - /// - /// Gets or sets the size for this parameter. - /// - /// - /// The size for this parameter. - /// - /// - /// - /// The maximum size, in bytes, of the data within the column. - /// - /// - /// This property is optional. If not specified the ADO.NET provider - /// will attempt to infer the size from the value. - /// - /// - /// For BLOB data types like VARCHAR(max) it may be impossible to infer the value automatically, use -1 as the size in this case. - /// - /// - /// - public int Size - { - get { return this.m_size; } - set { this.m_size = value; } - } - - /// - /// Gets or sets the to use to - /// render the logging event into an object for this - /// parameter. - /// - /// - /// The used to render the - /// logging event into an object for this parameter. - /// - /// - /// - /// The that renders the value for this - /// parameter. - /// - /// - /// The can be used to adapt - /// any into a - /// for use in the property. - /// - /// - public IRawLayout Layout - { - get { return this.m_layout; } - set { this.m_layout = value; } + /// + /// Gets or sets the name of this parameter. + /// + /// + /// The name of this parameter. + /// + /// + /// + /// The name of this parameter. The parameter name + /// must match up to a named parameter to the SQL stored procedure + /// or prepared statement. + /// + /// + public string ParameterName + { + get { return this.m_parameterName; } + set { this.m_parameterName = value; } } - /// - /// Prepare the specified database command object. - /// - /// The command to prepare. - /// - /// - /// Prepares the database command object by adding - /// this parameter to its collection of parameters. - /// - /// - public virtual void Prepare(IDbCommand command) - { - // Create a new parameter - IDbDataParameter param = command.CreateParameter(); - - // Set the parameter properties - param.ParameterName = this.ParameterName; - - if (!this.m_inferType) - { - param.DbType = this.DbType; - } - - if (this.Precision != 0) - { - param.Precision = this.Precision; - } - - if (this.Scale != 0) - { - param.Scale = this.Scale; - } - - if (this.Size != 0) - { - param.Size = this.Size; - } - - // Add the parameter to the collection of params - command.Parameters.Add(param); - } - - /// - /// Renders the logging event and set the parameter value in the command. - /// - /// The command containing the parameter. - /// The event to be rendered. - /// - /// - /// Renders the logging event using this parameters layout - /// object. Sets the value of the parameter on the command object. - /// - /// - public virtual void FormatValue(IDbCommand command, LoggingEvent loggingEvent) - { - // Lookup the parameter - IDbDataParameter param = (IDbDataParameter)command.Parameters[this.ParameterName]; - - // Format the value - object formattedValue = this.Layout.Format(loggingEvent); - - // If the value is null then convert to a DBNull - if (formattedValue == null) - { - formattedValue = DBNull.Value; - } - - param.Value = formattedValue; + /// + /// Gets or sets the database type for this parameter. + /// + /// + /// The database type for this parameter. + /// + /// + /// + /// The database type for this parameter. This property should + /// be set to the database type from the + /// enumeration. See . + /// + /// + /// This property is optional. If not specified the ADO.NET provider + /// will attempt to infer the type from the value. + /// + /// + /// + public DbType DbType + { + get { return this.m_dbType; } + set + { + this.m_dbType = value; + this.m_inferType = false; + } } - /// - /// The name of this parameter. - /// - private string m_parameterName; - - /// - /// The database type for this parameter. - /// - private DbType m_dbType; - - /// - /// Flag to infer type rather than use the DbType. - /// - private bool m_inferType = true; - - /// - /// The precision for this parameter. - /// - private byte m_precision; - - /// - /// The scale for this parameter. - /// - private byte m_scale; - - /// - /// The size for this parameter. - /// - private int m_size; - - /// - /// The to use to render the - /// logging event into an object for this parameter. - /// + /// + /// Gets or sets the precision for this parameter. + /// + /// + /// The precision for this parameter. + /// + /// + /// + /// The maximum number of digits used to represent the Value. + /// + /// + /// This property is optional. If not specified the ADO.NET provider + /// will attempt to infer the precision from the value. + /// + /// + /// + public byte Precision + { + get { return this.m_precision; } + set { this.m_precision = value; } + } + + /// + /// Gets or sets the scale for this parameter. + /// + /// + /// The scale for this parameter. + /// + /// + /// + /// The number of decimal places to which Value is resolved. + /// + /// + /// This property is optional. If not specified the ADO.NET provider + /// will attempt to infer the scale from the value. + /// + /// + /// + public byte Scale + { + get { return this.m_scale; } + set { this.m_scale = value; } + } + + /// + /// Gets or sets the size for this parameter. + /// + /// + /// The size for this parameter. + /// + /// + /// + /// The maximum size, in bytes, of the data within the column. + /// + /// + /// This property is optional. If not specified the ADO.NET provider + /// will attempt to infer the size from the value. + /// + /// + /// For BLOB data types like VARCHAR(max) it may be impossible to infer the value automatically, use -1 as the size in this case. + /// + /// + /// + public int Size + { + get { return this.m_size; } + set { this.m_size = value; } + } + + /// + /// Gets or sets the to use to + /// render the logging event into an object for this + /// parameter. + /// + /// + /// The used to render the + /// logging event into an object for this parameter. + /// + /// + /// + /// The that renders the value for this + /// parameter. + /// + /// + /// The can be used to adapt + /// any into a + /// for use in the property. + /// + /// + public IRawLayout Layout + { + get { return this.m_layout; } + set { this.m_layout = value; } + } + + /// + /// Prepare the specified database command object. + /// + /// The command to prepare. + /// + /// + /// Prepares the database command object by adding + /// this parameter to its collection of parameters. + /// + /// + public virtual void Prepare(IDbCommand command) + { + // Create a new parameter + IDbDataParameter param = command.CreateParameter(); + + // Set the parameter properties + param.ParameterName = this.ParameterName; + + if (!this.m_inferType) + { + param.DbType = this.DbType; + } + if (this.Precision != 0) + { + param.Precision = this.Precision; + } + if (this.Scale != 0) + { + param.Scale = this.Scale; + } + if (this.Size != 0) + { + param.Size = this.Size; + } + + // Add the parameter to the collection of params + command.Parameters.Add(param); + } + + /// + /// Renders the logging event and set the parameter value in the command. + /// + /// The command containing the parameter. + /// The event to be rendered. + /// + /// + /// Renders the logging event using this parameters layout + /// object. Sets the value of the parameter on the command object. + /// + /// + public virtual void FormatValue(IDbCommand command, LoggingEvent loggingEvent) + { + // Lookup the parameter + IDbDataParameter param = (IDbDataParameter)command.Parameters[this.ParameterName]; + + // Format the value + object formattedValue = this.Layout.Format(loggingEvent); + + // If the value is null then convert to a DBNull + if (formattedValue == null) + { + formattedValue = DBNull.Value; + } + + param.Value = formattedValue; + } + + /// + /// The name of this parameter. + /// + private string m_parameterName; + + /// + /// The database type for this parameter. + /// + private DbType m_dbType; + + /// + /// Flag to infer type rather than use the DbType + /// + private bool m_inferType = true; + + /// + /// The precision for this parameter. + /// + private byte m_precision; + + /// + /// The scale for this parameter. + /// + private byte m_scale; + + /// + /// The size for this parameter. + /// + private int m_size; + + /// + /// The to use to render the + /// logging event into an object for this parameter. + /// private IRawLayout m_layout; - } -} - -#endif // !SSCLI + } +} + +#endif // !SSCLI diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/AnsiColorTerminalAppender.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/AnsiColorTerminalAppender.cs index f54b7c1b57a..c0b13597882 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/AnsiColorTerminalAppender.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/AnsiColorTerminalAppender.cs @@ -1,555 +1,547 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.Appender -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; - using System.Globalization; - using System.Text; - - using log4net.Core; - using log4net.Layout; - using log4net.Util; - - /// - /// Appends logging events to the terminal using ANSI color escape sequences. - /// - /// - /// - /// AnsiColorTerminalAppender appends log events to the standard output stream - /// or the error output stream using a layout specified by the - /// user. It also allows the color of a specific level of message to be set. - /// - /// - /// This appender expects the terminal to understand the VT100 control set - /// in order to interpret the color codes. If the terminal or console does not - /// understand the control codes the behavior is not defined. - /// - /// - /// By default, all output is written to the console's standard output stream. - /// The property can be set to direct the output to the - /// error stream. - /// - /// - /// NOTE: This appender writes each message to the System.Console.Out or - /// System.Console.Error that is set at the time the event is appended. - /// Therefore it is possible to programmatically redirect the output of this appender - /// (for example NUnit does this to capture program output). While this is the desired - /// behavior of this appender it may have security implications in your application. - /// - /// - /// When configuring the ANSI colored terminal appender, a mapping should be - /// specified to map a logging level to a color. For example: - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// The Level is the standard log4net logging level and ForeColor and BackColor can be any - /// of the following values: - /// - /// Blue - /// Green - /// Red - /// White - /// Yellow - /// Purple - /// Cyan - /// - /// These color values cannot be combined together to make new colors. - /// - /// - /// The attributes can be any combination of the following: - /// - /// Brightforeground is brighter - /// Dimforeground is dimmer - /// Underscoremessage is underlined - /// Blinkforeground is blinking (does not work on all terminals) - /// Reverseforeground and background are reversed - /// Hiddenoutput is hidden - /// Strikethroughmessage has a line through it - /// - /// While any of these attributes may be combined together not all combinations - /// work well together, for example setting both Bright and Dim attributes makes - /// no sense. - /// - /// - /// Patrick Wagstrom. - /// Nicko Cadell. - public class AnsiColorTerminalAppender : AppenderSkeleton +using System; +using System.Text; +using System.Globalization; + +using log4net.Core; +using log4net.Layout; +using log4net.Util; + +namespace log4net.Appender +{ + /// + /// Appends logging events to the terminal using ANSI color escape sequences. + /// + /// + /// + /// AnsiColorTerminalAppender appends log events to the standard output stream + /// or the error output stream using a layout specified by the + /// user. It also allows the color of a specific level of message to be set. + /// + /// + /// This appender expects the terminal to understand the VT100 control set + /// in order to interpret the color codes. If the terminal or console does not + /// understand the control codes the behavior is not defined. + /// + /// + /// By default, all output is written to the console's standard output stream. + /// The property can be set to direct the output to the + /// error stream. + /// + /// + /// NOTE: This appender writes each message to the System.Console.Out or + /// System.Console.Error that is set at the time the event is appended. + /// Therefore it is possible to programmatically redirect the output of this appender + /// (for example NUnit does this to capture program output). While this is the desired + /// behavior of this appender it may have security implications in your application. + /// + /// + /// When configuring the ANSI colored terminal appender, a mapping should be + /// specified to map a logging level to a color. For example: + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// The Level is the standard log4net logging level and ForeColor and BackColor can be any + /// of the following values: + /// + /// Blue + /// Green + /// Red + /// White + /// Yellow + /// Purple + /// Cyan + /// + /// These color values cannot be combined together to make new colors. + /// + /// + /// The attributes can be any combination of the following: + /// + /// Brightforeground is brighter + /// Dimforeground is dimmer + /// Underscoremessage is underlined + /// Blinkforeground is blinking (does not work on all terminals) + /// Reverseforeground and background are reversed + /// Hiddenoutput is hidden + /// Strikethroughmessage has a line through it + /// + /// While any of these attributes may be combined together not all combinations + /// work well together, for example setting both Bright and Dim attributes makes + /// no sense. + /// + /// + /// Patrick Wagstrom + /// Nicko Cadell + public class AnsiColorTerminalAppender : AppenderSkeleton { - /// - /// The enum of possible display attributes. - /// - /// - /// - /// The following flags can be combined together to - /// form the ANSI color attributes. - /// - /// - /// - [Flags] - public enum AnsiAttributes : int - { - /// - /// text is bright - /// - Bright = 1, - - /// - /// text is dim - /// - Dim = 2, - - /// - /// text is underlined - /// - Underscore = 4, - - /// - /// text is blinking - /// - /// - /// Not all terminals support this attribute - /// - Blink = 8, - - /// - /// text and background colors are reversed - /// - Reverse = 16, - - /// - /// text is hidden - /// - Hidden = 32, - - /// - /// text is displayed with a strikethrough - /// - Strikethrough = 64, - - /// - /// text color is light - /// - Light = 128, - } - - /// - /// The enum of possible foreground or background color values for - /// use with the color mapping method. - /// - /// - /// - /// The output can be in one for the following ANSI colors. - /// - /// - /// - public enum AnsiColor : int - { - /// - /// color is black - /// - Black = 0, - - /// - /// color is red - /// - Red = 1, - - /// - /// color is green - /// - Green = 2, - - /// - /// color is yellow - /// - Yellow = 3, - - /// - /// color is blue - /// - Blue = 4, - - /// - /// color is magenta - /// - Magenta = 5, - - /// - /// color is cyan - /// - Cyan = 6, - - /// - /// color is white - /// - White = 7, + /// + /// The enum of possible display attributes + /// + /// + /// + /// The following flags can be combined together to + /// form the ANSI color attributes. + /// + /// + /// + [Flags] + public enum AnsiAttributes : int + { + /// + /// text is bright + /// + Bright = 1, + /// + /// text is dim + /// + Dim = 2, + + /// + /// text is underlined + /// + Underscore = 4, + + /// + /// text is blinking + /// + /// + /// Not all terminals support this attribute + /// + Blink = 8, + + /// + /// text and background colors are reversed + /// + Reverse = 16, + + /// + /// text is hidden + /// + Hidden = 32, + + /// + /// text is displayed with a strikethrough + /// + Strikethrough = 64, + + /// + /// text color is light + /// + Light = 128 + } + + /// + /// The enum of possible foreground or background color values for + /// use with the color mapping method + /// + /// + /// + /// The output can be in one for the following ANSI colors. + /// + /// + /// + public enum AnsiColor : int + { + /// + /// color is black + /// + Black = 0, + + /// + /// color is red + /// + Red = 1, + + /// + /// color is green + /// + Green = 2, + + /// + /// color is yellow + /// + Yellow = 3, + + /// + /// color is blue + /// + Blue = 4, + + /// + /// color is magenta + /// + Magenta = 5, + + /// + /// color is cyan + /// + Cyan = 6, + + /// + /// color is white + /// + White = 7 + } + + /// + /// Initializes a new instance of the class. + /// + /// + /// The instance of the class is set up to write + /// to the standard output stream. + /// + public AnsiColorTerminalAppender() + { + } + + /// + /// Target is the value of the console output stream. + /// + /// + /// Target is the value of the console output stream. + /// This is either "Console.Out" or "Console.Error". + /// + /// + /// + /// Target is the value of the console output stream. + /// This is either "Console.Out" or "Console.Error". + /// + /// + public virtual string Target + { + get { return this.m_writeToErrorStream ? ConsoleError : ConsoleOut; } + set + { + string trimmedTargetName = value.Trim(); + + if (SystemInfo.EqualsIgnoringCase(ConsoleError, trimmedTargetName)) + { + this.m_writeToErrorStream = true; + } + else + { + this.m_writeToErrorStream = false; + } + } + } + + /// + /// Add a mapping of level to color + /// + /// The mapping to add + /// + /// + /// Add a mapping to this appender. + /// Each mapping defines the foreground and background colours + /// for a level. + /// + /// + public void AddMapping(LevelColors mapping) + { + this.m_levelMapping.Add(mapping); } - /// - /// Initializes a new instance of the class. - /// - /// - /// The instance of the class is set up to write - /// to the standard output stream. - /// - public AnsiColorTerminalAppender() - { + /// + /// This method is called by the method. + /// + /// The event to log. + /// + /// + /// Writes the event to the console. + /// + /// + /// The format of the output will depend on the appender's layout. + /// + /// + protected override void Append(LoggingEvent loggingEvent) + { + string loggingMessage = this.RenderLoggingEvent(loggingEvent); + + // see if there is a specified lookup. + LevelColors levelColors = this.m_levelMapping.Lookup(loggingEvent.Level) as LevelColors; + if (levelColors != null) + { + // Prepend the Ansi Color code + loggingMessage = levelColors.CombinedColor + loggingMessage; + } + + // on most terminals there are weird effects if we don't clear the background color + // before the new line. This checks to see if it ends with a newline, and if + // so, inserts the clear codes before the newline, otherwise the clear codes + // are inserted afterwards. + if (loggingMessage.Length > 1) + { + if (loggingMessage.EndsWith("\r\n") || loggingMessage.EndsWith("\n\r")) + { + loggingMessage = loggingMessage.Insert(loggingMessage.Length - 2, PostEventCodes); + } + else if (loggingMessage.EndsWith("\n") || loggingMessage.EndsWith("\r")) + { + loggingMessage = loggingMessage.Insert(loggingMessage.Length - 1, PostEventCodes); + } + else + { + loggingMessage = loggingMessage + PostEventCodes; + } + } + else + { + if (loggingMessage[0] == '\n' || loggingMessage[0] == '\r') + { + loggingMessage = PostEventCodes + loggingMessage; + } + else + { + loggingMessage = loggingMessage + PostEventCodes; + } + } + +#if NETCF_1_0 + // Write to the output stream + Console.Write(loggingMessage); +#else + if (this.m_writeToErrorStream) + { + // Write to the error stream + Console.Error.Write(loggingMessage); + } + else + { + // Write to the output stream + Console.Write(loggingMessage); + } +#endif + } - /// - /// Gets or sets target is the value of the console output stream. - /// - /// - /// Target is the value of the console output stream. - /// This is either "Console.Out" or "Console.Error". - /// - /// - /// - /// Target is the value of the console output stream. - /// This is either "Console.Out" or "Console.Error". - /// - /// - public virtual string Target - { - get { return this.m_writeToErrorStream ? ConsoleError : ConsoleOut; } - - set - { - string trimmedTargetName = value.Trim(); - - if (SystemInfo.EqualsIgnoringCase(ConsoleError, trimmedTargetName)) - { - this.m_writeToErrorStream = true; - } - else - { - this.m_writeToErrorStream = false; - } - } - } - - /// - /// Add a mapping of level to color. - /// - /// The mapping to add. - /// - /// - /// Add a mapping to this appender. - /// Each mapping defines the foreground and background colours - /// for a level. - /// - /// - public void AddMapping(LevelColors mapping) - { - this.m_levelMapping.Add(mapping); + /// + /// This appender requires a to be set. + /// + /// true + /// + /// + /// This appender requires a to be set. + /// + /// + protected override bool RequiresLayout + { + get { return true; } } - /// - /// This method is called by the method. - /// - /// The event to log. - /// - /// - /// Writes the event to the console. - /// - /// - /// The format of the output will depend on the appender's layout. - /// - /// - protected override void Append(log4net.Core.LoggingEvent loggingEvent) - { - string loggingMessage = this.RenderLoggingEvent(loggingEvent); - - // see if there is a specified lookup. - LevelColors levelColors = this.m_levelMapping.Lookup(loggingEvent.Level) as LevelColors; - if (levelColors != null) - { - // Prepend the Ansi Color code - loggingMessage = levelColors.CombinedColor + loggingMessage; - } - - // on most terminals there are weird effects if we don't clear the background color - // before the new line. This checks to see if it ends with a newline, and if - // so, inserts the clear codes before the newline, otherwise the clear codes - // are inserted afterwards. - if (loggingMessage.Length > 1) - { - if (loggingMessage.EndsWith("\r\n") || loggingMessage.EndsWith("\n\r")) - { - loggingMessage = loggingMessage.Insert(loggingMessage.Length - 2, PostEventCodes); - } - else if (loggingMessage.EndsWith("\n") || loggingMessage.EndsWith("\r")) - { - loggingMessage = loggingMessage.Insert(loggingMessage.Length - 1, PostEventCodes); - } - else - { - loggingMessage = loggingMessage + PostEventCodes; - } - } - else - { - if (loggingMessage[0] == '\n' || loggingMessage[0] == '\r') - { - loggingMessage = PostEventCodes + loggingMessage; - } - else - { - loggingMessage = loggingMessage + PostEventCodes; - } - } - -#if NETCF_1_0 - // Write to the output stream - Console.Write(loggingMessage); -#else - if (this.m_writeToErrorStream) - { - // Write to the error stream - Console.Error.Write(loggingMessage); - } - else - { - // Write to the output stream - Console.Write(loggingMessage); - } -#endif - - } - - /// - /// Gets a value indicating whether this appender requires a to be set. - /// - /// true. - /// - /// - /// This appender requires a to be set. - /// - /// - protected override bool RequiresLayout - { - get { return true; } - } - - /// - /// Initialize the options for this appender. - /// - /// - /// - /// Initialize the level to color mappings set on this appender. - /// - /// - public override void ActivateOptions() - { - base.ActivateOptions(); - this.m_levelMapping.ActivateOptions(); + /// + /// Initialize the options for this appender + /// + /// + /// + /// Initialize the level to color mappings set on this appender. + /// + /// + public override void ActivateOptions() + { + base.ActivateOptions(); + this.m_levelMapping.ActivateOptions(); } - /// - /// The to use when writing to the Console - /// standard output stream. - /// - /// - /// - /// The to use when writing to the Console - /// standard output stream. - /// - /// - public const string ConsoleOut = "Console.Out"; - - /// - /// The to use when writing to the Console - /// standard error output stream. - /// - /// - /// - /// The to use when writing to the Console - /// standard error output stream. - /// - /// + /// + /// The to use when writing to the Console + /// standard output stream. + /// + /// + /// + /// The to use when writing to the Console + /// standard output stream. + /// + /// + public const string ConsoleOut = "Console.Out"; + + /// + /// The to use when writing to the Console + /// standard error output stream. + /// + /// + /// + /// The to use when writing to the Console + /// standard error output stream. + /// + /// public const string ConsoleError = "Console.Error"; - /// - /// Flag to write output to the error stream rather than the standard output stream. - /// - private bool m_writeToErrorStream = false; - - /// - /// Mapping from level object to color value. - /// - private LevelMapping m_levelMapping = new LevelMapping(); - - /// - /// Ansi code to reset terminal. - /// + /// + /// Flag to write output to the error stream rather than the standard output stream + /// + private bool m_writeToErrorStream = false; + + /// + /// Mapping from level object to color value + /// + private LevelMapping m_levelMapping = new LevelMapping(); + + /// + /// Ansi code to reset terminal + /// private const string PostEventCodes = "\x1b[0m"; - /// - /// A class to act as a mapping between the level that a logging call is made at and - /// the color it should be displayed as. - /// - /// - /// - /// Defines the mapping between a level and the color it should be displayed in. - /// - /// - public class LevelColors : LevelMappingEntry - { - private AnsiColor m_foreColor; - private AnsiColor m_backColor; - private AnsiAttributes m_attributes; - private string m_combinedColor = string.Empty; - - /// - /// Gets or sets the mapped foreground color for the specified level. - /// - /// - /// - /// Required property. - /// The mapped foreground color for the specified level. - /// - /// - public AnsiColor ForeColor - { - get { return this.m_foreColor; } - set { this.m_foreColor = value; } - } - - /// - /// Gets or sets the mapped background color for the specified level. - /// - /// - /// - /// Required property. - /// The mapped background color for the specified level. - /// - /// - public AnsiColor BackColor - { - get { return this.m_backColor; } - set { this.m_backColor = value; } - } - - /// - /// Gets or sets the color attributes for the specified level. - /// - /// - /// - /// Required property. - /// The color attributes for the specified level. - /// - /// - public AnsiAttributes Attributes - { - get { return this.m_attributes; } - set { this.m_attributes = value; } - } - - /// - /// Initialize the options for the object. - /// - /// - /// - /// Combine the and together - /// and append the attributes. - /// - /// - public override void ActivateOptions() - { - base.ActivateOptions(); - - StringBuilder buf = new StringBuilder(); - - // Reset any existing codes - buf.Append("\x1b[0;"); - - int lightAdjustment = ((this.m_attributes & AnsiAttributes.Light) > 0) ? 60 : 0; - - // set the foreground color - buf.Append(30 + lightAdjustment + (int)this.m_foreColor); - buf.Append(';'); - - // set the background color - buf.Append(40 + lightAdjustment + (int)this.m_backColor); - - // set the attributes - if ((this.m_attributes & AnsiAttributes.Bright) > 0) - { - buf.Append(";1"); - } - - if ((this.m_attributes & AnsiAttributes.Dim) > 0) - { - buf.Append(";2"); - } - - if ((this.m_attributes & AnsiAttributes.Underscore) > 0) - { - buf.Append(";4"); - } - - if ((this.m_attributes & AnsiAttributes.Blink) > 0) - { - buf.Append(";5"); - } - - if ((this.m_attributes & AnsiAttributes.Reverse) > 0) - { - buf.Append(";7"); - } - - if ((this.m_attributes & AnsiAttributes.Hidden) > 0) - { - buf.Append(";8"); - } - - if ((this.m_attributes & AnsiAttributes.Strikethrough) > 0) - { - buf.Append(";9"); - } - - buf.Append('m'); - - this.m_combinedColor = buf.ToString(); - } - - /// - /// Gets the combined , and - /// suitable for setting the ansi terminal color. - /// - internal string CombinedColor - { - get { return this.m_combinedColor; } - } + /// + /// A class to act as a mapping between the level that a logging call is made at and + /// the color it should be displayed as. + /// + /// + /// + /// Defines the mapping between a level and the color it should be displayed in. + /// + /// + public class LevelColors : LevelMappingEntry + { + private AnsiColor m_foreColor; + private AnsiColor m_backColor; + private AnsiAttributes m_attributes; + private string m_combinedColor = string.Empty; + + /// + /// The mapped foreground color for the specified level + /// + /// + /// + /// Required property. + /// The mapped foreground color for the specified level + /// + /// + public AnsiColor ForeColor + { + get { return this.m_foreColor; } + set { this.m_foreColor = value; } + } + + /// + /// The mapped background color for the specified level + /// + /// + /// + /// Required property. + /// The mapped background color for the specified level + /// + /// + public AnsiColor BackColor + { + get { return this.m_backColor; } + set { this.m_backColor = value; } + } + + /// + /// The color attributes for the specified level + /// + /// + /// + /// Required property. + /// The color attributes for the specified level + /// + /// + public AnsiAttributes Attributes + { + get { return this.m_attributes; } + set { this.m_attributes = value; } + } + + /// + /// Initialize the options for the object + /// + /// + /// + /// Combine the and together + /// and append the attributes. + /// + /// + public override void ActivateOptions() + { + base.ActivateOptions(); + + StringBuilder buf = new StringBuilder(); + + // Reset any existing codes + buf.Append("\x1b[0;"); + + int lightAdjustment = ((this.m_attributes & AnsiAttributes.Light) > 0) ? 60 : 0; + + // set the foreground color + buf.Append(30 + lightAdjustment + (int)this.m_foreColor); + buf.Append(';'); + + // set the background color + buf.Append(40 + lightAdjustment + (int)this.m_backColor); + + // set the attributes + if ((this.m_attributes & AnsiAttributes.Bright) > 0) + { + buf.Append(";1"); + } + if ((this.m_attributes & AnsiAttributes.Dim) > 0) + { + buf.Append(";2"); + } + if ((this.m_attributes & AnsiAttributes.Underscore) > 0) + { + buf.Append(";4"); + } + if ((this.m_attributes & AnsiAttributes.Blink) > 0) + { + buf.Append(";5"); + } + if ((this.m_attributes & AnsiAttributes.Reverse) > 0) + { + buf.Append(";7"); + } + if ((this.m_attributes & AnsiAttributes.Hidden) > 0) + { + buf.Append(";8"); + } + if ((this.m_attributes & AnsiAttributes.Strikethrough) > 0) + { + buf.Append(";9"); + } + + buf.Append('m'); + + this.m_combinedColor = buf.ToString(); + } + + /// + /// The combined , and + /// suitable for setting the ansi terminal color. + /// + internal string CombinedColor + { + get { return this.m_combinedColor; } + } } - } -} + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/AppenderCollection.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/AppenderCollection.cs index 030f4b925c3..99682bb268c 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/AppenderCollection.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/AppenderCollection.cs @@ -1,823 +1,812 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information - -namespace log4net.Appender -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; - using System.Collections; - - /// - /// A strongly-typed collection of objects. - /// - /// Nicko Cadell. - public class AppenderCollection : ICollection, IList, IEnumerable -#if !NETSTANDARD1_3 - , ICloneable -#endif +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +using System; +using System.Collections; + +namespace log4net.Appender +{ + /// + /// A strongly-typed collection of objects. + /// + /// Nicko Cadell + public class AppenderCollection : ICollection, IList, IEnumerable +#if !NETSTANDARD1_3 + , ICloneable +#endif { - /// - /// Supports type-safe iteration over a . - /// - /// - public interface IAppenderCollectionEnumerator - { - /// - /// Gets the current element in the collection. - /// - IAppender Current { get; } - - /// - /// Advances the enumerator to the next element in the collection. - /// - /// - /// true if the enumerator was successfully advanced to the next element; - /// false if the enumerator has passed the end of the collection. - /// - /// - /// The collection was modified after the enumerator was created. - /// - bool MoveNext(); - - /// - /// Sets the enumerator to its initial position, before the first element in the collection. - /// - void Reset(); + /// + /// Supports type-safe iteration over a . + /// + /// + public interface IAppenderCollectionEnumerator + { + /// + /// Gets the current element in the collection. + /// + IAppender Current { get; } + + /// + /// Advances the enumerator to the next element in the collection. + /// + /// + /// true if the enumerator was successfully advanced to the next element; + /// false if the enumerator has passed the end of the collection. + /// + /// + /// The collection was modified after the enumerator was created. + /// + bool MoveNext(); + + /// + /// Sets the enumerator to its initial position, before the first element in the collection. + /// + void Reset(); } private const int DEFAULT_CAPACITY = 16; - private IAppender[] m_array; - private int m_count = 0; + + private IAppender[] m_array; + private int m_count = 0; private int m_version = 0; - /// - /// Creates a read-only wrapper for a AppenderCollection instance. - /// - /// list to create a readonly wrapper arround. - /// - /// An AppenderCollection wrapper that is read-only. - /// - public static AppenderCollection ReadOnly(AppenderCollection list) - { - if (list == null) + /// + /// Creates a read-only wrapper for a AppenderCollection instance. + /// + /// list to create a readonly wrapper arround + /// + /// An AppenderCollection wrapper that is read-only. + /// + public static AppenderCollection ReadOnly(AppenderCollection list) + { + if(list == null) { throw new ArgumentNullException("list"); } - return new ReadOnlyAppenderCollection(list); + return new ReadOnlyAppenderCollection(list); } - /// - /// An empty readonly static AppenderCollection. - /// + /// + /// An empty readonly static AppenderCollection + /// public static readonly AppenderCollection EmptyCollection = ReadOnly(new AppenderCollection(0)); /// - /// Initializes a new instance of the class. - /// Initializes a new instance of the AppenderCollection class - /// that is empty and has the default initial capacity. - /// - public AppenderCollection() - { - this.m_array = new IAppender[DEFAULT_CAPACITY]; - } - - /// - /// Initializes a new instance of the class. - /// Initializes a new instance of the AppenderCollection class - /// that has the specified initial capacity. - /// - /// - /// The number of elements that the new AppenderCollection is initially capable of storing. - /// - public AppenderCollection(int capacity) - { - this.m_array = new IAppender[capacity]; - } - - /// - /// Initializes a new instance of the class. - /// Initializes a new instance of the AppenderCollection class - /// that contains elements copied from the specified AppenderCollection. - /// - /// The AppenderCollection whose elements are copied to the new collection. - public AppenderCollection(AppenderCollection c) - { - this.m_array = new IAppender[c.Count]; - this.AddRange(c); - } - - /// - /// Initializes a new instance of the class. - /// Initializes a new instance of the AppenderCollection class - /// that contains elements copied from the specified array. - /// - /// The array whose elements are copied to the new list. - public AppenderCollection(IAppender[] a) - { - this.m_array = new IAppender[a.Length]; - this.AddRange(a); - } - - /// - /// Initializes a new instance of the class. - /// Initializes a new instance of the AppenderCollection class - /// that contains elements copied from the specified collection. - /// - /// The collection whose elements are copied to the new list. - public AppenderCollection(ICollection col) - { - this.m_array = new IAppender[col.Count]; - this.AddRange(col); - } - - /// - /// Type visible only to our subclasses - /// Used to access protected constructor. - /// - /// - internal protected enum Tag - { - /// - /// A value - /// - Default, - } - - /// - /// Initializes a new instance of the class. - /// Allow subclasses to avoid our default constructors. - /// - /// - /// - internal protected AppenderCollection(Tag tag) - { - this.m_array = null; - } - - /// - /// Gets the number of elements actually contained in the AppenderCollection. - /// - public virtual int Count - { - get { return this.m_count; } - } - - /// - /// Copies the entire AppenderCollection to a one-dimensional - /// array. - /// - /// The one-dimensional array to copy to. - public virtual void CopyTo(IAppender[] array) - { - this.CopyTo(array, 0); - } - - /// - /// Copies the entire AppenderCollection to a one-dimensional - /// array, starting at the specified index of the target array. - /// - /// The one-dimensional array to copy to. - /// The zero-based index in at which copying begins. - public virtual void CopyTo(IAppender[] array, int start) - { - if (this.m_count > array.GetUpperBound(0) + 1 - start) - { - throw new System.ArgumentException("Destination array was not long enough."); - } - - Array.Copy(this.m_array, 0, array, start, this.m_count); - } - - /// - /// Gets a value indicating whether access to the collection is synchronized (thread-safe). - /// - /// false, because the backing type is an array, which is never thread-safe. - public virtual bool IsSynchronized - { - get { return false; } - } - - /// - /// Gets an object that can be used to synchronize access to the collection. - /// - public virtual object SyncRoot - { - get { return this.m_array; } - } - - /// - /// Gets or sets the at the specified index. - /// - /// The zero-based index of the element to get or set. - /// - /// is less than zero. - /// -or- - /// is equal to or greater than . - /// - public virtual IAppender this[int index] - { - get - { - this.ValidateIndex(index); // throws - return this.m_array[index]; - } - - set - { - this.ValidateIndex(index); // throws - ++this.m_version; - this.m_array[index] = value; - } - } - - /// - /// Adds a to the end of the AppenderCollection. - /// - /// The to be added to the end of the AppenderCollection. - /// The index at which the value has been added. - public virtual int Add(IAppender item) - { - if (this.m_count == this.m_array.Length) - { - this.EnsureCapacity(this.m_count + 1); - } - - this.m_array[this.m_count] = item; - this.m_version++; - - return this.m_count++; - } - - /// - /// Removes all elements from the AppenderCollection. - /// - public virtual void Clear() - { - ++this.m_version; - this.m_array = new IAppender[DEFAULT_CAPACITY]; - this.m_count = 0; - } - - /// - /// Creates a shallow copy of the . - /// - /// A new with a shallow copy of the collection data. - public virtual object Clone() - { - AppenderCollection newCol = new AppenderCollection(this.m_count); - Array.Copy(this.m_array, 0, newCol.m_array, 0, this.m_count); - newCol.m_count = this.m_count; - newCol.m_version = this.m_version; - - return newCol; - } - - /// - /// Determines whether a given is in the AppenderCollection. - /// - /// The to check for. - /// true if is found in the AppenderCollection; otherwise, false. - public virtual bool Contains(IAppender item) - { - for (int i = 0; i != this.m_count; ++i) - { - if (this.m_array[i].Equals(item)) - { - return true; - } - } - - return false; - } - - /// - /// Returns the zero-based index of the first occurrence of a - /// in the AppenderCollection. - /// - /// The to locate in the AppenderCollection. - /// - /// The zero-based index of the first occurrence of - /// in the entire AppenderCollection, if found; otherwise, -1. - /// - public virtual int IndexOf(IAppender item) - { - for (int i = 0; i != this.m_count; ++i) - { - if (this.m_array[i].Equals(item)) - { - return i; - } - } - - return -1; - } - - /// - /// Inserts an element into the AppenderCollection at the specified index. - /// - /// The zero-based index at which should be inserted. - /// The to insert. - /// - /// is less than zero. - /// -or- - /// is equal to or greater than . - /// - public virtual void Insert(int index, IAppender item) - { - this.ValidateIndex(index, true); // throws - - if (this.m_count == this.m_array.Length) - { - this.EnsureCapacity(this.m_count + 1); - } - - if (index < this.m_count) - { - Array.Copy(this.m_array, index, this.m_array, index + 1, this.m_count - index); - } - - this.m_array[index] = item; - this.m_count++; - this.m_version++; - } - - /// - /// Removes the first occurrence of a specific from the AppenderCollection. - /// - /// The to remove from the AppenderCollection. - /// - /// The specified was not found in the AppenderCollection. - /// - public virtual void Remove(IAppender item) - { - int i = this.IndexOf(item); - if (i < 0) - { - throw new System.ArgumentException("Cannot remove the specified item because it was not found in the specified Collection."); - } - - ++this.m_version; - this.RemoveAt(i); - } - - /// - /// Removes the element at the specified index of the AppenderCollection. - /// - /// The zero-based index of the element to remove. - /// - /// is less than zero. - /// -or- - /// is equal to or greater than . - /// - public virtual void RemoveAt(int index) - { - this.ValidateIndex(index); // throws - - this.m_count--; - - if (index < this.m_count) - { - Array.Copy(this.m_array, index + 1, this.m_array, index, this.m_count - index); - } - - // We can't set the deleted entry equal to null, because it might be a value type. - // Instead, we'll create an empty single-element array of the right type and copy it - // over the entry we want to erase. - IAppender[] temp = new IAppender[1]; - Array.Copy(temp, 0, this.m_array, this.m_count, 1); - this.m_version++; - } - - /// - /// Gets a value indicating whether the collection has a fixed size. - /// - /// true if the collection has a fixed size; otherwise, false. The default is false. - public virtual bool IsFixedSize - { - get { return false; } - } - - /// - /// Gets a value indicating whether the IList is read-only. - /// - /// true if the collection is read-only; otherwise, false. The default is false. - public virtual bool IsReadOnly - { - get { return false; } - } - - /// - /// Returns an enumerator that can iterate through the AppenderCollection. - /// - /// An for the entire AppenderCollection. - public virtual IAppenderCollectionEnumerator GetEnumerator() - { - return new Enumerator(this); - } - - /// - /// Gets or sets the number of elements the AppenderCollection can contain. - /// - public virtual int Capacity - { - get - { - return this.m_array.Length; - } - - set - { - if (value < this.m_count) - { - value = this.m_count; - } - - if (value != this.m_array.Length) - { - if (value > 0) - { - IAppender[] temp = new IAppender[value]; - Array.Copy(this.m_array, 0, temp, 0, this.m_count); - this.m_array = temp; - } - else - { - this.m_array = new IAppender[DEFAULT_CAPACITY]; - } - } - } - } - - /// - /// Adds the elements of another AppenderCollection to the current AppenderCollection. - /// - /// The AppenderCollection whose elements should be added to the end of the current AppenderCollection. - /// The new of the AppenderCollection. - public virtual int AddRange(AppenderCollection x) - { - if (this.m_count + x.Count >= this.m_array.Length) - { - this.EnsureCapacity(this.m_count + x.Count); - } - - Array.Copy(x.m_array, 0, this.m_array, this.m_count, x.Count); - this.m_count += x.Count; - this.m_version++; - - return this.m_count; - } - - /// - /// Adds the elements of a array to the current AppenderCollection. - /// - /// The array whose elements should be added to the end of the AppenderCollection. - /// The new of the AppenderCollection. - public virtual int AddRange(IAppender[] x) - { - if (this.m_count + x.Length >= this.m_array.Length) - { - this.EnsureCapacity(this.m_count + x.Length); - } - - Array.Copy(x, 0, this.m_array, this.m_count, x.Length); - this.m_count += x.Length; - this.m_version++; - - return this.m_count; - } - - /// - /// Adds the elements of a collection to the current AppenderCollection. - /// - /// The collection whose elements should be added to the end of the AppenderCollection. - /// The new of the AppenderCollection. - public virtual int AddRange(ICollection col) - { - if (this.m_count + col.Count >= this.m_array.Length) - { - this.EnsureCapacity(this.m_count + col.Count); - } - - foreach (object item in col) - { - this.Add((IAppender)item); - } - - return this.m_count; - } - - /// - /// Sets the capacity to the actual number of elements. - /// - public virtual void TrimToSize() - { - this.Capacity = this.m_count; - } - - /// - /// Return the collection elements as an array. - /// - /// the array. - public virtual IAppender[] ToArray() - { - IAppender[] resultArray = new IAppender[this.m_count]; - if (this.m_count > 0) - { - Array.Copy(this.m_array, 0, resultArray, 0, this.m_count); - } - - return resultArray; - } - - /// - /// is less than zero. - /// -or- - /// is equal to or greater than . - /// - private void ValidateIndex(int i) - { - this.ValidateIndex(i, false); - } - - /// - /// is less than zero. - /// -or- - /// is equal to or greater than . - /// - private void ValidateIndex(int i, bool allowEqualEnd) - { - int max = allowEqualEnd ? this.m_count : (this.m_count - 1); - if (i < 0 || i > max) - { - throw log4net.Util.SystemInfo.CreateArgumentOutOfRangeException("i", (object)i, "Index was out of range. Must be non-negative and less than the size of the collection. [" + (object)i + "] Specified argument was out of the range of valid values."); - } - } - - private void EnsureCapacity(int min) - { - int newCapacity = (this.m_array.Length == 0) ? DEFAULT_CAPACITY : this.m_array.Length * 2; - if (newCapacity < min) - { - newCapacity = min; - } - - this.Capacity = newCapacity; - } - - void ICollection.CopyTo(Array array, int start) - { - if (this.m_count > 0) - { - Array.Copy(this.m_array, 0, array, start, this.m_count); - } - } - - object IList.this[int i] - { - get { return (object)this[i]; } - set { this[i] = (IAppender)value; } - } - - int IList.Add(object x) - { - return this.Add((IAppender)x); - } - - bool IList.Contains(object x) - { - return this.Contains((IAppender)x); - } - - int IList.IndexOf(object x) - { - return this.IndexOf((IAppender)x); - } - - void IList.Insert(int pos, object x) - { - this.Insert(pos, (IAppender)x); - } - - void IList.Remove(object x) - { - this.Remove((IAppender)x); - } - - void IList.RemoveAt(int pos) - { - this.RemoveAt(pos); - } - - IEnumerator IEnumerable.GetEnumerator() - { - return (IEnumerator)this.GetEnumerator(); - } - - /// - /// Supports simple iteration over a . - /// - /// - private sealed class Enumerator : IEnumerator, IAppenderCollectionEnumerator - { - private readonly AppenderCollection m_collection; - private int m_index; + /// Initializes a new instance of the AppenderCollection class + /// that is empty and has the default initial capacity. + /// + public AppenderCollection() + { + this.m_array = new IAppender[DEFAULT_CAPACITY]; + } + + /// + /// Initializes a new instance of the AppenderCollection class + /// that has the specified initial capacity. + /// + /// + /// The number of elements that the new AppenderCollection is initially capable of storing. + /// + public AppenderCollection(int capacity) + { + this.m_array = new IAppender[capacity]; + } + + /// + /// Initializes a new instance of the AppenderCollection class + /// that contains elements copied from the specified AppenderCollection. + /// + /// The AppenderCollection whose elements are copied to the new collection. + public AppenderCollection(AppenderCollection c) + { + this.m_array = new IAppender[c.Count]; + this.AddRange(c); + } + + /// + /// Initializes a new instance of the AppenderCollection class + /// that contains elements copied from the specified array. + /// + /// The array whose elements are copied to the new list. + public AppenderCollection(IAppender[] a) + { + this.m_array = new IAppender[a.Length]; + this.AddRange(a); + } + + /// + /// Initializes a new instance of the AppenderCollection class + /// that contains elements copied from the specified collection. + /// + /// The collection whose elements are copied to the new list. + public AppenderCollection(ICollection col) + { + this.m_array = new IAppender[col.Count]; + this.AddRange(col); + } + + /// + /// Type visible only to our subclasses + /// Used to access protected constructor + /// + /// + protected internal enum Tag + { + /// + /// A value + /// + Default + } + + /// + /// Allow subclasses to avoid our default constructors + /// + /// + /// + protected internal AppenderCollection(Tag tag) + { + this.m_array = null; + } + + /// + /// Gets the number of elements actually contained in the AppenderCollection. + /// + public virtual int Count + { + get { return this.m_count; } + } + + /// + /// Copies the entire AppenderCollection to a one-dimensional + /// array. + /// + /// The one-dimensional array to copy to. + public virtual void CopyTo(IAppender[] array) + { + this.CopyTo(array, 0); + } + + /// + /// Copies the entire AppenderCollection to a one-dimensional + /// array, starting at the specified index of the target array. + /// + /// The one-dimensional array to copy to. + /// The zero-based index in at which copying begins. + public virtual void CopyTo(IAppender[] array, int start) + { + if (this.m_count > array.GetUpperBound(0) + 1 - start) + { + throw new ArgumentException("Destination array was not long enough."); + } + + Array.Copy(this.m_array, 0, array, start, this.m_count); + } + + /// + /// Gets a value indicating whether access to the collection is synchronized (thread-safe). + /// + /// false, because the backing type is an array, which is never thread-safe. + public virtual bool IsSynchronized + { + get { return false; } + } + + /// + /// Gets an object that can be used to synchronize access to the collection. + /// + public virtual object SyncRoot + { + get { return this.m_array; } + } + + /// + /// Gets or sets the at the specified index. + /// + /// The zero-based index of the element to get or set. + /// + /// is less than zero + /// -or- + /// is equal to or greater than . + /// + public virtual IAppender this[int index] + { + get + { + this.ValidateIndex(index); // throws + return this.m_array[index]; + } + set + { + this.ValidateIndex(index); // throws + ++this.m_version; + this.m_array[index] = value; + } + } + + /// + /// Adds a to the end of the AppenderCollection. + /// + /// The to be added to the end of the AppenderCollection. + /// The index at which the value has been added. + public virtual int Add(IAppender item) + { + if (this.m_count == this.m_array.Length) + { + this.EnsureCapacity(this.m_count + 1); + } + + this.m_array[this.m_count] = item; + this.m_version++; + + return this.m_count++; + } + + /// + /// Removes all elements from the AppenderCollection. + /// + public virtual void Clear() + { + ++this.m_version; + this.m_array = new IAppender[DEFAULT_CAPACITY]; + this.m_count = 0; + } + + /// + /// Creates a shallow copy of the . + /// + /// A new with a shallow copy of the collection data. + public virtual object Clone() + { + AppenderCollection newCol = new AppenderCollection(this.m_count); + Array.Copy(this.m_array, 0, newCol.m_array, 0, this.m_count); + newCol.m_count = this.m_count; + newCol.m_version = this.m_version; + + return newCol; + } + + /// + /// Determines whether a given is in the AppenderCollection. + /// + /// The to check for. + /// true if is found in the AppenderCollection; otherwise, false. + public virtual bool Contains(IAppender item) + { + for (int i = 0; i != this.m_count; ++i) + { + if (this.m_array[i].Equals(item)) + { + return true; + } + } + return false; + } + + /// + /// Returns the zero-based index of the first occurrence of a + /// in the AppenderCollection. + /// + /// The to locate in the AppenderCollection. + /// + /// The zero-based index of the first occurrence of + /// in the entire AppenderCollection, if found; otherwise, -1. + /// + public virtual int IndexOf(IAppender item) + { + for (int i = 0; i != this.m_count; ++i) + { + if (this.m_array[i].Equals(item)) + { + return i; + } + } + return -1; + } + + /// + /// Inserts an element into the AppenderCollection at the specified index. + /// + /// The zero-based index at which should be inserted. + /// The to insert. + /// + /// is less than zero + /// -or- + /// is equal to or greater than . + /// + public virtual void Insert(int index, IAppender item) + { + this.ValidateIndex(index, true); // throws + + if (this.m_count == this.m_array.Length) + { + this.EnsureCapacity(this.m_count + 1); + } + + if (index < this.m_count) + { + Array.Copy(this.m_array, index, this.m_array, index + 1, this.m_count - index); + } + + this.m_array[index] = item; + this.m_count++; + this.m_version++; + } + + /// + /// Removes the first occurrence of a specific from the AppenderCollection. + /// + /// The to remove from the AppenderCollection. + /// + /// The specified was not found in the AppenderCollection. + /// + public virtual void Remove(IAppender item) + { + int i = this.IndexOf(item); + if (i < 0) + { + throw new ArgumentException("Cannot remove the specified item because it was not found in the specified Collection."); + } + + ++this.m_version; + this.RemoveAt(i); + } + + /// + /// Removes the element at the specified index of the AppenderCollection. + /// + /// The zero-based index of the element to remove. + /// + /// is less than zero + /// -or- + /// is equal to or greater than . + /// + public virtual void RemoveAt(int index) + { + this.ValidateIndex(index); // throws + + this.m_count--; + + if (index < this.m_count) + { + Array.Copy(this.m_array, index + 1, this.m_array, index, this.m_count - index); + } + + // We can't set the deleted entry equal to null, because it might be a value type. + // Instead, we'll create an empty single-element array of the right type and copy it + // over the entry we want to erase. + IAppender[] temp = new IAppender[1]; + Array.Copy(temp, 0, this.m_array, this.m_count, 1); + this.m_version++; + } + + /// + /// Gets a value indicating whether the collection has a fixed size. + /// + /// true if the collection has a fixed size; otherwise, false. The default is false + public virtual bool IsFixedSize + { + get { return false; } + } + + /// + /// Gets a value indicating whether the IList is read-only. + /// + /// true if the collection is read-only; otherwise, false. The default is false + public virtual bool IsReadOnly + { + get { return false; } + } + + /// + /// Returns an enumerator that can iterate through the AppenderCollection. + /// + /// An for the entire AppenderCollection. + public virtual IAppenderCollectionEnumerator GetEnumerator() + { + return new Enumerator(this); + } + + /// + /// Gets or sets the number of elements the AppenderCollection can contain. + /// + public virtual int Capacity + { + get + { + return this.m_array.Length; + } + set + { + if (value < this.m_count) + { + value = this.m_count; + } + + if (value != this.m_array.Length) + { + if (value > 0) + { + IAppender[] temp = new IAppender[value]; + Array.Copy(this.m_array, 0, temp, 0, this.m_count); + this.m_array = temp; + } + else + { + this.m_array = new IAppender[DEFAULT_CAPACITY]; + } + } + } + } + + /// + /// Adds the elements of another AppenderCollection to the current AppenderCollection. + /// + /// The AppenderCollection whose elements should be added to the end of the current AppenderCollection. + /// The new of the AppenderCollection. + public virtual int AddRange(AppenderCollection x) + { + if (this.m_count + x.Count >= this.m_array.Length) + { + this.EnsureCapacity(this.m_count + x.Count); + } + + Array.Copy(x.m_array, 0, this.m_array, this.m_count, x.Count); + this.m_count += x.Count; + this.m_version++; + + return this.m_count; + } + + /// + /// Adds the elements of a array to the current AppenderCollection. + /// + /// The array whose elements should be added to the end of the AppenderCollection. + /// The new of the AppenderCollection. + public virtual int AddRange(IAppender[] x) + { + if (this.m_count + x.Length >= this.m_array.Length) + { + this.EnsureCapacity(this.m_count + x.Length); + } + + Array.Copy(x, 0, this.m_array, this.m_count, x.Length); + this.m_count += x.Length; + this.m_version++; + + return this.m_count; + } + + /// + /// Adds the elements of a collection to the current AppenderCollection. + /// + /// The collection whose elements should be added to the end of the AppenderCollection. + /// The new of the AppenderCollection. + public virtual int AddRange(ICollection col) + { + if (this.m_count + col.Count >= this.m_array.Length) + { + this.EnsureCapacity(this.m_count + col.Count); + } + + foreach(object item in col) + { + this.Add((IAppender)item); + } + + return this.m_count; + } + + /// + /// Sets the capacity to the actual number of elements. + /// + public virtual void TrimToSize() + { + this.Capacity = this.m_count; + } + + /// + /// Return the collection elements as an array + /// + /// the array + public virtual IAppender[] ToArray() + { + IAppender[] resultArray = new IAppender[this.m_count]; + if (this.m_count > 0) + { + Array.Copy(this.m_array, 0, resultArray, 0, this.m_count); + } + return resultArray; + } + + /// + /// is less than zero + /// -or- + /// is equal to or greater than . + /// + private void ValidateIndex(int i) + { + this.ValidateIndex(i, false); + } + + /// + /// is less than zero + /// -or- + /// is equal to or greater than . + /// + private void ValidateIndex(int i, bool allowEqualEnd) + { + int max = (allowEqualEnd) ? (this.m_count) : (this.m_count-1); + if (i < 0 || i > max) + { + throw Util.SystemInfo.CreateArgumentOutOfRangeException("i", (object)i, "Index was out of range. Must be non-negative and less than the size of the collection. [" + (object)i + "] Specified argument was out of the range of valid values."); + } + } + + private void EnsureCapacity(int min) + { + int newCapacity = ((this.m_array.Length == 0) ? DEFAULT_CAPACITY : this.m_array.Length * 2); + if (newCapacity < min) + { + newCapacity = min; + } + + this.Capacity = newCapacity; + } + + void ICollection.CopyTo(Array array, int start) + { + if (this.m_count > 0) + { + Array.Copy(this.m_array, 0, array, start, this.m_count); + } + } + + object IList.this[int i] + { + get { return (object)this[i]; } + set { this[i] = (IAppender)value; } + } + + int IList.Add(object x) + { + return this.Add((IAppender)x); + } + + bool IList.Contains(object x) + { + return this.Contains((IAppender)x); + } + + int IList.IndexOf(object x) + { + return this.IndexOf((IAppender)x); + } + + void IList.Insert(int pos, object x) + { + this.Insert(pos, (IAppender)x); + } + + void IList.Remove(object x) + { + this.Remove((IAppender)x); + } + + void IList.RemoveAt(int pos) + { + this.RemoveAt(pos); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return (IEnumerator)(this.GetEnumerator()); + } + + /// + /// Supports simple iteration over a . + /// + /// + private sealed class Enumerator : IEnumerator, IAppenderCollectionEnumerator + { + private readonly AppenderCollection m_collection; + private int m_index; private int m_version; /// - /// Initializes a new instance of the class. - /// Initializes a new instance of the Enumerator class. - /// - /// - internal Enumerator(AppenderCollection tc) - { - this.m_collection = tc; - this.m_index = -1; - this.m_version = tc.m_version; - } - - /// - /// Gets the current element in the collection. - /// - public IAppender Current - { - get { return this.m_collection[this.m_index]; } - } - - /// - /// Advances the enumerator to the next element in the collection. - /// - /// - /// true if the enumerator was successfully advanced to the next element; - /// false if the enumerator has passed the end of the collection. - /// - /// - /// The collection was modified after the enumerator was created. - /// - public bool MoveNext() - { - if (this.m_version != this.m_collection.m_version) - { - throw new System.InvalidOperationException("Collection was modified; enumeration operation may not execute."); - } - - ++this.m_index; - return this.m_index < this.m_collection.Count; - } - - /// - /// Sets the enumerator to its initial position, before the first element in the collection. - /// - public void Reset() - { - this.m_index = -1; - } - - object IEnumerator.Current - { - get { return this.Current; } - } - } - - /// - private sealed class ReadOnlyAppenderCollection : AppenderCollection, ICollection + /// Initializes a new instance of the Enumerator class. + /// + /// + internal Enumerator(AppenderCollection tc) + { + this.m_collection = tc; + this.m_index = -1; + this.m_version = tc.m_version; + } + + /// + /// Gets the current element in the collection. + /// + public IAppender Current + { + get { return this.m_collection[this.m_index]; } + } + + /// + /// Advances the enumerator to the next element in the collection. + /// + /// + /// true if the enumerator was successfully advanced to the next element; + /// false if the enumerator has passed the end of the collection. + /// + /// + /// The collection was modified after the enumerator was created. + /// + public bool MoveNext() + { + if (this.m_version != this.m_collection.m_version) + { + throw new InvalidOperationException("Collection was modified; enumeration operation may not execute."); + } + + ++this.m_index; + return (this.m_index < this.m_collection.Count); + } + + /// + /// Sets the enumerator to its initial position, before the first element in the collection. + /// + public void Reset() + { + this.m_index = -1; + } + + object IEnumerator.Current + { + get { return this.Current; } + } + } + + /// + private sealed class ReadOnlyAppenderCollection : AppenderCollection, ICollection { private readonly AppenderCollection m_collection; - internal ReadOnlyAppenderCollection(AppenderCollection list) - : base(Tag.Default) - { - this.m_collection = list; - } - - public override void CopyTo(IAppender[] array) - { - this.m_collection.CopyTo(array); - } - - public override void CopyTo(IAppender[] array, int start) - { - this.m_collection.CopyTo(array, start); - } - - void ICollection.CopyTo(Array array, int start) - { - ((ICollection)this.m_collection).CopyTo(array, start); - } - - public override int Count - { - get { return this.m_collection.Count; } - } - - public override bool IsSynchronized - { - get { return this.m_collection.IsSynchronized; } - } - - public override object SyncRoot - { - get { return this.m_collection.SyncRoot; } - } - - public override IAppender this[int i] - { - get { return this.m_collection[i]; } - set { throw new NotSupportedException("This is a Read Only Collection and can not be modified"); } - } - - public override int Add(IAppender x) - { - throw new NotSupportedException("This is a Read Only Collection and can not be modified"); - } - - public override void Clear() - { - throw new NotSupportedException("This is a Read Only Collection and can not be modified"); - } - - public override bool Contains(IAppender x) - { - return this.m_collection.Contains(x); - } - - public override int IndexOf(IAppender x) - { - return this.m_collection.IndexOf(x); - } - - public override void Insert(int pos, IAppender x) - { - throw new NotSupportedException("This is a Read Only Collection and can not be modified"); - } - - public override void Remove(IAppender x) - { - throw new NotSupportedException("This is a Read Only Collection and can not be modified"); - } - - public override void RemoveAt(int pos) - { - throw new NotSupportedException("This is a Read Only Collection and can not be modified"); - } - - public override bool IsFixedSize - { - get { return true; } - } - - public override bool IsReadOnly - { - get { return true; } - } - - public override IAppenderCollectionEnumerator GetEnumerator() - { - return this.m_collection.GetEnumerator(); + internal ReadOnlyAppenderCollection(AppenderCollection list) : base(Tag.Default) + { + this.m_collection = list; + } + + public override void CopyTo(IAppender[] array) + { + this.m_collection.CopyTo(array); + } + + public override void CopyTo(IAppender[] array, int start) + { + this.m_collection.CopyTo(array, start); + } + + void ICollection.CopyTo(Array array, int start) + { + ((ICollection)this.m_collection).CopyTo(array, start); + } + + public override int Count + { + get { return this.m_collection.Count; } + } + + public override bool IsSynchronized + { + get { return this.m_collection.IsSynchronized; } + } + + public override object SyncRoot + { + get { return this.m_collection.SyncRoot; } + } + + public override IAppender this[int i] + { + get { return this.m_collection[i]; } + set { throw new NotSupportedException("This is a Read Only Collection and can not be modified"); } + } + + public override int Add(IAppender x) + { + throw new NotSupportedException("This is a Read Only Collection and can not be modified"); + } + + public override void Clear() + { + throw new NotSupportedException("This is a Read Only Collection and can not be modified"); + } + + public override bool Contains(IAppender x) + { + return this.m_collection.Contains(x); + } + + public override int IndexOf(IAppender x) + { + return this.m_collection.IndexOf(x); + } + + public override void Insert(int pos, IAppender x) + { + throw new NotSupportedException("This is a Read Only Collection and can not be modified"); + } + + public override void Remove(IAppender x) + { + throw new NotSupportedException("This is a Read Only Collection and can not be modified"); + } + + public override void RemoveAt(int pos) + { + throw new NotSupportedException("This is a Read Only Collection and can not be modified"); + } + + public override bool IsFixedSize + { + get { return true; } + } + + public override bool IsReadOnly + { + get { return true; } + } + + public override IAppenderCollectionEnumerator GetEnumerator() + { + return this.m_collection.GetEnumerator(); } // (just to mimic some nice features of ArrayList) - public override int Capacity - { - get { return this.m_collection.Capacity; } - set { throw new NotSupportedException("This is a Read Only Collection and can not be modified"); } - } - - public override int AddRange(AppenderCollection x) - { - throw new NotSupportedException("This is a Read Only Collection and can not be modified"); - } - - public override int AddRange(IAppender[] x) - { - throw new NotSupportedException("This is a Read Only Collection and can not be modified"); - } - - public override IAppender[] ToArray() - { - return this.m_collection.ToArray(); - } - - public override void TrimToSize() - { - throw new NotSupportedException("This is a Read Only Collection and can not be modified"); - } - } - } -} + public override int Capacity + { + get { return this.m_collection.Capacity; } + set { throw new NotSupportedException("This is a Read Only Collection and can not be modified"); } + } + + public override int AddRange(AppenderCollection x) + { + throw new NotSupportedException("This is a Read Only Collection and can not be modified"); + } + + public override int AddRange(IAppender[] x) + { + throw new NotSupportedException("This is a Read Only Collection and can not be modified"); + } + + public override IAppender[] ToArray() + { + return this.m_collection.ToArray(); + } + + public override void TrimToSize() + { + throw new NotSupportedException("This is a Read Only Collection and can not be modified"); + } + } + } + +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/AppenderSkeleton.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/AppenderSkeleton.cs index 1dde3bb4374..24410b3283a 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/AppenderSkeleton.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/AppenderSkeleton.cs @@ -1,867 +1,866 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.Appender -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; - using System.Collections; - using System.IO; - - using log4net.Core; - using log4net.Filter; - using log4net.Layout; - using log4net.Util; - - /// - /// Abstract base class implementation of . - /// - /// - /// - /// This class provides the code for common functionality, such - /// as support for threshold filtering and support for general filters. - /// - /// - /// Appenders can also implement the interface. Therefore - /// they would require that the method - /// be called after the appenders properties have been configured. - /// - /// - /// Nicko Cadell. - /// Gert Driesen. - public abstract class AppenderSkeleton : IAppender, IBulkAppender, IOptionHandler, IFlushable +using System; +using System.IO; +using System.Collections; + +using log4net.Filter; +using log4net.Util; +using log4net.Layout; +using log4net.Core; + +namespace log4net.Appender +{ + /// + /// Abstract base class implementation of . + /// + /// + /// + /// This class provides the code for common functionality, such + /// as support for threshold filtering and support for general filters. + /// + /// + /// Appenders can also implement the interface. Therefore + /// they would require that the method + /// be called after the appenders properties have been configured. + /// + /// + /// Nicko Cadell + /// Gert Driesen + public abstract class AppenderSkeleton : IAppender, IBulkAppender, IOptionHandler, IFlushable { /// - /// Initializes a new instance of the class. - /// Default constructor. - /// - /// - /// Empty default constructor. - /// - protected AppenderSkeleton() - { - this.m_errorHandler = new OnlyOnceErrorHandler(this.GetType().Name); + /// Default constructor + /// + /// + /// Empty default constructor + /// + protected AppenderSkeleton() + { + this.m_errorHandler = new OnlyOnceErrorHandler(this.GetType().Name); + } + + /// + /// Finalizes this appender by calling the implementation's + /// method. + /// + /// + /// + /// If this appender has not been closed then the Finalize method + /// will call . + /// + /// + ~AppenderSkeleton() + { + // An appender might be closed then garbage collected. + // There is no point in closing twice. + if (!this.m_closed) + { + LogLog.Debug(declaringType, "Finalizing appender named ["+ this.m_name+"]."); + this.Close(); + } + } + + /// + /// Gets or sets the threshold of this appender. + /// + /// + /// The threshold of the appender. + /// + /// + /// + /// All log events with lower level than the threshold level are ignored + /// by the appender. + /// + /// + /// In configuration files this option is specified by setting the + /// value of the option to a level + /// string, such as "DEBUG", "INFO" and so on. + /// + /// + public Level Threshold + { + get { return this.m_threshold; } + set { this.m_threshold = value; } } /// - /// Finalizes an instance of the class. - /// Finalizes this appender by calling the implementation's - /// method. - /// - /// - /// - /// If this appender has not been closed then the Finalize method - /// will call . - /// - /// - ~AppenderSkeleton() - { - // An appender might be closed then garbage collected. - // There is no point in closing twice. - if (!this.m_closed) - { - LogLog.Debug(declaringType, "Finalizing appender named [" + this.m_name + "]."); - this.Close(); - } + /// Gets or sets the for this appender. + /// + /// The of the appender + /// + /// + /// The provides a default + /// implementation for the property. + /// + /// + public virtual IErrorHandler ErrorHandler + { + get { return this.m_errorHandler; } + set + { + lock(this) + { + if (value == null) + { + // We do not throw exception here since the cause is probably a + // bad config file. + LogLog.Warn(declaringType, "You have tried to set a null error-handler."); + } + else + { + this.m_errorHandler = value; + } + } + } } - /// - /// Gets or sets the threshold of this appender. - /// - /// - /// The threshold of the appender. - /// - /// - /// - /// All log events with lower level than the threshold level are ignored - /// by the appender. - /// - /// - /// In configuration files this option is specified by setting the - /// value of the option to a level - /// string, such as "DEBUG", "INFO" and so on. - /// - /// - public Level Threshold - { - get { return this.m_threshold; } - set { this.m_threshold = value; } - } - - /// - /// Gets or sets the for this appender. - /// - /// The of the appender. - /// - /// - /// The provides a default - /// implementation for the property. - /// - /// - public virtual IErrorHandler ErrorHandler - { - get { return this.m_errorHandler; } - - set - { - lock (this) - { - if (value == null) - { - // We do not throw exception here since the cause is probably a - // bad config file. - LogLog.Warn(declaringType, "You have tried to set a null error-handler."); - } - else - { - this.m_errorHandler = value; - } - } - } - } - - /// - /// Gets the filter chain. - /// - /// The head of the filter chain filter chain. - /// - /// - /// Returns the head Filter. The Filters are organized in a linked list - /// and so all Filters on this Appender are available through the result. - /// - /// - public virtual IFilter FilterHead - { - get { return this.m_headFilter; } - } - - /// - /// Gets or sets the for this appender. - /// - /// The layout of the appender. - /// - /// - /// See for more information. - /// - /// - /// - public virtual ILayout Layout - { - get { return this.m_layout; } - set { this.m_layout = value; } + /// + /// The filter chain. + /// + /// The head of the filter chain filter chain. + /// + /// + /// Returns the head Filter. The Filters are organized in a linked list + /// and so all Filters on this Appender are available through the result. + /// + /// + public virtual IFilter FilterHead + { + get { return this.m_headFilter; } } - /// - /// Initialize the appender based on the options set. - /// - /// - /// - /// This is part of the delayed object - /// activation scheme. The method must - /// be called on this object after the configuration properties have - /// been set. Until is called this - /// object is in an undefined state and must not be used. - /// - /// - /// If any of the configuration properties are modified then - /// must be called again. - /// - /// - public virtual void ActivateOptions() - { + /// + /// Gets or sets the for this appender. + /// + /// The layout of the appender. + /// + /// + /// See for more information. + /// + /// + /// + public virtual ILayout Layout + { + get { return this.m_layout; } + set { this.m_layout = value; } } - /// - /// Gets or sets the name of this appender. - /// - /// The name of the appender. - /// - /// - /// The name uniquely identifies the appender. - /// - /// - public string Name - { - get { return this.m_name; } - set { this.m_name = value; } - } - - /// - /// Closes the appender and release resources. - /// - /// - /// - /// Release any resources allocated within the appender such as file handles, - /// network connections, etc. - /// - /// - /// It is a programming error to append to a closed appender. - /// - /// - /// This method cannot be overridden by subclasses. This method - /// delegates the closing of the appender to the - /// method which must be overridden in the subclass. - /// - /// - public void Close() - { - // This lock prevents the appender being closed while it is still appending - lock (this) - { - if (!this.m_closed) - { - this.OnClose(); - this.m_closed = true; - } - } - } - - /// - /// Performs threshold checks and invokes filters before - /// delegating actual logging to the subclasses specific - /// method. - /// - /// The event to log. - /// - /// - /// This method cannot be overridden by derived classes. A - /// derived class should override the method - /// which is called by this method. - /// - /// - /// The implementation of this method is as follows: - /// - /// - /// - /// - /// - /// Checks that the severity of the - /// is greater than or equal to the of this - /// appender. - /// - /// - /// - /// Checks that the chain accepts the - /// . - /// - /// - /// - /// - /// Calls and checks that - /// it returns true. - /// - /// - /// - /// - /// If all of the above steps succeed then the - /// will be passed to the abstract method. - /// - /// - public void DoAppend(LoggingEvent loggingEvent) - { - // This lock is absolutely critical for correct formatting - // of the message in a multi-threaded environment. Without - // this, the message may be broken up into elements from - // multiple thread contexts (like get the wrong thread ID). - lock (this) - { - if (this.m_closed) - { - this.ErrorHandler.Error("Attempted to append to closed appender named [" + this.m_name + "]."); - return; - } - - // prevent re-entry - if (this.m_recursiveGuard) - { - return; - } - - try - { - this.m_recursiveGuard = true; - - if (this.FilterEvent(loggingEvent) && this.PreAppendCheck()) - { - this.Append(loggingEvent); - } - } - catch (Exception ex) - { - this.ErrorHandler.Error("Failed in DoAppend", ex); - } -#if !MONO && !NET_2_0 && !NETSTANDARD1_3 - // on .NET 2.0 (and higher) and Mono (all profiles), - // exceptions that do not derive from System.Exception will be - // wrapped in a RuntimeWrappedException by the runtime, and as - // such will be catched by the catch clause above - catch - { - // Catch handler for non System.Exception types - ErrorHandler.Error("Failed in DoAppend (unknown exception)"); - } -#endif - finally - { - this.m_recursiveGuard = false; - } - } + /// + /// Initialize the appender based on the options set + /// + /// + /// + /// This is part of the delayed object + /// activation scheme. The method must + /// be called on this object after the configuration properties have + /// been set. Until is called this + /// object is in an undefined state and must not be used. + /// + /// + /// If any of the configuration properties are modified then + /// must be called again. + /// + /// + public virtual void ActivateOptions() + { + } + + /// + /// Gets or sets the name of this appender. + /// + /// The name of the appender. + /// + /// + /// The name uniquely identifies the appender. + /// + /// + public string Name + { + get { return this.m_name; } + set { this.m_name = value; } + } + + /// + /// Closes the appender and release resources. + /// + /// + /// + /// Release any resources allocated within the appender such as file handles, + /// network connections, etc. + /// + /// + /// It is a programming error to append to a closed appender. + /// + /// + /// This method cannot be overridden by subclasses. This method + /// delegates the closing of the appender to the + /// method which must be overridden in the subclass. + /// + /// + public void Close() + { + // This lock prevents the appender being closed while it is still appending + lock(this) + { + if (!this.m_closed) + { + this.OnClose(); + this.m_closed = true; + } + } + } + + /// + /// Performs threshold checks and invokes filters before + /// delegating actual logging to the subclasses specific + /// method. + /// + /// The event to log. + /// + /// + /// This method cannot be overridden by derived classes. A + /// derived class should override the method + /// which is called by this method. + /// + /// + /// The implementation of this method is as follows: + /// + /// + /// + /// + /// + /// Checks that the severity of the + /// is greater than or equal to the of this + /// appender. + /// + /// + /// + /// Checks that the chain accepts the + /// . + /// + /// + /// + /// + /// Calls and checks that + /// it returns true. + /// + /// + /// + /// + /// If all of the above steps succeed then the + /// will be passed to the abstract method. + /// + /// + public void DoAppend(LoggingEvent loggingEvent) + { + // This lock is absolutely critical for correct formatting + // of the message in a multi-threaded environment. Without + // this, the message may be broken up into elements from + // multiple thread contexts (like get the wrong thread ID). + + lock(this) + { + if (this.m_closed) + { + this.ErrorHandler.Error("Attempted to append to closed appender named ["+ this.m_name+"]."); + return; + } + + // prevent re-entry + if (this.m_recursiveGuard) + { + return; + } + + try + { + this.m_recursiveGuard = true; + + if (this.FilterEvent(loggingEvent) && this.PreAppendCheck()) + { + this.Append(loggingEvent); + } + } + catch(Exception ex) + { + this.ErrorHandler.Error("Failed in DoAppend", ex); + } +#if !MONO && !NET_2_0 && !NETSTANDARD + // on .NET 2.0 (and higher) and Mono (all profiles), + // exceptions that do not derive from System.Exception will be + // wrapped in a RuntimeWrappedException by the runtime, and as + // such will be catched by the catch clause above + catch + { + // Catch handler for non System.Exception types + ErrorHandler.Error("Failed in DoAppend (unknown exception)"); + } +#endif + finally + { + this.m_recursiveGuard = false; + } + } + } + + /// + /// Performs threshold checks and invokes filters before + /// delegating actual logging to the subclasses specific + /// method. + /// + /// The array of events to log. + /// + /// + /// This method cannot be overridden by derived classes. A + /// derived class should override the method + /// which is called by this method. + /// + /// + /// The implementation of this method is as follows: + /// + /// + /// + /// + /// + /// Checks that the severity of the + /// is greater than or equal to the of this + /// appender. + /// + /// + /// + /// Checks that the chain accepts the + /// . + /// + /// + /// + /// + /// Calls and checks that + /// it returns true. + /// + /// + /// + /// + /// If all of the above steps succeed then the + /// will be passed to the method. + /// + /// + public void DoAppend(LoggingEvent[] loggingEvents) + { + // This lock is absolutely critical for correct formatting + // of the message in a multi-threaded environment. Without + // this, the message may be broken up into elements from + // multiple thread contexts (like get the wrong thread ID). + + lock(this) + { + if (this.m_closed) + { + this.ErrorHandler.Error("Attempted to append to closed appender named ["+ this.m_name+"]."); + return; + } + + // prevent re-entry + if (this.m_recursiveGuard) + { + return; + } + + try + { + this.m_recursiveGuard = true; + + ArrayList filteredEvents = new ArrayList(loggingEvents.Length); + + foreach(LoggingEvent loggingEvent in loggingEvents) + { + if (this.FilterEvent(loggingEvent)) + { + filteredEvents.Add(loggingEvent); + } + } + + if (filteredEvents.Count > 0 && this.PreAppendCheck()) + { + this.Append((LoggingEvent[])filteredEvents.ToArray(typeof(LoggingEvent))); + } + } + catch(Exception ex) + { + this.ErrorHandler.Error("Failed in Bulk DoAppend", ex); + } +#if !MONO && !NET_2_0 && !NETSTANDARD + // on .NET 2.0 (and higher) and Mono (all profiles), + // exceptions that do not derive from System.Exception will be + // wrapped in a RuntimeWrappedException by the runtime, and as + // such will be catched by the catch clause above + catch + { + // Catch handler for non System.Exception types + ErrorHandler.Error("Failed in Bulk DoAppend (unknown exception)"); + } +#endif + finally + { + this.m_recursiveGuard = false; + } + } + } + + /// + /// Test if the logging event should we output by this appender + /// + /// the event to test + /// true if the event should be output, false if the event should be ignored + /// + /// + /// This method checks the logging event against the threshold level set + /// on this appender and also against the filters specified on this + /// appender. + /// + /// + /// The implementation of this method is as follows: + /// + /// + /// + /// + /// + /// Checks that the severity of the + /// is greater than or equal to the of this + /// appender. + /// + /// + /// + /// Checks that the chain accepts the + /// . + /// + /// + /// + /// + /// + protected virtual bool FilterEvent(LoggingEvent loggingEvent) + { + if (!this.IsAsSevereAsThreshold(loggingEvent.Level)) + { + return false; + } + + IFilter f = this.FilterHead; + + while(f != null) + { + switch(f.Decide(loggingEvent)) + { + case FilterDecision.Deny: + return false; // Return without appending + + case FilterDecision.Accept: + f = null; // Break out of the loop + break; + + case FilterDecision.Neutral: + f = f.Next; // Move to next filter + break; + } + } + + return true; + } + + /// + /// Adds a filter to the end of the filter chain. + /// + /// the filter to add to this appender + /// + /// + /// The Filters are organized in a linked list. + /// + /// + /// Setting this property causes the new filter to be pushed onto the + /// back of the filter chain. + /// + /// + public virtual void AddFilter(IFilter filter) + { + if (filter == null) + { + throw new ArgumentNullException("filter param must not be null"); + } + + if (this.m_headFilter == null) + { + this.m_headFilter = this.m_tailFilter = filter; + } + else + { + this.m_tailFilter.Next = filter; + this.m_tailFilter = filter; + } } - /// - /// Performs threshold checks and invokes filters before - /// delegating actual logging to the subclasses specific - /// method. - /// - /// The array of events to log. - /// - /// - /// This method cannot be overridden by derived classes. A - /// derived class should override the method - /// which is called by this method. - /// - /// - /// The implementation of this method is as follows: - /// - /// - /// - /// - /// - /// Checks that the severity of the - /// is greater than or equal to the of this - /// appender. - /// - /// - /// - /// Checks that the chain accepts the - /// . - /// - /// - /// - /// - /// Calls and checks that - /// it returns true. - /// - /// - /// - /// - /// If all of the above steps succeed then the - /// will be passed to the method. - /// - /// - public void DoAppend(LoggingEvent[] loggingEvents) - { - // This lock is absolutely critical for correct formatting - // of the message in a multi-threaded environment. Without - // this, the message may be broken up into elements from - // multiple thread contexts (like get the wrong thread ID). - lock (this) - { - if (this.m_closed) - { - this.ErrorHandler.Error("Attempted to append to closed appender named [" + this.m_name + "]."); - return; - } - - // prevent re-entry - if (this.m_recursiveGuard) - { - return; - } - - try - { - this.m_recursiveGuard = true; - - ArrayList filteredEvents = new ArrayList(loggingEvents.Length); - - foreach (LoggingEvent loggingEvent in loggingEvents) - { - if (this.FilterEvent(loggingEvent)) - { - filteredEvents.Add(loggingEvent); - } - } - - if (filteredEvents.Count > 0 && this.PreAppendCheck()) - { - this.Append((LoggingEvent[])filteredEvents.ToArray(typeof(LoggingEvent))); - } - } - catch (Exception ex) - { - this.ErrorHandler.Error("Failed in Bulk DoAppend", ex); - } -#if !MONO && !NET_2_0 && !NETSTANDARD1_3 - // on .NET 2.0 (and higher) and Mono (all profiles), - // exceptions that do not derive from System.Exception will be - // wrapped in a RuntimeWrappedException by the runtime, and as - // such will be catched by the catch clause above - catch - { - // Catch handler for non System.Exception types - ErrorHandler.Error("Failed in Bulk DoAppend (unknown exception)"); - } -#endif - finally - { - this.m_recursiveGuard = false; - } - } + /// + /// Clears the filter list for this appender. + /// + /// + /// + /// Clears the filter list for this appender. + /// + /// + public virtual void ClearFilters() + { + this.m_headFilter = this.m_tailFilter = null; } - /// - /// Test if the logging event should we output by this appender. - /// - /// the event to test. - /// true if the event should be output, false if the event should be ignored. - /// - /// - /// This method checks the logging event against the threshold level set - /// on this appender and also against the filters specified on this - /// appender. - /// - /// - /// The implementation of this method is as follows: - /// - /// - /// - /// - /// - /// Checks that the severity of the - /// is greater than or equal to the of this - /// appender. - /// - /// - /// - /// Checks that the chain accepts the - /// . - /// - /// - /// - /// - /// - protected virtual bool FilterEvent(LoggingEvent loggingEvent) - { - if (!this.IsAsSevereAsThreshold(loggingEvent.Level)) - { - return false; - } - - IFilter f = this.FilterHead; - - while (f != null) - { - switch (f.Decide(loggingEvent)) - { - case FilterDecision.Deny: - return false; // Return without appending - - case FilterDecision.Accept: - f = null; // Break out of the loop - break; - - case FilterDecision.Neutral: - f = f.Next; // Move to next filter - break; - } - } - - return true; + /// + /// Checks if the message level is below this appender's threshold. + /// + /// to test against. + /// + /// + /// If there is no threshold set, then the return value is always true. + /// + /// + /// + /// true if the meets the + /// requirements of this appender. + /// + protected virtual bool IsAsSevereAsThreshold(Level level) + { + return ((this.m_threshold == null) || level >= this.m_threshold); } - /// - /// Adds a filter to the end of the filter chain. - /// - /// the filter to add to this appender. - /// - /// - /// The Filters are organized in a linked list. - /// - /// - /// Setting this property causes the new filter to be pushed onto the - /// back of the filter chain. - /// - /// - public virtual void AddFilter(IFilter filter) - { - if (filter == null) - { - throw new ArgumentNullException("filter param must not be null"); - } - - if (this.m_headFilter == null) - { - this.m_headFilter = this.m_tailFilter = filter; - } - else - { - this.m_tailFilter.Next = filter; - this.m_tailFilter = filter; - } - } - - /// - /// Clears the filter list for this appender. - /// - /// - /// - /// Clears the filter list for this appender. - /// - /// - public virtual void ClearFilters() - { - this.m_headFilter = this.m_tailFilter = null; + /// + /// Is called when the appender is closed. Derived classes should override + /// this method if resources need to be released. + /// + /// + /// + /// Releases any resources allocated within the appender such as file handles, + /// network connections, etc. + /// + /// + /// It is a programming error to append to a closed appender. + /// + /// + protected virtual void OnClose() + { + // Do nothing by default } - /// - /// Checks if the message level is below this appender's threshold. - /// - /// to test against. - /// - /// - /// If there is no threshold set, then the return value is always true. - /// - /// - /// - /// true if the meets the - /// requirements of this appender. - /// - protected virtual bool IsAsSevereAsThreshold(Level level) - { - return (this.m_threshold == null) || level >= this.m_threshold; - } - - /// - /// Is called when the appender is closed. Derived classes should override - /// this method if resources need to be released. - /// - /// - /// - /// Releases any resources allocated within the appender such as file handles, - /// network connections, etc. - /// - /// - /// It is a programming error to append to a closed appender. - /// - /// - protected virtual void OnClose() - { - // Do nothing by default - } - - /// - /// Subclasses of should implement this method - /// to perform actual logging. - /// - /// The event to append. - /// - /// - /// A subclass must implement this method to perform - /// logging of the . - /// - /// This method will be called by - /// if all the conditions listed for that method are met. - /// - /// - /// To restrict the logging of events in the appender - /// override the method. - /// - /// - protected abstract void Append(LoggingEvent loggingEvent); - - /// - /// Append a bulk array of logging events. - /// - /// the array of logging events. - /// - /// - /// This base class implementation calls the - /// method for each element in the bulk array. - /// - /// - /// A sub class that can better process a bulk array of events should - /// override this method in addition to . - /// - /// - protected virtual void Append(LoggingEvent[] loggingEvents) - { - foreach (LoggingEvent loggingEvent in loggingEvents) - { - this.Append(loggingEvent); - } - } - - /// - /// Called before as a precondition. - /// - /// - /// - /// This method is called by - /// before the call to the abstract method. - /// - /// - /// This method can be overridden in a subclass to extend the checks - /// made before the event is passed to the method. - /// - /// - /// A subclass should ensure that they delegate this call to - /// this base class if it is overridden. - /// - /// - /// true if the call to should proceed. - protected virtual bool PreAppendCheck() - { - if ((this.m_layout == null) && this.RequiresLayout) - { - this.ErrorHandler.Error("AppenderSkeleton: No layout set for the appender named [" + this.m_name + "]."); - return false; - } - - return true; - } - - /// - /// Renders the to a string. - /// - /// The event to render. - /// The event rendered as a string. - /// - /// - /// Helper method to render a to - /// a string. This appender must have a - /// set to render the to - /// a string. - /// - /// If there is exception data in the logging event and - /// the layout does not process the exception, this method - /// will append the exception text to the rendered string. - /// - /// - /// Where possible use the alternative version of this method - /// . - /// That method streams the rendering onto an existing Writer - /// which can give better performance if the caller already has - /// a open and ready for writing. - /// - /// - protected string RenderLoggingEvent(LoggingEvent loggingEvent) - { - // Create the render writer on first use - if (this.m_renderWriter == null) - { - this.m_renderWriter = new ReusableStringWriter(System.Globalization.CultureInfo.InvariantCulture); - } - - lock (this.m_renderWriter) - { - // Reset the writer so we can reuse it - this.m_renderWriter.Reset(c_renderBufferMaxCapacity, c_renderBufferSize); - - this.RenderLoggingEvent(this.m_renderWriter, loggingEvent); - return this.m_renderWriter.ToString(); - } - } - - /// - /// Renders the to a string. - /// - /// The event to render. - /// The TextWriter to write the formatted event to. - /// - /// - /// Helper method to render a to - /// a string. This appender must have a - /// set to render the to - /// a string. - /// - /// If there is exception data in the logging event and - /// the layout does not process the exception, this method - /// will append the exception text to the rendered string. - /// - /// - /// Use this method in preference to - /// where possible. If, however, the caller needs to render the event - /// to a string then does - /// provide an efficient mechanism for doing so. - /// - /// - protected void RenderLoggingEvent(TextWriter writer, LoggingEvent loggingEvent) - { - if (this.m_layout == null) - { - throw new InvalidOperationException("A layout must be set"); - } - - if (this.m_layout.IgnoresException) - { - string exceptionStr = loggingEvent.GetExceptionString(); - if (exceptionStr != null && exceptionStr.Length > 0) - { - // render the event and the exception - this.m_layout.Format(writer, loggingEvent); - writer.WriteLine(exceptionStr); - } - else - { - // there is no exception to render - this.m_layout.Format(writer, loggingEvent); - } - } - else - { - // The layout will render the exception - this.m_layout.Format(writer, loggingEvent); - } - } - - /// - /// Gets a value indicating whether tests if this appender requires a to be set. - /// - /// - /// - /// In the rather exceptional case, where the appender - /// implementation admits a layout but can also work without it, - /// then the appender should return true. - /// - /// - /// This default implementation always returns false. - /// - /// - /// - /// true if the appender requires a layout object, otherwise false. - /// - protected virtual bool RequiresLayout - { - get { return false; } + /// + /// Subclasses of should implement this method + /// to perform actual logging. + /// + /// The event to append. + /// + /// + /// A subclass must implement this method to perform + /// logging of the . + /// + /// This method will be called by + /// if all the conditions listed for that method are met. + /// + /// + /// To restrict the logging of events in the appender + /// override the method. + /// + /// + protected abstract void Append(LoggingEvent loggingEvent); + + /// + /// Append a bulk array of logging events. + /// + /// the array of logging events + /// + /// + /// This base class implementation calls the + /// method for each element in the bulk array. + /// + /// + /// A sub class that can better process a bulk array of events should + /// override this method in addition to . + /// + /// + protected virtual void Append(LoggingEvent[] loggingEvents) + { + foreach(LoggingEvent loggingEvent in loggingEvents) + { + this.Append(loggingEvent); + } } - /// - /// Flushes any buffered log data. - /// - /// - /// This implementation doesn't flush anything and always returns true. - /// - /// True if all logging events were flushed successfully, else false. - public virtual bool Flush(int millisecondsTimeout) - { + /// + /// Called before as a precondition. + /// + /// + /// + /// This method is called by + /// before the call to the abstract method. + /// + /// + /// This method can be overridden in a subclass to extend the checks + /// made before the event is passed to the method. + /// + /// + /// A subclass should ensure that they delegate this call to + /// this base class if it is overridden. + /// + /// + /// true if the call to should proceed. + protected virtual bool PreAppendCheck() + { + if ((this.m_layout == null) && this.RequiresLayout) + { + this.ErrorHandler.Error("AppenderSkeleton: No layout set for the appender named ["+ this.m_name+"]."); + return false; + } + return true; } - /// - /// The layout of this appender. - /// - /// - /// See for more information. - /// - private ILayout m_layout; - - /// - /// The name of this appender. - /// - /// - /// See for more information. - /// - private string m_name; - - /// - /// The level threshold of this appender. - /// - /// - /// - /// There is no level threshold filtering by default. - /// - /// - /// See for more information. - /// - /// - private Level m_threshold; - - /// - /// It is assumed and enforced that errorHandler is never null. - /// - /// - /// - /// It is assumed and enforced that errorHandler is never null. - /// - /// - /// See for more information. - /// - /// - private IErrorHandler m_errorHandler; - - /// - /// The first filter in the filter chain. - /// - /// - /// - /// Set to null initially. - /// - /// - /// See for more information. - /// - /// - private IFilter m_headFilter; - - /// - /// The last filter in the filter chain. - /// - /// - /// See for more information. - /// - private IFilter m_tailFilter; - - /// - /// Flag indicating if this appender is closed. - /// - /// - /// See for more information. - /// - private bool m_closed = false; - - /// - /// The guard prevents an appender from repeatedly calling its own DoAppend method. - /// - private bool m_recursiveGuard = false; - - /// - /// StringWriter used to render events. - /// + /// + /// Renders the to a string. + /// + /// The event to render. + /// The event rendered as a string. + /// + /// + /// Helper method to render a to + /// a string. This appender must have a + /// set to render the to + /// a string. + /// + /// If there is exception data in the logging event and + /// the layout does not process the exception, this method + /// will append the exception text to the rendered string. + /// + /// + /// Where possible use the alternative version of this method + /// . + /// That method streams the rendering onto an existing Writer + /// which can give better performance if the caller already has + /// a open and ready for writing. + /// + /// + protected string RenderLoggingEvent(LoggingEvent loggingEvent) + { + // Create the render writer on first use + if (this.m_renderWriter == null) + { + this.m_renderWriter = new ReusableStringWriter(System.Globalization.CultureInfo.InvariantCulture); + } + + lock (this.m_renderWriter) + { + // Reset the writer so we can reuse it + this.m_renderWriter.Reset(c_renderBufferMaxCapacity, c_renderBufferSize); + + this.RenderLoggingEvent(this.m_renderWriter, loggingEvent); + return this.m_renderWriter.ToString(); + } + } + + /// + /// Renders the to a string. + /// + /// The event to render. + /// The TextWriter to write the formatted event to + /// + /// + /// Helper method to render a to + /// a string. This appender must have a + /// set to render the to + /// a string. + /// + /// If there is exception data in the logging event and + /// the layout does not process the exception, this method + /// will append the exception text to the rendered string. + /// + /// + /// Use this method in preference to + /// where possible. If, however, the caller needs to render the event + /// to a string then does + /// provide an efficient mechanism for doing so. + /// + /// + protected void RenderLoggingEvent(TextWriter writer, LoggingEvent loggingEvent) + { + if (this.m_layout == null) + { + throw new InvalidOperationException("A layout must be set"); + } + + if (this.m_layout.IgnoresException) + { + string exceptionStr = loggingEvent.GetExceptionString(); + if (exceptionStr != null && exceptionStr.Length > 0) + { + // render the event and the exception + this.m_layout.Format(writer, loggingEvent); + writer.WriteLine(exceptionStr); + } + else + { + // there is no exception to render + this.m_layout.Format(writer, loggingEvent); + } + } + else + { + // The layout will render the exception + this.m_layout.Format(writer, loggingEvent); + } + } + + /// + /// Tests if this appender requires a to be set. + /// + /// + /// + /// In the rather exceptional case, where the appender + /// implementation admits a layout but can also work without it, + /// then the appender should return true. + /// + /// + /// This default implementation always returns false. + /// + /// + /// + /// true if the appender requires a layout object, otherwise false. + /// + protected virtual bool RequiresLayout + { + get { return false; } + } + + /// + /// Flushes any buffered log data. + /// + /// + /// This implementation doesn't flush anything and always returns true + /// + /// True if all logging events were flushed successfully, else false. + public virtual bool Flush(int millisecondsTimeout) + { + return true; + } + + /// + /// The layout of this appender. + /// + /// + /// See for more information. + /// + private ILayout m_layout; + + /// + /// The name of this appender. + /// + /// + /// See for more information. + /// + private string m_name; + + /// + /// The level threshold of this appender. + /// + /// + /// + /// There is no level threshold filtering by default. + /// + /// + /// See for more information. + /// + /// + private Level m_threshold; + + /// + /// It is assumed and enforced that errorHandler is never null. + /// + /// + /// + /// It is assumed and enforced that errorHandler is never null. + /// + /// + /// See for more information. + /// + /// + private IErrorHandler m_errorHandler; + + /// + /// The first filter in the filter chain. + /// + /// + /// + /// Set to null initially. + /// + /// + /// See for more information. + /// + /// + private IFilter m_headFilter; + + /// + /// The last filter in the filter chain. + /// + /// + /// See for more information. + /// + private IFilter m_tailFilter; + + /// + /// Flag indicating if this appender is closed. + /// + /// + /// See for more information. + /// + private bool m_closed = false; + + /// + /// The guard prevents an appender from repeatedly calling its own DoAppend method + /// + private bool m_recursiveGuard = false; + + /// + /// StringWriter used to render events + /// private ReusableStringWriter m_renderWriter = null; - /// - /// Initial buffer size. - /// - private const int c_renderBufferSize = 256; - - /// - /// Maximum buffer size before it is recycled. - /// + /// + /// Initial buffer size + /// + private const int c_renderBufferSize = 256; + + /// + /// Maximum buffer size before it is recycled + /// private const int c_renderBufferMaxCapacity = 1024; - /// - /// The fully qualified type of the AppenderSkeleton class. - /// - /// - /// Used by the internal logger to record the Type of the - /// log message. - /// + /// + /// The fully qualified type of the AppenderSkeleton class. + /// + /// + /// Used by the internal logger to record the Type of the + /// log message. + /// private static readonly Type declaringType = typeof(AppenderSkeleton); - } -} + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/AspNetTraceAppender.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/AspNetTraceAppender.cs index 580c2aeda71..105f91a91bc 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/AspNetTraceAppender.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/AspNetTraceAppender.cs @@ -1,141 +1,141 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -// .NET Compact Framework 1.0 has no support for ASP.NET -// SSCLI 1.0 has no support for ASP.NET -#if !NETCF && !SSCLI && !CLIENT_PROFILE - -using System.Web; +#if NET_2_0 +// SSCLI 1.0 has no support for ASP.NET +#if !NETCF && !SSCLI && !CLIENT_PROFILE -using log4net.Core; -using log4net.Layout; - -namespace log4net.Appender -{ - /// - /// - /// Appends log events to the ASP.NET system. - /// - /// - /// - /// - /// Diagnostic information and tracing messages that you specify are appended to the output - /// of the page that is sent to the requesting browser. Optionally, you can view this information - /// from a separate trace viewer (Trace.axd) that displays trace information for every page in a - /// given application. - /// - /// - /// Trace statements are processed and displayed only when tracing is enabled. You can control - /// whether tracing is displayed to a page, to the trace viewer, or both. - /// - /// - /// The logging event is passed to the or - /// method depending on the level of the logging event. - /// The event's logger name is the default value for the category parameter of the Write/Warn method. - /// - /// - /// Nicko Cadell. - /// Gert Driesen. - /// Ron Grabowski. - public class AspNetTraceAppender : AppenderSkeleton +using System.Web; + +using log4net.Layout; +using log4net.Core; + +namespace log4net.Appender +{ + /// + /// + /// Appends log events to the ASP.NET system. + /// + /// + /// + /// + /// Diagnostic information and tracing messages that you specify are appended to the output + /// of the page that is sent to the requesting browser. Optionally, you can view this information + /// from a separate trace viewer (Trace.axd) that displays trace information for every page in a + /// given application. + /// + /// + /// Trace statements are processed and displayed only when tracing is enabled. You can control + /// whether tracing is displayed to a page, to the trace viewer, or both. + /// + /// + /// The logging event is passed to the or + /// method depending on the level of the logging event. + /// The event's logger name is the default value for the category parameter of the Write/Warn method. + /// + /// + /// Nicko Cadell + /// Gert Driesen + /// Ron Grabowski + public class AspNetTraceAppender : AppenderSkeleton { - /// - /// Initializes a new instance of the class. - /// - /// - /// - /// Default constructor. - /// - /// - public AspNetTraceAppender() - { + /// + /// Initializes a new instance of the class. + /// + /// + /// + /// Default constructor. + /// + /// + public AspNetTraceAppender() + { } - /// - /// Write the logging event to the ASP.NET trace. - /// - /// the event to log. - /// - /// - /// Write the logging event to the ASP.NET trace - /// HttpContext.Current.Trace - /// (). - /// - /// - protected override void Append(LoggingEvent loggingEvent) - { - // check if log4net is running in the context of an ASP.NET application - if (HttpContext.Current != null) - { - // check if tracing is enabled for the current context - if (HttpContext.Current.Trace.IsEnabled) - { - if (loggingEvent.Level >= Level.Warn) - { - HttpContext.Current.Trace.Warn(this.m_category.Format(loggingEvent), this.RenderLoggingEvent(loggingEvent)); - } - else - { - HttpContext.Current.Trace.Write(this.m_category.Format(loggingEvent), this.RenderLoggingEvent(loggingEvent)); - } - } - } - } - - /// - /// Gets a value indicating whether this appender requires a to be set. - /// - /// true. - /// - /// - /// This appender requires a to be set. - /// - /// - protected override bool RequiresLayout - { - get { return true; } + /// + /// Write the logging event to the ASP.NET trace + /// + /// the event to log + /// + /// + /// Write the logging event to the ASP.NET trace + /// HttpContext.Current.Trace + /// (). + /// + /// + protected override void Append(LoggingEvent loggingEvent) + { + // check if log4net is running in the context of an ASP.NET application + if (HttpContext.Current != null) + { + // check if tracing is enabled for the current context + if (HttpContext.Current.Trace.IsEnabled) + { + if (loggingEvent.Level >= Level.Warn) + { + HttpContext.Current.Trace.Warn(this.m_category.Format(loggingEvent), this.RenderLoggingEvent(loggingEvent)); + } + else + { + HttpContext.Current.Trace.Write(this.m_category.Format(loggingEvent), this.RenderLoggingEvent(loggingEvent)); + } + } + } } - /// - /// Gets or sets the category parameter sent to the Trace method. - /// - /// - /// - /// Defaults to %logger which will use the logger name of the current - /// as the category parameter. - /// - /// - /// - /// - public PatternLayout Category - { - get { return this.m_category; } - set { this.m_category = value; } + /// + /// This appender requires a to be set. + /// + /// true + /// + /// + /// This appender requires a to be set. + /// + /// + protected override bool RequiresLayout + { + get { return true; } } - /// - /// Defaults to %logger. - /// + /// + /// The category parameter sent to the Trace method. + /// + /// + /// + /// Defaults to %logger which will use the logger name of the current + /// as the category parameter. + /// + /// + /// + /// + public PatternLayout Category + { + get { return this.m_category; } + set { this.m_category = value; } + } + + /// + /// Defaults to %logger + /// private PatternLayout m_category = new PatternLayout("%logger"); - } -} - -#endif // !NETCF && !SSCLI + } +} + +#endif // !NETCF && !SSCLI +#endif // NET_2_0 diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/BufferingAppenderSkeleton.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/BufferingAppenderSkeleton.cs index 76afac1f929..1b05d19242a 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/BufferingAppenderSkeleton.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/BufferingAppenderSkeleton.cs @@ -1,630 +1,628 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.Appender -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; - using System.Collections; - - using log4net.Core; - using log4net.Util; - - /// - /// Abstract base class implementation of that - /// buffers events in a fixed size buffer. - /// - /// - /// - /// This base class should be used by appenders that need to buffer a - /// number of events before logging them. For example the - /// buffers events and then submits the entire contents of the buffer to - /// the underlying database in one go. - /// - /// - /// Subclasses should override the - /// method to deliver the buffered events. - /// - /// The BufferingAppenderSkeleton maintains a fixed size cyclic - /// buffer of events. The size of the buffer is set using - /// the property. - /// - /// A is used to inspect - /// each event as it arrives in the appender. If the - /// triggers, then the current buffer is sent immediately - /// (see ). Otherwise the event - /// is stored in the buffer. For example, an evaluator can be used to - /// deliver the events immediately when an ERROR event arrives. - /// - /// - /// The buffering appender can be configured in a mode. - /// By default the appender is NOT lossy. When the buffer is full all - /// the buffered events are sent with . - /// If the property is set to true then the - /// buffer will not be sent when it is full, and new events arriving - /// in the appender will overwrite the oldest event in the buffer. - /// In lossy mode the buffer will only be sent when the - /// triggers. This can be useful behavior when you need to know about - /// ERROR events but not about events with a lower level, configure an - /// evaluator that will trigger when an ERROR event arrives, the whole - /// buffer will be sent which gives a history of events leading up to - /// the ERROR event. - /// - /// - /// Nicko Cadell. - /// Gert Driesen. - public abstract class BufferingAppenderSkeleton : AppenderSkeleton +using System; +using System.Collections; + +using log4net.Util; +using log4net.Core; + +namespace log4net.Appender +{ + /// + /// Abstract base class implementation of that + /// buffers events in a fixed size buffer. + /// + /// + /// + /// This base class should be used by appenders that need to buffer a + /// number of events before logging them. + /// For example the + /// buffers events and then submits the entire contents of the buffer to + /// the underlying database in one go. + /// + /// + /// Subclasses should override the + /// method to deliver the buffered events. + /// + /// The BufferingAppenderSkeleton maintains a fixed size cyclic + /// buffer of events. The size of the buffer is set using + /// the property. + /// + /// A is used to inspect + /// each event as it arrives in the appender. If the + /// triggers, then the current buffer is sent immediately + /// (see ). Otherwise the event + /// is stored in the buffer. For example, an evaluator can be used to + /// deliver the events immediately when an ERROR event arrives. + /// + /// + /// The buffering appender can be configured in a mode. + /// By default the appender is NOT lossy. When the buffer is full all + /// the buffered events are sent with . + /// If the property is set to true then the + /// buffer will not be sent when it is full, and new events arriving + /// in the appender will overwrite the oldest event in the buffer. + /// In lossy mode the buffer will only be sent when the + /// triggers. This can be useful behavior when you need to know about + /// ERROR events but not about events with a lower level, configure an + /// evaluator that will trigger when an ERROR event arrives, the whole + /// buffer will be sent which gives a history of events leading up to + /// the ERROR event. + /// + /// + /// Nicko Cadell + /// Gert Driesen + public abstract class BufferingAppenderSkeleton : AppenderSkeleton { - /// - /// Initializes a new instance of the class. - /// - /// - /// - /// Protected default constructor to allow subclassing. - /// - /// - protected BufferingAppenderSkeleton() - : this(true) - { - } - - /// - /// Initializes a new instance of the class. - /// - /// the events passed through this appender must be - /// fixed by the time that they arrive in the derived class' SendBuffer method. - /// - /// - /// Protected constructor to allow subclassing. - /// - /// - /// The should be set if the subclass - /// expects the events delivered to be fixed even if the - /// is set to zero, i.e. when no buffering occurs. - /// - /// - protected BufferingAppenderSkeleton(bool eventMustBeFixed) - : base() - { - this.m_eventMustBeFixed = eventMustBeFixed; + /// + /// Initializes a new instance of the class. + /// + /// + /// + /// Protected default constructor to allow subclassing. + /// + /// + protected BufferingAppenderSkeleton() : this(true) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// the events passed through this appender must be + /// fixed by the time that they arrive in the derived class' SendBuffer method. + /// + /// + /// Protected constructor to allow subclassing. + /// + /// + /// The should be set if the subclass + /// expects the events delivered to be fixed even if the + /// is set to zero, i.e. when no buffering occurs. + /// + /// + protected BufferingAppenderSkeleton(bool eventMustBeFixed) : base() + { + this.m_eventMustBeFixed = eventMustBeFixed; + } + + /// + /// Gets or sets a value that indicates whether the appender is lossy. + /// + /// + /// true if the appender is lossy, otherwise false. The default is false. + /// + /// + /// + /// This appender uses a buffer to store logging events before + /// delivering them. A triggering event causes the whole buffer + /// to be send to the remote sink. If the buffer overruns before + /// a triggering event then logging events could be lost. Set + /// to false to prevent logging events + /// from being lost. + /// + /// If is set to true then an + /// must be specified. + /// + public bool Lossy + { + get { return this.m_lossy; } + set { this.m_lossy = value; } + } + + /// + /// Gets or sets the size of the cyclic buffer used to hold the + /// logging events. + /// + /// + /// The size of the cyclic buffer used to hold the logging events. + /// + /// + /// + /// The option takes a positive integer + /// representing the maximum number of logging events to collect in + /// a cyclic buffer. When the is reached, + /// oldest events are deleted as new events are added to the + /// buffer. By default the size of the cyclic buffer is 512 events. + /// + /// + /// If the is set to a value less than + /// or equal to 1 then no buffering will occur. The logging event + /// will be delivered synchronously (depending on the + /// and properties). Otherwise the event will + /// be buffered. + /// + /// + public int BufferSize + { + get { return this.m_bufferSize; } + set { this.m_bufferSize = value; } + } + + /// + /// Gets or sets the that causes the + /// buffer to be sent immediately. + /// + /// + /// The that causes the buffer to be + /// sent immediately. + /// + /// + /// + /// The evaluator will be called for each event that is appended to this + /// appender. If the evaluator triggers then the current buffer will + /// immediately be sent (see ). + /// + /// If is set to true then an + /// must be specified. + /// + public ITriggeringEventEvaluator Evaluator + { + get { return this.m_evaluator; } + set { this.m_evaluator = value; } } - /// - /// Gets or sets a value indicating whether gets or sets a value that indicates whether the appender is lossy. - /// - /// - /// true if the appender is lossy, otherwise false. The default is false. - /// - /// - /// - /// This appender uses a buffer to store logging events before - /// delivering them. A triggering event causes the whole buffer - /// to be send to the remote sink. If the buffer overruns before - /// a triggering event then logging events could be lost. Set - /// to false to prevent logging events - /// from being lost. - /// - /// If is set to true then an - /// must be specified. - /// - public bool Lossy - { - get { return this.m_lossy; } - set { this.m_lossy = value; } - } - - /// - /// Gets or sets the size of the cyclic buffer used to hold the - /// logging events. - /// - /// - /// The size of the cyclic buffer used to hold the logging events. - /// - /// - /// - /// The option takes a positive integer - /// representing the maximum number of logging events to collect in - /// a cyclic buffer. When the is reached, - /// oldest events are deleted as new events are added to the - /// buffer. By default the size of the cyclic buffer is 512 events. - /// - /// - /// If the is set to a value less than - /// or equal to 1 then no buffering will occur. The logging event - /// will be delivered synchronously (depending on the - /// and properties). Otherwise the event will - /// be buffered. - /// - /// - public int BufferSize - { - get { return this.m_bufferSize; } - set { this.m_bufferSize = value; } - } - - /// - /// Gets or sets the that causes the - /// buffer to be sent immediately. - /// - /// - /// The that causes the buffer to be - /// sent immediately. - /// - /// - /// - /// The evaluator will be called for each event that is appended to this - /// appender. If the evaluator triggers then the current buffer will - /// immediately be sent (see ). - /// - /// If is set to true then an - /// must be specified. - /// - public ITriggeringEventEvaluator Evaluator - { - get { return this.m_evaluator; } - set { this.m_evaluator = value; } - } - - /// - /// Gets or sets the value of the to use. - /// - /// - /// The value of the to use. - /// - /// - /// - /// The evaluator will be called for each event that is discarded from this - /// appender. If the evaluator triggers then the current buffer will immediately - /// be sent (see ). - /// - /// - public ITriggeringEventEvaluator LossyEvaluator - { - get { return this.m_lossyEvaluator; } - set { this.m_lossyEvaluator = value; } - } - - /// - /// Gets or sets a value indicating whether gets or sets a value indicating if only part of the logging event data - /// should be fixed. - /// - /// - /// true if the appender should only fix part of the logging event - /// data, otherwise false. The default is false. - /// - /// - /// - /// Setting this property to true will cause only part of the - /// event data to be fixed and serialized. This will improve performance. - /// - /// - /// See for more information. - /// - /// - [Obsolete("Use Fix property. Scheduled removal in v10.0.0.")] - public virtual bool OnlyFixPartialEventData - { - get { return this.Fix == FixFlags.Partial; } - - set - { - if (value) - { - this.Fix = FixFlags.Partial; - } - else - { - this.Fix = FixFlags.All; - } - } - } - - /// - /// Gets or sets a the fields that will be fixed in the event. - /// - /// - /// The event fields that will be fixed before the event is buffered. - /// - /// - /// - /// The logging event needs to have certain thread specific values - /// captured before it can be buffered. See - /// for details. - /// - /// - /// - public virtual FixFlags Fix - { - get { return this.m_fixFlags; } - set { this.m_fixFlags = value; } + /// + /// Gets or sets the value of the to use. + /// + /// + /// The value of the to use. + /// + /// + /// + /// The evaluator will be called for each event that is discarded from this + /// appender. If the evaluator triggers then the current buffer will immediately + /// be sent (see ). + /// + /// + public ITriggeringEventEvaluator LossyEvaluator + { + get { return this.m_lossyEvaluator; } + set { this.m_lossyEvaluator = value; } } - /// - /// Flushes any buffered log data. - /// - /// The maximum time to wait for logging events to be flushed. - /// True if all logging events were flushed successfully, else false. - public override bool Flush(int millisecondsTimeout) - { - this.Flush(); - return true; - } - - /// - /// Flush the currently buffered events. - /// - /// - /// - /// Flushes any events that have been buffered. - /// - /// - /// If the appender is buffering in mode then the contents - /// of the buffer will NOT be flushed to the appender. - /// - /// - public virtual void Flush() - { - this.Flush(false); - } - - /// - /// Flush the currently buffered events. - /// - /// set to true to flush the buffer of lossy events. - /// - /// - /// Flushes events that have been buffered. If is - /// false then events will only be flushed if this buffer is non-lossy mode. - /// - /// - /// If the appender is buffering in mode then the contents - /// of the buffer will only be flushed if is true. - /// In this case the contents of the buffer will be tested against the - /// and if triggering will be output. All other buffered - /// events will be discarded. - /// - /// - /// If is true then the buffer will always - /// be emptied by calling this method. - /// - /// - public virtual void Flush(bool flushLossyBuffer) - { - // This method will be called outside of the AppenderSkeleton DoAppend() method - // therefore it needs to be protected by its own lock. This will block any - // Appends while the buffer is flushed. - lock (this) - { - if (this.m_cb != null && this.m_cb.Length > 0) - { - if (this.m_lossy) - { - // If we are allowed to eagerly flush from the lossy buffer - if (flushLossyBuffer) - { - if (this.m_lossyEvaluator != null) - { - // Test the contents of the buffer against the lossy evaluator - LoggingEvent[] bufferedEvents = this.m_cb.PopAll(); - ArrayList filteredEvents = new ArrayList(bufferedEvents.Length); - - foreach (LoggingEvent loggingEvent in bufferedEvents) - { - if (this.m_lossyEvaluator.IsTriggeringEvent(loggingEvent)) - { - filteredEvents.Add(loggingEvent); - } - } - - // Send the events that meet the lossy evaluator criteria - if (filteredEvents.Count > 0) - { - this.SendBuffer((LoggingEvent[])filteredEvents.ToArray(typeof(LoggingEvent))); - } - } - else - { - // No lossy evaluator, all buffered events are discarded - this.m_cb.Clear(); - } - } - } - else - { - // Not lossy, send whole buffer - this.SendFromBuffer(null, this.m_cb); - } - } - } + /// + /// Gets or sets a value indicating if only part of the logging event data + /// should be fixed. + /// + /// + /// true if the appender should only fix part of the logging event + /// data, otherwise false. The default is false. + /// + /// + /// + /// Setting this property to true will cause only part of the + /// event data to be fixed and serialized. This will improve performance. + /// + /// + /// See for more information. + /// + /// + [Obsolete("Use Fix property")] + public virtual bool OnlyFixPartialEventData + { + get { return (this.Fix == FixFlags.Partial); } + set + { + if (value) + { + this.Fix = FixFlags.Partial; + } + else + { + this.Fix = FixFlags.All; + } + } } - /// - /// Initialize the appender based on the options set. - /// - /// - /// - /// This is part of the delayed object - /// activation scheme. The method must - /// be called on this object after the configuration properties have - /// been set. Until is called this - /// object is in an undefined state and must not be used. - /// - /// - /// If any of the configuration properties are modified then - /// must be called again. - /// - /// - public override void ActivateOptions() - { - base.ActivateOptions(); - - // If the appender is in Lossy mode then we will - // only send the buffer when the Evaluator triggers - // therefore check we have an evaluator. - if (this.m_lossy && this.m_evaluator == null) - { - this.ErrorHandler.Error("Appender [" + this.Name + "] is Lossy but has no Evaluator. The buffer will never be sent!"); - } - - if (this.m_bufferSize > 1) - { - this.m_cb = new CyclicBuffer(this.m_bufferSize); - } - else - { - this.m_cb = null; - } + /// + /// Gets or sets a the fields that will be fixed in the event + /// + /// + /// The event fields that will be fixed before the event is buffered + /// + /// + /// + /// The logging event needs to have certain thread specific values + /// captured before it can be buffered. See + /// for details. + /// + /// + /// + public virtual FixFlags Fix + { + get { return this.m_fixFlags; } + set { this.m_fixFlags = value; } } - /// - /// Close this appender instance. - /// - /// - /// - /// Close this appender instance. If this appender is marked - /// as not then the remaining events in - /// the buffer must be sent when the appender is closed. - /// - /// - protected override void OnClose() - { - // Flush the buffer on close - this.Flush(true); - } - - /// - /// This method is called by the method. - /// - /// the event to log. - /// - /// - /// Stores the in the cyclic buffer. - /// - /// - /// The buffer will be sent (i.e. passed to the - /// method) if one of the following conditions is met: - /// - /// - /// - /// The cyclic buffer is full and this appender is - /// marked as not lossy (see ) - /// - /// - /// An is set and - /// it is triggered for the - /// specified. - /// - /// - /// - /// Before the event is stored in the buffer it is fixed - /// (see ) to ensure that - /// any data referenced by the event will be valid when the buffer - /// is processed. - /// - /// - protected override void Append(LoggingEvent loggingEvent) - { - // If the buffer size is set to 1 or less then the buffer will be - // sent immediately because there is not enough space in the buffer - // to buffer up more than 1 event. Therefore as a special case - // we don't use the buffer at all. - if (this.m_cb == null || this.m_bufferSize <= 1) - { - // Only send the event if we are in non lossy mode or the event is a triggering event - if ((!this.m_lossy) || - (this.m_evaluator != null && this.m_evaluator.IsTriggeringEvent(loggingEvent)) || - (this.m_lossyEvaluator != null && this.m_lossyEvaluator.IsTriggeringEvent(loggingEvent))) - { - if (this.m_eventMustBeFixed) - { - // Derive class expects fixed events - loggingEvent.Fix = this.Fix; - } - - // Not buffering events, send immediately - this.SendBuffer(new LoggingEvent[] { loggingEvent }); - } - } - else - { - // Because we are caching the LoggingEvent beyond the - // lifetime of the Append() method we must fix any - // volatile data in the event. - loggingEvent.Fix = this.Fix; - - // Add to the buffer, returns the event discarded from the buffer if there is no space remaining after the append - LoggingEvent discardedLoggingEvent = this.m_cb.Append(loggingEvent); - - if (discardedLoggingEvent != null) - { - // Buffer is full and has had to discard an event - if (!this.m_lossy) - { - // Not lossy, must send all events - this.SendFromBuffer(discardedLoggingEvent, this.m_cb); - } - else - { - // Check if the discarded event should not be logged - if (this.m_lossyEvaluator == null || !this.m_lossyEvaluator.IsTriggeringEvent(discardedLoggingEvent)) - { - // Clear the discarded event as we should not forward it - discardedLoggingEvent = null; - } - - // Check if the event should trigger the whole buffer to be sent - if (this.m_evaluator != null && this.m_evaluator.IsTriggeringEvent(loggingEvent)) - { - this.SendFromBuffer(discardedLoggingEvent, this.m_cb); - } - else if (discardedLoggingEvent != null) - { - // Just send the discarded event - this.SendBuffer(new LoggingEvent[] { discardedLoggingEvent }); - } - } - } - else - { - // Buffer is not yet full - - // Check if the event should trigger the whole buffer to be sent - if (this.m_evaluator != null && this.m_evaluator.IsTriggeringEvent(loggingEvent)) - { - this.SendFromBuffer(null, this.m_cb); - } - } - } + /// + /// Flushes any buffered log data. + /// + /// The maximum time to wait for logging events to be flushed. + /// True if all logging events were flushed successfully, else false. + public override bool Flush(int millisecondsTimeout) + { + this.Flush(); + return true; } - /// - /// Sends the contents of the buffer. - /// - /// The first logging event. - /// The buffer containing the events that need to be send. - /// - /// - /// The subclass must override . - /// - /// - protected virtual void SendFromBuffer(LoggingEvent firstLoggingEvent, CyclicBuffer buffer) - { - LoggingEvent[] bufferEvents = buffer.PopAll(); - - if (firstLoggingEvent == null) - { - this.SendBuffer(bufferEvents); - } - else if (bufferEvents.Length == 0) - { - this.SendBuffer(new LoggingEvent[] { firstLoggingEvent }); - } - else - { - // Create new array with the firstLoggingEvent at the head - LoggingEvent[] events = new LoggingEvent[bufferEvents.Length + 1]; - Array.Copy(bufferEvents, 0, events, 1, bufferEvents.Length); - events[0] = firstLoggingEvent; - - this.SendBuffer(events); - } + /// + /// Flush the currently buffered events + /// + /// + /// + /// Flushes any events that have been buffered. + /// + /// + /// If the appender is buffering in mode then the contents + /// of the buffer will NOT be flushed to the appender. + /// + /// + public virtual void Flush() + { + this.Flush(false); } - /// - /// Sends the events. - /// - /// The events that need to be send. - /// - /// - /// The subclass must override this method to process the buffered events. - /// - /// + /// + /// Flush the currently buffered events + /// + /// set to true to flush the buffer of lossy events + /// + /// + /// Flushes events that have been buffered. If is + /// false then events will only be flushed if this buffer is non-lossy mode. + /// + /// + /// If the appender is buffering in mode then the contents + /// of the buffer will only be flushed if is true. + /// In this case the contents of the buffer will be tested against the + /// and if triggering will be output. All other buffered + /// events will be discarded. + /// + /// + /// If is true then the buffer will always + /// be emptied by calling this method. + /// + /// + public virtual void Flush(bool flushLossyBuffer) + { + // This method will be called outside of the AppenderSkeleton DoAppend() method + // therefore it needs to be protected by its own lock. This will block any + // Appends while the buffer is flushed. + lock(this) + { + if (this.m_cb != null && this.m_cb.Length > 0) + { + if (this.m_lossy) + { + // If we are allowed to eagerly flush from the lossy buffer + if (flushLossyBuffer) + { + if (this.m_lossyEvaluator != null) + { + // Test the contents of the buffer against the lossy evaluator + LoggingEvent[] bufferedEvents = this.m_cb.PopAll(); + ArrayList filteredEvents = new ArrayList(bufferedEvents.Length); + + foreach(LoggingEvent loggingEvent in bufferedEvents) + { + if (this.m_lossyEvaluator.IsTriggeringEvent(loggingEvent)) + { + filteredEvents.Add(loggingEvent); + } + } + + // Send the events that meet the lossy evaluator criteria + if (filteredEvents.Count > 0) + { + this.SendBuffer((LoggingEvent[])filteredEvents.ToArray(typeof(LoggingEvent))); + } + } + else + { + // No lossy evaluator, all buffered events are discarded + this.m_cb.Clear(); + } + } + } + else + { + // Not lossy, send whole buffer + this.SendFromBuffer(null, this.m_cb); + } + } + } + } + + /// + /// Initialize the appender based on the options set + /// + /// + /// + /// This is part of the delayed object + /// activation scheme. The method must + /// be called on this object after the configuration properties have + /// been set. Until is called this + /// object is in an undefined state and must not be used. + /// + /// + /// If any of the configuration properties are modified then + /// must be called again. + /// + /// + public override void ActivateOptions() + { + base.ActivateOptions(); + + // If the appender is in Lossy mode then we will + // only send the buffer when the Evaluator triggers + // therefore check we have an evaluator. + if (this.m_lossy && this.m_evaluator == null) + { + this.ErrorHandler.Error("Appender [" + this.Name + "] is Lossy but has no Evaluator. The buffer will never be sent!"); + } + + if (this.m_bufferSize > 1) + { + this.m_cb = new CyclicBuffer(this.m_bufferSize); + } + else + { + this.m_cb = null; + } + } + + /// + /// Close this appender instance. + /// + /// + /// + /// Close this appender instance. If this appender is marked + /// as not then the remaining events in + /// the buffer must be sent when the appender is closed. + /// + /// + protected override void OnClose() + { + // Flush the buffer on close + this.Flush(true); + } + + /// + /// This method is called by the method. + /// + /// the event to log + /// + /// + /// Stores the in the cyclic buffer. + /// + /// + /// The buffer will be sent (i.e. passed to the + /// method) if one of the following conditions is met: + /// + /// + /// + /// The cyclic buffer is full and this appender is + /// marked as not lossy (see ) + /// + /// + /// An is set and + /// it is triggered for the + /// specified. + /// + /// + /// + /// Before the event is stored in the buffer it is fixed + /// (see ) to ensure that + /// any data referenced by the event will be valid when the buffer + /// is processed. + /// + /// + protected override void Append(LoggingEvent loggingEvent) + { + // If the buffer size is set to 1 or less then the buffer will be + // sent immediately because there is not enough space in the buffer + // to buffer up more than 1 event. Therefore as a special case + // we don't use the buffer at all. + if (this.m_cb == null || this.m_bufferSize <= 1) + { + // Only send the event if we are in non lossy mode or the event is a triggering event + if ((!this.m_lossy) || + (this.m_evaluator != null && this.m_evaluator.IsTriggeringEvent(loggingEvent)) || + (this.m_lossyEvaluator != null && this.m_lossyEvaluator.IsTriggeringEvent(loggingEvent))) + { + if (this.m_eventMustBeFixed) + { + // Derive class expects fixed events + loggingEvent.Fix = this.Fix; + } + + // Not buffering events, send immediately + this.SendBuffer(new LoggingEvent[] { loggingEvent }); + } + } + else + { + // Because we are caching the LoggingEvent beyond the + // lifetime of the Append() method we must fix any + // volatile data in the event. + loggingEvent.Fix = this.Fix; + + // Add to the buffer, returns the event discarded from the buffer if there is no space remaining after the append + LoggingEvent discardedLoggingEvent = this.m_cb.Append(loggingEvent); + + if (discardedLoggingEvent != null) + { + // Buffer is full and has had to discard an event + if (!this.m_lossy) + { + // Not lossy, must send all events + this.SendFromBuffer(discardedLoggingEvent, this.m_cb); + } + else + { + // Check if the discarded event should not be logged + if (this.m_lossyEvaluator == null || !this.m_lossyEvaluator.IsTriggeringEvent(discardedLoggingEvent)) + { + // Clear the discarded event as we should not forward it + discardedLoggingEvent = null; + } + + // Check if the event should trigger the whole buffer to be sent + if (this.m_evaluator != null && this.m_evaluator.IsTriggeringEvent(loggingEvent)) + { + this.SendFromBuffer(discardedLoggingEvent, this.m_cb); + } + else if (discardedLoggingEvent != null) + { + // Just send the discarded event + this.SendBuffer(new LoggingEvent[] { discardedLoggingEvent }); + } + } + } + else + { + // Buffer is not yet full + + // Check if the event should trigger the whole buffer to be sent + if (this.m_evaluator != null && this.m_evaluator.IsTriggeringEvent(loggingEvent)) + { + this.SendFromBuffer(null, this.m_cb); + } + } + } + } + + /// + /// Sends the contents of the buffer. + /// + /// The first logging event. + /// The buffer containing the events that need to be send. + /// + /// + /// The subclass must override . + /// + /// + protected virtual void SendFromBuffer(LoggingEvent firstLoggingEvent, CyclicBuffer buffer) + { + LoggingEvent[] bufferEvents = buffer.PopAll(); + + if (firstLoggingEvent == null) + { + this.SendBuffer(bufferEvents); + } + else if (bufferEvents.Length == 0) + { + this.SendBuffer(new LoggingEvent[] { firstLoggingEvent }); + } + else + { + // Create new array with the firstLoggingEvent at the head + LoggingEvent[] events = new LoggingEvent[bufferEvents.Length + 1]; + Array.Copy(bufferEvents, 0, events, 1, bufferEvents.Length); + events[0] = firstLoggingEvent; + + this.SendBuffer(events); + } + } + + /// + /// Sends the events. + /// + /// The events that need to be send. + /// + /// + /// The subclass must override this method to process the buffered events. + /// + /// protected abstract void SendBuffer(LoggingEvent[] events); - /// - /// The default buffer size. - /// - /// - /// The default size of the cyclic buffer used to store events. - /// This is set to 512 by default. - /// + /// + /// The default buffer size. + /// + /// + /// The default size of the cyclic buffer used to store events. + /// This is set to 512 by default. + /// private const int DEFAULT_BUFFER_SIZE = 512; - /// - /// The size of the cyclic buffer used to hold the logging events. - /// - /// - /// Set to by default. - /// - private int m_bufferSize = DEFAULT_BUFFER_SIZE; - - /// - /// The cyclic buffer used to store the logging events. - /// - private CyclicBuffer m_cb; - - /// - /// The triggering event evaluator that causes the buffer to be sent immediately. - /// - /// - /// The object that is used to determine if an event causes the entire - /// buffer to be sent immediately. This field can be null, which - /// indicates that event triggering is not to be done. The evaluator - /// can be set using the property. If this appender - /// has the ( property) set to - /// true then an must be set. - /// - private ITriggeringEventEvaluator m_evaluator; - - /// - /// Indicates if the appender should overwrite events in the cyclic buffer - /// when it becomes full, or if the buffer should be flushed when the - /// buffer is full. - /// - /// - /// If this field is set to true then an must - /// be set. - /// - private bool m_lossy = false; - - /// - /// The triggering event evaluator filters discarded events. - /// - /// - /// The object that is used to determine if an event that is discarded should - /// really be discarded or if it should be sent to the appenders. - /// This field can be null, which indicates that all discarded events will - /// be discarded. - /// - private ITriggeringEventEvaluator m_lossyEvaluator; - - /// - /// Value indicating which fields in the event should be fixed. - /// - /// - /// By default all fields are fixed. - /// - private FixFlags m_fixFlags = FixFlags.All; - - /// - /// The events delivered to the subclass must be fixed. - /// + /// + /// The size of the cyclic buffer used to hold the logging events. + /// + /// + /// Set to by default. + /// + private int m_bufferSize = DEFAULT_BUFFER_SIZE; + + /// + /// The cyclic buffer used to store the logging events. + /// + private CyclicBuffer m_cb; + + /// + /// The triggering event evaluator that causes the buffer to be sent immediately. + /// + /// + /// The object that is used to determine if an event causes the entire + /// buffer to be sent immediately. This field can be null, which + /// indicates that event triggering is not to be done. The evaluator + /// can be set using the property. If this appender + /// has the ( property) set to + /// true then an must be set. + /// + private ITriggeringEventEvaluator m_evaluator; + + /// + /// Indicates if the appender should overwrite events in the cyclic buffer + /// when it becomes full, or if the buffer should be flushed when the + /// buffer is full. + /// + /// + /// If this field is set to true then an must + /// be set. + /// + private bool m_lossy = false; + + /// + /// The triggering event evaluator filters discarded events. + /// + /// + /// The object that is used to determine if an event that is discarded should + /// really be discarded or if it should be sent to the appenders. + /// This field can be null, which indicates that all discarded events will + /// be discarded. + /// + private ITriggeringEventEvaluator m_lossyEvaluator; + + /// + /// Value indicating which fields in the event should be fixed + /// + /// + /// By default all fields are fixed + /// + private FixFlags m_fixFlags = FixFlags.All; + + /// + /// The events delivered to the subclass must be fixed. + /// private readonly bool m_eventMustBeFixed; - } -} + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/BufferingForwardingAppender.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/BufferingForwardingAppender.cs index bb36b55e45b..2839b687cdc 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/BufferingForwardingAppender.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/BufferingForwardingAppender.cs @@ -1,259 +1,256 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.Appender -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; +using System; - using log4net.Core; - using log4net.Layout; - using log4net.Util; +using log4net.Util; +using log4net.Layout; +using log4net.Core; - /// - /// Buffers events and then forwards them to attached appenders. - /// - /// - /// - /// The events are buffered in this appender until conditions are - /// met to allow the appender to deliver the events to the attached - /// appenders. See for the - /// conditions that cause the buffer to be sent. - /// - /// The forwarding appender can be used to specify different - /// thresholds and filters for the same appender at different locations - /// within the hierarchy. - /// - /// - /// Nicko Cadell. - /// Gert Driesen. - public class BufferingForwardingAppender : BufferingAppenderSkeleton, IAppenderAttachable +namespace log4net.Appender +{ + /// + /// Buffers events and then forwards them to attached appenders. + /// + /// + /// + /// The events are buffered in this appender until conditions are + /// met to allow the appender to deliver the events to the attached + /// appenders. See for the + /// conditions that cause the buffer to be sent. + /// + /// The forwarding appender can be used to specify different + /// thresholds and filters for the same appender at different locations + /// within the hierarchy. + /// + /// + /// Nicko Cadell + /// Gert Driesen + public class BufferingForwardingAppender : BufferingAppenderSkeleton, IAppenderAttachable { - /// - /// Initializes a new instance of the class. - /// - /// - /// - /// Default constructor. - /// - /// - public BufferingForwardingAppender() - { + /// + /// Initializes a new instance of the class. + /// + /// + /// + /// Default constructor. + /// + /// + public BufferingForwardingAppender() + { } - /// - /// Closes the appender and releases resources. - /// - /// - /// - /// Releases any resources allocated within the appender such as file handles, - /// network connections, etc. - /// - /// - /// It is a programming error to append to a closed appender. - /// - /// - protected override void OnClose() - { - // Remove all the attached appenders - lock (this) - { - // Delegate to base, which will flush buffers - base.OnClose(); - - if (this.m_appenderAttachedImpl != null) - { - this.m_appenderAttachedImpl.RemoveAllAppenders(); - } - } + /// + /// Closes the appender and releases resources. + /// + /// + /// + /// Releases any resources allocated within the appender such as file handles, + /// network connections, etc. + /// + /// + /// It is a programming error to append to a closed appender. + /// + /// + protected override void OnClose() + { + // Remove all the attached appenders + lock(this) + { + // Delegate to base, which will flush buffers + base.OnClose(); + + if (this.m_appenderAttachedImpl != null) + { + this.m_appenderAttachedImpl.RemoveAllAppenders(); + } + } } - /// - /// Send the events. - /// - /// The events that need to be send. - /// - /// - /// Forwards the events to the attached appenders. - /// - /// - protected override void SendBuffer(LoggingEvent[] events) - { - // Pass the logging event on to the attached appenders - if (this.m_appenderAttachedImpl != null) - { - this.m_appenderAttachedImpl.AppendLoopOnAppenders(events); - } + /// + /// Send the events. + /// + /// The events that need to be send. + /// + /// + /// Forwards the events to the attached appenders. + /// + /// + protected override void SendBuffer(LoggingEvent[] events) + { + // Pass the logging event on to the attached appenders + if (this.m_appenderAttachedImpl != null) + { + this.m_appenderAttachedImpl.AppendLoopOnAppenders(events); + } } - /// - /// Adds an to the list of appenders of this - /// instance. - /// - /// The to add to this appender. - /// - /// - /// If the specified is already in the list of - /// appenders, then it won't be added again. - /// - /// - public virtual void AddAppender(IAppender newAppender) - { - if (newAppender == null) - { - throw new ArgumentNullException("newAppender"); - } + /// + /// Adds an to the list of appenders of this + /// instance. + /// + /// The to add to this appender. + /// + /// + /// If the specified is already in the list of + /// appenders, then it won't be added again. + /// + /// + public virtual void AddAppender(IAppender newAppender) + { + if (newAppender == null) + { + throw new ArgumentNullException("newAppender"); + } + lock(this) + { + if (this.m_appenderAttachedImpl == null) + { + this.m_appenderAttachedImpl = new AppenderAttachedImpl(); + } - lock (this) - { - if (this.m_appenderAttachedImpl == null) - { - this.m_appenderAttachedImpl = new log4net.Util.AppenderAttachedImpl(); - } + this.m_appenderAttachedImpl.AddAppender(newAppender); + } + } - this.m_appenderAttachedImpl.AddAppender(newAppender); - } - } - - /// - /// Gets the appenders contained in this appender as an - /// . - /// - /// - /// If no appenders can be found, then an - /// is returned. - /// - /// - /// A collection of the appenders in this appender. - /// - public virtual AppenderCollection Appenders - { - get - { - lock (this) - { - if (this.m_appenderAttachedImpl == null) - { - return AppenderCollection.EmptyCollection; - } - else - { - return this.m_appenderAttachedImpl.Appenders; - } - } - } - } - - /// - /// Looks for the appender with the specified name. - /// - /// The name of the appender to lookup. - /// - /// The appender with the specified name, or null. - /// - /// - /// - /// Get the named appender attached to this buffering appender. - /// - /// - public virtual IAppender GetAppender(string name) - { - lock (this) - { - if (this.m_appenderAttachedImpl == null || name == null) - { - return null; - } - - return this.m_appenderAttachedImpl.GetAppender(name); - } - } - - /// - /// Removes all previously added appenders from this appender. - /// - /// - /// - /// This is useful when re-reading configuration information. - /// - /// - public virtual void RemoveAllAppenders() - { - lock (this) - { - if (this.m_appenderAttachedImpl != null) - { - this.m_appenderAttachedImpl.RemoveAllAppenders(); - this.m_appenderAttachedImpl = null; - } - } - } - - /// - /// Removes the specified appender from the list of appenders. - /// - /// The appender to remove. - /// The appender removed from the list. - /// - /// The appender removed is not closed. - /// If you are discarding the appender you must call - /// on the appender removed. - /// - public virtual IAppender RemoveAppender(IAppender appender) - { - lock (this) - { - if (appender != null && this.m_appenderAttachedImpl != null) - { - return this.m_appenderAttachedImpl.RemoveAppender(appender); - } - } + /// + /// Gets the appenders contained in this appender as an + /// . + /// + /// + /// If no appenders can be found, then an + /// is returned. + /// + /// + /// A collection of the appenders in this appender. + /// + public virtual AppenderCollection Appenders + { + get + { + lock(this) + { + if (this.m_appenderAttachedImpl == null) + { + return AppenderCollection.EmptyCollection; + } + else + { + return this.m_appenderAttachedImpl.Appenders; + } + } + } + } - return null; - } - - /// - /// Removes the appender with the specified name from the list of appenders. - /// - /// The name of the appender to remove. - /// The appender removed from the list. - /// - /// The appender removed is not closed. - /// If you are discarding the appender you must call - /// on the appender removed. - /// - public virtual IAppender RemoveAppender(string name) - { - lock (this) - { - if (name != null && this.m_appenderAttachedImpl != null) - { - return this.m_appenderAttachedImpl.RemoveAppender(name); - } - } + /// + /// Looks for the appender with the specified name. + /// + /// The name of the appender to lookup. + /// + /// The appender with the specified name, or null. + /// + /// + /// + /// Get the named appender attached to this buffering appender. + /// + /// + public virtual IAppender GetAppender(string name) + { + lock(this) + { + if (this.m_appenderAttachedImpl == null || name == null) + { + return null; + } + + return this.m_appenderAttachedImpl.GetAppender(name); + } + } + + /// + /// Removes all previously added appenders from this appender. + /// + /// + /// + /// This is useful when re-reading configuration information. + /// + /// + public virtual void RemoveAllAppenders() + { + lock(this) + { + if (this.m_appenderAttachedImpl != null) + { + this.m_appenderAttachedImpl.RemoveAllAppenders(); + this.m_appenderAttachedImpl = null; + } + } + } + + /// + /// Removes the specified appender from the list of appenders. + /// + /// The appender to remove. + /// The appender removed from the list + /// + /// The appender removed is not closed. + /// If you are discarding the appender you must call + /// on the appender removed. + /// + public virtual IAppender RemoveAppender(IAppender appender) + { + lock(this) + { + if (appender != null && this.m_appenderAttachedImpl != null) + { + return this.m_appenderAttachedImpl.RemoveAppender(appender); + } + } + return null; + } - return null; + /// + /// Removes the appender with the specified name from the list of appenders. + /// + /// The name of the appender to remove. + /// The appender removed from the list + /// + /// The appender removed is not closed. + /// If you are discarding the appender you must call + /// on the appender removed. + /// + public virtual IAppender RemoveAppender(string name) + { + lock(this) + { + if (name != null && this.m_appenderAttachedImpl != null) + { + return this.m_appenderAttachedImpl.RemoveAppender(name); + } + } + return null; } - /// - /// Implementation of the interface. - /// + /// + /// Implementation of the interface + /// private AppenderAttachedImpl m_appenderAttachedImpl; - } -} + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/ColoredConsoleAppender.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/ColoredConsoleAppender.cs index 8718d701349..078601c2452 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/ColoredConsoleAppender.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/ColoredConsoleAppender.cs @@ -1,636 +1,637 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -// MONO 1.0 Beta mcs does not like #if !A && !B && !C syntax - -// .NET Compact Framework 1.0 has no support for Win32 Console API's -#if !NETCF -// .Mono 1.0 has no support for Win32 Console API's -#if !MONO -// SSCLI 1.0 has no support for Win32 Console API's -#if !SSCLI -// We don't want framework or platform specific code in the CLI version of log4net -#if !CLI_1_0 - -using System; -using System.Globalization; -using System.Runtime.InteropServices; - -using log4net.Layout; -using log4net.Util; - -namespace log4net.Appender -{ - /// - /// Appends logging events to the console. - /// - /// - /// - /// ColoredConsoleAppender appends log events to the standard output stream - /// or the error output stream using a layout specified by the - /// user. It also allows the color of a specific type of message to be set. - /// - /// - /// By default, all output is written to the console's standard output stream. - /// The property can be set to direct the output to the - /// error stream. - /// - /// - /// NOTE: This appender writes directly to the application's attached console - /// not to the System.Console.Out or System.Console.Error TextWriter. - /// The System.Console.Out and System.Console.Error streams can be - /// programmatically redirected (for example NUnit does this to capture program output). - /// This appender will ignore these redirections because it needs to use Win32 - /// API calls to colorize the output. To respect these redirections the - /// must be used. - /// - /// - /// When configuring the colored console appender, mapping should be - /// specified to map a logging level to a color. For example: - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// The Level is the standard log4net logging level and ForeColor and BackColor can be any - /// combination of the following values: - /// - /// Blue - /// Green - /// Red - /// White - /// Yellow - /// Purple - /// Cyan - /// HighIntensity - /// - /// - /// - /// Rick Hobbs. - /// Nicko Cadell. - public class ColoredConsoleAppender : AppenderSkeleton +// MONO 1.0 Beta mcs does not like #if !A && !B && !C syntax + +#if !NETSTANDARD1_3 // netstandard doesn't support System.Security.Permissions +// .NET Compact Framework 1.0 has no support for Win32 Console API's +#if !NETCF +// .Mono 1.0 has no support for Win32 Console API's +#if !MONO +// SSCLI 1.0 has no support for Win32 Console API's +#if !SSCLI +// We don't want framework or platform specific code in the CLI version of log4net +#if !CLI_1_0 + +using System; +using System.Globalization; +using System.Runtime.InteropServices; + +using log4net.Layout; +using log4net.Util; + +namespace log4net.Appender +{ + /// + /// Appends logging events to the console. + /// + /// + /// + /// ColoredConsoleAppender appends log events to the standard output stream + /// or the error output stream using a layout specified by the + /// user. It also allows the color of a specific type of message to be set. + /// + /// + /// By default, all output is written to the console's standard output stream. + /// The property can be set to direct the output to the + /// error stream. + /// + /// + /// NOTE: This appender writes directly to the application's attached console + /// not to the System.Console.Out or System.Console.Error TextWriter. + /// The System.Console.Out and System.Console.Error streams can be + /// programmatically redirected (for example NUnit does this to capture program output). + /// This appender will ignore these redirections because it needs to use Win32 + /// API calls to colorize the output. To respect these redirections the + /// must be used. + /// + /// + /// When configuring the colored console appender, mapping should be + /// specified to map a logging level to a color. For example: + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// The Level is the standard log4net logging level and ForeColor and BackColor can be any + /// combination of the following values: + /// + /// Blue + /// Green + /// Red + /// White + /// Yellow + /// Purple + /// Cyan + /// HighIntensity + /// + /// + /// + /// Rick Hobbs + /// Nicko Cadell + public class ColoredConsoleAppender : AppenderSkeleton { - /// - /// The enum of possible color values for use with the color mapping method. - /// - /// - /// - /// The following flags can be combined together to - /// form the colors. - /// - /// - /// - [Flags] - public enum Colors : int - { - /// - /// color is blue - /// - Blue = 0x0001, - - /// - /// color is green - /// - Green = 0x0002, - - /// - /// color is red - /// - Red = 0x0004, - - /// - /// color is white - /// - White = Blue | Green | Red, - - /// - /// color is yellow - /// - Yellow = Red | Green, - - /// - /// color is purple - /// - Purple = Red | Blue, - - /// - /// color is cyan - /// - Cyan = Green | Blue, - - /// - /// color is intensified - /// - HighIntensity = 0x0008, + /// + /// The enum of possible color values for use with the color mapping method + /// + /// + /// + /// The following flags can be combined together to + /// form the colors. + /// + /// + /// + [Flags] + public enum Colors : int + { + /// + /// color is blue + /// + Blue = 0x0001, + + /// + /// color is green + /// + Green = 0x0002, + + /// + /// color is red + /// + Red = 0x0004, + + /// + /// color is white + /// + White = Blue | Green | Red, + + /// + /// color is yellow + /// + Yellow = Red | Green, + + /// + /// color is purple + /// + Purple = Red | Blue, + + /// + /// color is cyan + /// + Cyan = Green | Blue, + + /// + /// color is intensified + /// + HighIntensity = 0x0008, + } + + /// + /// Initializes a new instance of the class. + /// + /// + /// The instance of the class is set up to write + /// to the standard output stream. + /// + public ColoredConsoleAppender() + { + } + + /// + /// Initializes a new instance of the class + /// with the specified layout. + /// + /// the layout to use for this appender + /// + /// The instance of the class is set up to write + /// to the standard output stream. + /// + [Obsolete("Instead use the default constructor and set the Layout property")] + public ColoredConsoleAppender(ILayout layout) : this(layout, false) + { + } + + /// + /// Initializes a new instance of the class + /// with the specified layout. + /// + /// the layout to use for this appender + /// flag set to true to write to the console error stream + /// + /// When is set to true, output is written to + /// the standard error output stream. Otherwise, output is written to the standard + /// output stream. + /// + [Obsolete("Instead use the default constructor and set the Layout & Target properties")] + public ColoredConsoleAppender(ILayout layout, bool writeToErrorStream) + { + this.Layout = layout; + this.m_writeToErrorStream = writeToErrorStream; } - /// - /// Initializes a new instance of the class. - /// - /// - /// The instance of the class is set up to write - /// to the standard output stream. - /// - public ColoredConsoleAppender() - { - } - - /// - /// Initializes a new instance of the class - /// with the specified layout. - /// - /// the layout to use for this appender. - /// - /// The instance of the class is set up to write - /// to the standard output stream. - /// - [Obsolete("Instead use the default constructor and set the Layout property. Scheduled removal in v10.0.0.")] - public ColoredConsoleAppender(ILayout layout) - : this(layout, false) - { - } - - /// - /// Initializes a new instance of the class - /// with the specified layout. - /// - /// the layout to use for this appender. - /// flag set to true to write to the console error stream. - /// - /// When is set to true, output is written to - /// the standard error output stream. Otherwise, output is written to the standard - /// output stream. - /// - [Obsolete("Instead use the default constructor and set the Layout & Target properties. Scheduled removal in v10.0.0.")] - public ColoredConsoleAppender(ILayout layout, bool writeToErrorStream) - { - this.Layout = layout; - this.m_writeToErrorStream = writeToErrorStream; + /// + /// Target is the value of the console output stream. + /// This is either "Console.Out" or "Console.Error". + /// + /// + /// Target is the value of the console output stream. + /// This is either "Console.Out" or "Console.Error". + /// + /// + /// + /// Target is the value of the console output stream. + /// This is either "Console.Out" or "Console.Error". + /// + /// + public virtual string Target + { + get { return this.m_writeToErrorStream ? ConsoleError : ConsoleOut; } + set + { + string v = value.Trim(); + + if (string.Compare(ConsoleError, v, true, CultureInfo.InvariantCulture) == 0) + { + this.m_writeToErrorStream = true; + } + else + { + this.m_writeToErrorStream = false; + } + } } - /// - /// Gets or sets target is the value of the console output stream. - /// This is either "Console.Out" or "Console.Error". - /// - /// - /// Target is the value of the console output stream. - /// This is either "Console.Out" or "Console.Error". - /// - /// - /// - /// Target is the value of the console output stream. - /// This is either "Console.Out" or "Console.Error". - /// - /// - public virtual string Target - { - get { return this.m_writeToErrorStream ? ConsoleError : ConsoleOut; } - - set - { - string v = value.Trim(); - - if (string.Compare(ConsoleError, v, true, CultureInfo.InvariantCulture) == 0) - { - this.m_writeToErrorStream = true; - } - else - { - this.m_writeToErrorStream = false; - } - } - } - - /// - /// Add a mapping of level to color - done by the config file. - /// - /// The mapping to add. - /// - /// - /// Add a mapping to this appender. - /// Each mapping defines the foreground and background colors - /// for a level. - /// - /// - public void AddMapping(LevelColors mapping) - { - this.m_levelMapping.Add(mapping); + /// + /// Add a mapping of level to color - done by the config file + /// + /// The mapping to add + /// + /// + /// Add a mapping to this appender. + /// Each mapping defines the foreground and background colors + /// for a level. + /// + /// + public void AddMapping(LevelColors mapping) + { + this.m_levelMapping.Add(mapping); + } + + /// + /// This method is called by the method. + /// + /// The event to log. + /// + /// + /// Writes the event to the console. + /// + /// + /// The format of the output will depend on the appender's layout. + /// + /// +#if NET_4_0 || MONO_4_0 || NETSTANDARD + [System.Security.SecuritySafeCritical] +#endif + [System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Demand, UnmanagedCode = true)] + protected override void Append(Core.LoggingEvent loggingEvent) + { + if (this.m_consoleOutputWriter != null) + { + IntPtr consoleHandle = IntPtr.Zero; + if (this.m_writeToErrorStream) + { + // Write to the error stream + consoleHandle = GetStdHandle(STD_ERROR_HANDLE); + } + else + { + // Write to the output stream + consoleHandle = GetStdHandle(STD_OUTPUT_HANDLE); + } + + // Default to white on black + ushort colorInfo = (ushort)Colors.White; + + // see if there is a specified lookup + LevelColors levelColors = this.m_levelMapping.Lookup(loggingEvent.Level) as LevelColors; + if (levelColors != null) + { + colorInfo = levelColors.CombinedColor; + } + + // Render the event to a string + string strLoggingMessage = this.RenderLoggingEvent(loggingEvent); + + // get the current console color - to restore later + CONSOLE_SCREEN_BUFFER_INFO bufferInfo; + GetConsoleScreenBufferInfo(consoleHandle, out bufferInfo); + + // set the console colors + SetConsoleTextAttribute(consoleHandle, colorInfo); + + // Using WriteConsoleW seems to be unreliable. + // If a large buffer is written, say 15,000 chars + // Followed by a larger buffer, say 20,000 chars + // then WriteConsoleW will fail, last error 8 + // 'Not enough storage is available to process this command.' + // + // Although the documentation states that the buffer must + // be less that 64KB (i.e. 32,000 WCHARs) the longest string + // that I can write out a the first call to WriteConsoleW + // is only 30,704 chars. + // + // Unlike the WriteFile API the WriteConsoleW method does not + // seem to be able to partially write out from the input buffer. + // It does have a lpNumberOfCharsWritten parameter, but this is + // either the length of the input buffer if any output was written, + // or 0 when an error occurs. + // + // All results above were observed on Windows XP SP1 running + // .NET runtime 1.1 SP1. + // + // Old call to WriteConsoleW: + // + // WriteConsoleW( + // consoleHandle, + // strLoggingMessage, + // (UInt32)strLoggingMessage.Length, + // out (UInt32)ignoreWrittenCount, + // IntPtr.Zero); + // + // Instead of calling WriteConsoleW we use WriteFile which + // handles large buffers correctly. Because WriteFile does not + // handle the codepage conversion as WriteConsoleW does we + // need to use a System.IO.StreamWriter with the appropriate + // Encoding. The WriteFile calls are wrapped up in the + // System.IO.__ConsoleStream internal class obtained through + // the System.Console.OpenStandardOutput method. + // + // See the ActivateOptions method below for the code that + // retrieves and wraps the stream. + + + // The windows console uses ScrollConsoleScreenBuffer internally to + // scroll the console buffer when the display buffer of the console + // has been used up. ScrollConsoleScreenBuffer fills the area uncovered + // by moving the current content with the background color + // currently specified on the console. This means that it fills the + // whole line in front of the cursor position with the current + // background color. + // This causes an issue when writing out text with a non default + // background color. For example; We write a message with a Blue + // background color and the scrollable area of the console is full. + // When we write the newline at the end of the message the console + // needs to scroll the buffer to make space available for the new line. + // The ScrollConsoleScreenBuffer internals will fill the newly created + // space with the current background color: Blue. + // We then change the console color back to default (White text on a + // Black background). We write some text to the console, the text is + // written correctly in White with a Black background, however the + // remainder of the line still has a Blue background. + // + // This causes a disjointed appearance to the output where the background + // colors change. + // + // This can be remedied by restoring the console colors before causing + // the buffer to scroll, i.e. before writing the last newline. This does + // assume that the rendered message will end with a newline. + // + // Therefore we identify a trailing newline in the message and don't + // write this to the output, then we restore the console color and write + // a newline. Note that we must AutoFlush before we restore the console + // color otherwise we will have no effect. + // + // There will still be a slight artefact for the last line of the message + // will have the background extended to the end of the line, however this + // is unlikely to cause any user issues. + // + // Note that none of the above is visible while the console buffer is scrollable + // within the console window viewport, the effects only arise when the actual + // buffer is full and needs to be scrolled. + + char[] messageCharArray = strLoggingMessage.ToCharArray(); + int arrayLength = messageCharArray.Length; + bool appendNewline = false; + + // Trim off last newline, if it exists + if (arrayLength > 1 && messageCharArray[arrayLength-2] == '\r' && messageCharArray[arrayLength-1] == '\n') + { + arrayLength -= 2; + appendNewline = true; + } + + // Write to the output stream + this.m_consoleOutputWriter.Write(messageCharArray, 0, arrayLength); + + // Restore the console back to its previous color scheme + SetConsoleTextAttribute(consoleHandle, bufferInfo.wAttributes); + + if (appendNewline) + { + // Write the newline, after changing the color scheme + this.m_consoleOutputWriter.Write(s_windowsNewline, 0, 2); + } + } } - /// - /// This method is called by the method. - /// - /// The event to log. - /// - /// - /// Writes the event to the console. - /// - /// - /// The format of the output will depend on the appender's layout. - /// - /// -#if NET_4_0 || MONO_4_0 - [System.Security.SecuritySafeCritical] -#endif - [System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Demand, UnmanagedCode = true)] - protected override void Append(log4net.Core.LoggingEvent loggingEvent) - { - if (this.m_consoleOutputWriter != null) - { - IntPtr consoleHandle = IntPtr.Zero; - if (this.m_writeToErrorStream) - { - // Write to the error stream - consoleHandle = GetStdHandle(STD_ERROR_HANDLE); - } - else - { - // Write to the output stream - consoleHandle = GetStdHandle(STD_OUTPUT_HANDLE); - } - - // Default to white on black - ushort colorInfo = (ushort)Colors.White; - - // see if there is a specified lookup - LevelColors levelColors = this.m_levelMapping.Lookup(loggingEvent.Level) as LevelColors; - if (levelColors != null) - { - colorInfo = levelColors.CombinedColor; - } - - // Render the event to a string - string strLoggingMessage = this.RenderLoggingEvent(loggingEvent); - - // get the current console color - to restore later - CONSOLE_SCREEN_BUFFER_INFO bufferInfo; - GetConsoleScreenBufferInfo(consoleHandle, out bufferInfo); - - // set the console colors - SetConsoleTextAttribute(consoleHandle, colorInfo); - - // Using WriteConsoleW seems to be unreliable. - // If a large buffer is written, say 15,000 chars - // Followed by a larger buffer, say 20,000 chars - // then WriteConsoleW will fail, last error 8 - // 'Not enough storage is available to process this command.' - // - // Although the documentation states that the buffer must - // be less that 64KB (i.e. 32,000 WCHARs) the longest string - // that I can write out a the first call to WriteConsoleW - // is only 30,704 chars. - // - // Unlike the WriteFile API the WriteConsoleW method does not - // seem to be able to partially write out from the input buffer. - // It does have a lpNumberOfCharsWritten parameter, but this is - // either the length of the input buffer if any output was written, - // or 0 when an error occurs. - // - // All results above were observed on Windows XP SP1 running - // .NET runtime 1.1 SP1. - // - // Old call to WriteConsoleW: - // - // WriteConsoleW( - // consoleHandle, - // strLoggingMessage, - // (UInt32)strLoggingMessage.Length, - // out (UInt32)ignoreWrittenCount, - // IntPtr.Zero); - // - // Instead of calling WriteConsoleW we use WriteFile which - // handles large buffers correctly. Because WriteFile does not - // handle the codepage conversion as WriteConsoleW does we - // need to use a System.IO.StreamWriter with the appropriate - // Encoding. The WriteFile calls are wrapped up in the - // System.IO.__ConsoleStream internal class obtained through - // the System.Console.OpenStandardOutput method. - // - // See the ActivateOptions method below for the code that - // retrieves and wraps the stream. - - // The windows console uses ScrollConsoleScreenBuffer internally to - // scroll the console buffer when the display buffer of the console - // has been used up. ScrollConsoleScreenBuffer fills the area uncovered - // by moving the current content with the background color - // currently specified on the console. This means that it fills the - // whole line in front of the cursor position with the current - // background color. - // This causes an issue when writing out text with a non default - // background color. For example; We write a message with a Blue - // background color and the scrollable area of the console is full. - // When we write the newline at the end of the message the console - // needs to scroll the buffer to make space available for the new line. - // The ScrollConsoleScreenBuffer internals will fill the newly created - // space with the current background color: Blue. - // We then change the console color back to default (White text on a - // Black background). We write some text to the console, the text is - // written correctly in White with a Black background, however the - // remainder of the line still has a Blue background. - // - // This causes a disjointed appearance to the output where the background - // colors change. - // - // This can be remedied by restoring the console colors before causing - // the buffer to scroll, i.e. before writing the last newline. This does - // assume that the rendered message will end with a newline. - // - // Therefore we identify a trailing newline in the message and don't - // write this to the output, then we restore the console color and write - // a newline. Note that we must AutoFlush before we restore the console - // color otherwise we will have no effect. - // - // There will still be a slight artefact for the last line of the message - // will have the background extended to the end of the line, however this - // is unlikely to cause any user issues. - // - // Note that none of the above is visible while the console buffer is scrollable - // within the console window viewport, the effects only arise when the actual - // buffer is full and needs to be scrolled. - char[] messageCharArray = strLoggingMessage.ToCharArray(); - int arrayLength = messageCharArray.Length; - bool appendNewline = false; - - // Trim off last newline, if it exists - if (arrayLength > 1 && messageCharArray[arrayLength - 2] == '\r' && messageCharArray[arrayLength - 1] == '\n') - { - arrayLength -= 2; - appendNewline = true; - } - - // Write to the output stream - this.m_consoleOutputWriter.Write(messageCharArray, 0, arrayLength); - - // Restore the console back to its previous color scheme - SetConsoleTextAttribute(consoleHandle, bufferInfo.wAttributes); - - if (appendNewline) - { - // Write the newline, after changing the color scheme - this.m_consoleOutputWriter.Write(s_windowsNewline, 0, 2); - } - } - } - - private static readonly char[] s_windowsNewline = { '\r', '\n' }; - - /// - /// Gets a value indicating whether this appender requires a to be set. - /// - /// true. - /// - /// - /// This appender requires a to be set. - /// - /// - protected override bool RequiresLayout - { - get { return true; } + private static readonly char[] s_windowsNewline = {'\r', '\n'}; + + /// + /// This appender requires a to be set. + /// + /// true + /// + /// + /// This appender requires a to be set. + /// + /// + protected override bool RequiresLayout + { + get { return true; } } - /// - /// Initialize the options for this appender. - /// - /// - /// - /// Initialize the level to color mappings set on this appender. - /// - /// -#if NET_4_0 || MONO_4_0 - [System.Security.SecuritySafeCritical] -#endif - [System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Demand, UnmanagedCode = true)] - public override void ActivateOptions() - { - base.ActivateOptions(); - this.m_levelMapping.ActivateOptions(); - - System.IO.Stream consoleOutputStream = null; - - // Use the Console methods to open a Stream over the console std handle - if (this.m_writeToErrorStream) - { - // Write to the error stream - consoleOutputStream = Console.OpenStandardError(); - } - else - { - // Write to the output stream - consoleOutputStream = Console.OpenStandardOutput(); - } - - // Lookup the codepage encoding for the console - System.Text.Encoding consoleEncoding = System.Text.Encoding.GetEncoding(GetConsoleOutputCP()); - - // Create a writer around the console stream - this.m_consoleOutputWriter = new System.IO.StreamWriter(consoleOutputStream, consoleEncoding, 0x100); - - this.m_consoleOutputWriter.AutoFlush = true; - - // SuppressFinalize on m_consoleOutputWriter because all it will do is flush - // and close the file handle. Because we have set AutoFlush the additional flush - // is not required. The console file handle should not be closed, so we don't call - // Dispose, Close or the finalizer. - GC.SuppressFinalize(this.m_consoleOutputWriter); + /// + /// Initialize the options for this appender + /// + /// + /// + /// Initialize the level to color mappings set on this appender. + /// + /// +#if NET_4_0 || MONO_4_0 || NETSTANDARD + [System.Security.SecuritySafeCritical] +#endif + [System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Demand, UnmanagedCode = true)] + public override void ActivateOptions() + { + base.ActivateOptions(); + this.m_levelMapping.ActivateOptions(); + + System.IO.Stream consoleOutputStream = null; + + // Use the Console methods to open a Stream over the console std handle + if (this.m_writeToErrorStream) + { + // Write to the error stream + consoleOutputStream = Console.OpenStandardError(); + } + else + { + // Write to the output stream + consoleOutputStream = Console.OpenStandardOutput(); + } + + // Lookup the codepage encoding for the console + System.Text.Encoding consoleEncoding = System.Text.Encoding.GetEncoding(GetConsoleOutputCP()); + + // Create a writer around the console stream + this.m_consoleOutputWriter = new System.IO.StreamWriter(consoleOutputStream, consoleEncoding, 0x100); + + this.m_consoleOutputWriter.AutoFlush = true; + + // SuppressFinalize on m_consoleOutputWriter because all it will do is flush + // and close the file handle. Because we have set AutoFlush the additional flush + // is not required. The console file handle should not be closed, so we don't call + // Dispose, Close or the finalizer. + GC.SuppressFinalize(this.m_consoleOutputWriter); } - /// - /// The to use when writing to the Console - /// standard output stream. - /// - /// - /// - /// The to use when writing to the Console - /// standard output stream. - /// - /// - public const string ConsoleOut = "Console.Out"; - - /// - /// The to use when writing to the Console - /// standard error output stream. - /// - /// - /// - /// The to use when writing to the Console - /// standard error output stream. - /// - /// + /// + /// The to use when writing to the Console + /// standard output stream. + /// + /// + /// + /// The to use when writing to the Console + /// standard output stream. + /// + /// + public const string ConsoleOut = "Console.Out"; + + /// + /// The to use when writing to the Console + /// standard error output stream. + /// + /// + /// + /// The to use when writing to the Console + /// standard error output stream. + /// + /// public const string ConsoleError = "Console.Error"; - /// - /// Flag to write output to the error stream rather than the standard output stream. - /// - private bool m_writeToErrorStream = false; - - /// - /// Mapping from level object to color value. - /// - private LevelMapping m_levelMapping = new LevelMapping(); - - /// - /// The console output stream writer to write to. - /// - /// - /// - /// This writer is not thread safe. - /// - /// + /// + /// Flag to write output to the error stream rather than the standard output stream + /// + private bool m_writeToErrorStream = false; + + /// + /// Mapping from level object to color value + /// + private LevelMapping m_levelMapping = new LevelMapping(); + + /// + /// The console output stream writer to write to + /// + /// + /// + /// This writer is not thread safe. + /// + /// private System.IO.StreamWriter m_consoleOutputWriter = null; - [DllImport("Kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)] - private static extern int GetConsoleOutputCP(); - - [DllImport("Kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)] - private static extern bool SetConsoleTextAttribute( - IntPtr consoleHandle, - ushort attributes); - - [DllImport("Kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)] - private static extern bool GetConsoleScreenBufferInfo( - IntPtr consoleHandle, + [DllImport("Kernel32.dll", SetLastError=true, CharSet=CharSet.Auto)] + private static extern int GetConsoleOutputCP(); + + [DllImport("Kernel32.dll", SetLastError=true, CharSet=CharSet.Auto)] + private static extern bool SetConsoleTextAttribute( + IntPtr consoleHandle, + ushort attributes); + + [DllImport("Kernel32.dll", SetLastError=true, CharSet=CharSet.Auto)] + private static extern bool GetConsoleScreenBufferInfo( + IntPtr consoleHandle, out CONSOLE_SCREEN_BUFFER_INFO bufferInfo); - // [DllImport("Kernel32.dll", SetLastError=true, CharSet=CharSet.Unicode)] - // private static extern bool WriteConsoleW( - // IntPtr hConsoleHandle, - // [MarshalAs(UnmanagedType.LPWStr)] string strBuffer, - // UInt32 bufferLen, - // out UInt32 written, - // IntPtr reserved); - - // private const UInt32 STD_INPUT_HANDLE = unchecked((UInt32)(-10)); - private const uint STD_OUTPUT_HANDLE = unchecked((uint)(-11)); - private const uint STD_ERROR_HANDLE = unchecked((uint)(-12)); - - [DllImport("Kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)] - private static extern IntPtr GetStdHandle( - uint type); - - [StructLayout(LayoutKind.Sequential)] - private struct COORD - { - public ushort x; - public ushort y; - } - - [StructLayout(LayoutKind.Sequential)] - private struct SMALL_RECT - { - public ushort Left; - public ushort Top; - public ushort Right; - public ushort Bottom; - } - - [StructLayout(LayoutKind.Sequential)] - private struct CONSOLE_SCREEN_BUFFER_INFO - { - public COORD dwSize; - public COORD dwCursorPosition; - public ushort wAttributes; - public SMALL_RECT srWindow; - public COORD dwMaximumWindowSize; +// [DllImport("Kernel32.dll", SetLastError=true, CharSet=CharSet.Unicode)] +// private static extern bool WriteConsoleW( +// IntPtr hConsoleHandle, +// [MarshalAs(UnmanagedType.LPWStr)] string strBuffer, +// UInt32 bufferLen, +// out UInt32 written, +// IntPtr reserved); + + //private const UInt32 STD_INPUT_HANDLE = unchecked((UInt32)(-10)); + private const UInt32 STD_OUTPUT_HANDLE = unchecked((UInt32)(-11)); + private const UInt32 STD_ERROR_HANDLE = unchecked((UInt32)(-12)); + + [DllImport("Kernel32.dll", SetLastError=true, CharSet=CharSet.Auto)] + private static extern IntPtr GetStdHandle( + UInt32 type); + + [StructLayout(LayoutKind.Sequential)] + private struct COORD + { + public UInt16 x; + public UInt16 y; + } + + [StructLayout(LayoutKind.Sequential)] + private struct SMALL_RECT + { + public UInt16 Left; + public UInt16 Top; + public UInt16 Right; + public UInt16 Bottom; } - /// - /// A class to act as a mapping between the level that a logging call is made at and - /// the color it should be displayed as. - /// - /// - /// - /// Defines the mapping between a level and the color it should be displayed in. - /// - /// - public class LevelColors : LevelMappingEntry - { - private Colors m_foreColor; - private Colors m_backColor; - private ushort m_combinedColor = 0; - - /// - /// Gets or sets the mapped foreground color for the specified level. - /// - /// - /// - /// Required property. - /// The mapped foreground color for the specified level. - /// - /// - public Colors ForeColor - { - get { return this.m_foreColor; } - set { this.m_foreColor = value; } - } - - /// - /// Gets or sets the mapped background color for the specified level. - /// - /// - /// - /// Required property. - /// The mapped background color for the specified level. - /// - /// - public Colors BackColor - { - get { return this.m_backColor; } - set { this.m_backColor = value; } - } - - /// - /// Initialize the options for the object. - /// - /// - /// - /// Combine the and together. - /// - /// - public override void ActivateOptions() - { - base.ActivateOptions(); - this.m_combinedColor = (ushort)((int)this.m_foreColor + (((int)this.m_backColor) << 4)); - } - - /// - /// Gets the combined and suitable for - /// setting the console color. - /// - internal ushort CombinedColor - { - get { return this.m_combinedColor; } - } + [StructLayout(LayoutKind.Sequential)] + private struct CONSOLE_SCREEN_BUFFER_INFO + { + public COORD dwSize; + public COORD dwCursorPosition; + public ushort wAttributes; + public SMALL_RECT srWindow; + public COORD dwMaximumWindowSize; } - } -} - -#endif // !CLI_1_0 -#endif // !SSCLI -#endif // !MONO -#endif // !NETCF + + /// + /// A class to act as a mapping between the level that a logging call is made at and + /// the color it should be displayed as. + /// + /// + /// + /// Defines the mapping between a level and the color it should be displayed in. + /// + /// + public class LevelColors : LevelMappingEntry + { + private Colors m_foreColor; + private Colors m_backColor; + private ushort m_combinedColor = 0; + + /// + /// The mapped foreground color for the specified level + /// + /// + /// + /// Required property. + /// The mapped foreground color for the specified level. + /// + /// + public Colors ForeColor + { + get { return this.m_foreColor; } + set { this.m_foreColor = value; } + } + + /// + /// The mapped background color for the specified level + /// + /// + /// + /// Required property. + /// The mapped background color for the specified level. + /// + /// + public Colors BackColor + { + get { return this.m_backColor; } + set { this.m_backColor = value; } + } + + /// + /// Initialize the options for the object + /// + /// + /// + /// Combine the and together. + /// + /// + public override void ActivateOptions() + { + base.ActivateOptions(); + this.m_combinedColor = (ushort)( (int)this.m_foreColor + (((int)this.m_backColor) << 4) ); + } + + /// + /// The combined and suitable for + /// setting the console color. + /// + internal ushort CombinedColor + { + get { return this.m_combinedColor; } + } + } + } +} + +#endif // !CLI_1_0 +#endif // !SSCLI +#endif // !MONO +#endif // !NETCF +#endif // !NETSTANDARD1_3 diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/ConsoleAppender.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/ConsoleAppender.cs index 413a15fd030..a6eeed685eb 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/ConsoleAppender.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/ConsoleAppender.cs @@ -1,203 +1,202 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.Appender -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; - using System.Globalization; +using System; +using System.Globalization; - using log4net.Core; - using log4net.Layout; - using log4net.Util; +using log4net.Layout; +using log4net.Core; +using log4net.Util; - /// - /// Appends logging events to the console. - /// - /// - /// - /// ConsoleAppender appends log events to the standard output stream - /// or the error output stream using a layout specified by the - /// user. - /// - /// - /// By default, all output is written to the console's standard output stream. - /// The property can be set to direct the output to the - /// error stream. - /// - /// - /// NOTE: This appender writes each message to the System.Console.Out or - /// System.Console.Error that is set at the time the event is appended. - /// Therefore it is possible to programmatically redirect the output of this appender - /// (for example NUnit does this to capture program output). While this is the desired - /// behavior of this appender it may have security implications in your application. - /// - /// - /// Nicko Cadell. - /// Gert Driesen. - public class ConsoleAppender : AppenderSkeleton +namespace log4net.Appender +{ + /// + /// Appends logging events to the console. + /// + /// + /// + /// ConsoleAppender appends log events to the standard output stream + /// or the error output stream using a layout specified by the + /// user. + /// + /// + /// By default, all output is written to the console's standard output stream. + /// The property can be set to direct the output to the + /// error stream. + /// + /// + /// NOTE: This appender writes each message to the System.Console.Out or + /// System.Console.Error that is set at the time the event is appended. + /// Therefore it is possible to programmatically redirect the output of this appender + /// (for example NUnit does this to capture program output). While this is the desired + /// behavior of this appender it may have security implications in your application. + /// + /// + /// Nicko Cadell + /// Gert Driesen + public class ConsoleAppender : AppenderSkeleton { - /// - /// Initializes a new instance of the class. - /// - /// - /// The instance of the class is set up to write - /// to the standard output stream. - /// - public ConsoleAppender() - { - } - - /// - /// Initializes a new instance of the class - /// with the specified layout. - /// - /// the layout to use for this appender. - /// - /// The instance of the class is set up to write - /// to the standard output stream. - /// - [Obsolete("Instead use the default constructor and set the Layout property. Scheduled removal in v10.0.0.")] - public ConsoleAppender(ILayout layout) - : this(layout, false) - { - } - - /// - /// Initializes a new instance of the class - /// with the specified layout. - /// - /// the layout to use for this appender. - /// flag set to true to write to the console error stream. - /// - /// When is set to true, output is written to - /// the standard error output stream. Otherwise, output is written to the standard - /// output stream. - /// - [Obsolete("Instead use the default constructor and set the Layout & Target properties. Scheduled removal in v10.0.0.")] - public ConsoleAppender(ILayout layout, bool writeToErrorStream) - { - this.Layout = layout; - this.m_writeToErrorStream = writeToErrorStream; + /// + /// Initializes a new instance of the class. + /// + /// + /// The instance of the class is set up to write + /// to the standard output stream. + /// + public ConsoleAppender() + { } - /// - /// Gets or sets target is the value of the console output stream. - /// This is either "Console.Out" or "Console.Error". - /// - /// - /// Target is the value of the console output stream. - /// This is either "Console.Out" or "Console.Error". - /// - /// - /// - /// Target is the value of the console output stream. - /// This is either "Console.Out" or "Console.Error". - /// - /// - public virtual string Target - { - get { return this.m_writeToErrorStream ? ConsoleError : ConsoleOut; } + /// + /// Initializes a new instance of the class + /// with the specified layout. + /// + /// the layout to use for this appender + /// + /// The instance of the class is set up to write + /// to the standard output stream. + /// + [Obsolete("Instead use the default constructor and set the Layout property")] + public ConsoleAppender(ILayout layout) : this(layout, false) + { + } + + /// + /// Initializes a new instance of the class + /// with the specified layout. + /// + /// the layout to use for this appender + /// flag set to true to write to the console error stream + /// + /// When is set to true, output is written to + /// the standard error output stream. Otherwise, output is written to the standard + /// output stream. + /// + [Obsolete("Instead use the default constructor and set the Layout & Target properties")] + public ConsoleAppender(ILayout layout, bool writeToErrorStream) + { + this.Layout = layout; + this.m_writeToErrorStream = writeToErrorStream; + } + + /// + /// Target is the value of the console output stream. + /// This is either "Console.Out" or "Console.Error". + /// + /// + /// Target is the value of the console output stream. + /// This is either "Console.Out" or "Console.Error". + /// + /// + /// + /// Target is the value of the console output stream. + /// This is either "Console.Out" or "Console.Error". + /// + /// + public virtual string Target + { + get { return this.m_writeToErrorStream ? ConsoleError : ConsoleOut; } + set + { + string v = value.Trim(); - set - { - string v = value.Trim(); - - if (SystemInfo.EqualsIgnoringCase(ConsoleError, v)) - { - this.m_writeToErrorStream = true; - } - else - { - this.m_writeToErrorStream = false; - } - } + if (SystemInfo.EqualsIgnoringCase(ConsoleError, v)) + { + this.m_writeToErrorStream = true; + } + else + { + this.m_writeToErrorStream = false; + } + } } - /// - /// This method is called by the method. - /// - /// The event to log. - /// - /// - /// Writes the event to the console. - /// - /// - /// The format of the output will depend on the appender's layout. - /// - /// - protected override void Append(LoggingEvent loggingEvent) - { -#if NETCF_1_0 - // Write to the output stream - Console.Write(RenderLoggingEvent(loggingEvent)); -#else - if (this.m_writeToErrorStream) - { - // Write to the error stream - Console.Error.Write(this.RenderLoggingEvent(loggingEvent)); - } - else - { - // Write to the output stream - Console.Write(this.RenderLoggingEvent(loggingEvent)); - } -#endif - } - - /// - /// Gets a value indicating whether this appender requires a to be set. - /// - /// true. - /// - /// - /// This appender requires a to be set. - /// - /// - protected override bool RequiresLayout - { - get { return true; } + /// + /// This method is called by the method. + /// + /// The event to log. + /// + /// + /// Writes the event to the console. + /// + /// + /// The format of the output will depend on the appender's layout. + /// + /// + protected override void Append(LoggingEvent loggingEvent) + { +#if NETCF_1_0 + // Write to the output stream + Console.Write(RenderLoggingEvent(loggingEvent)); +#else + if (this.m_writeToErrorStream) + { + // Write to the error stream + Console.Error.Write(this.RenderLoggingEvent(loggingEvent)); + } + else + { + // Write to the output stream + Console.Write(this.RenderLoggingEvent(loggingEvent)); + } +#endif } - /// - /// The to use when writing to the Console - /// standard output stream. - /// - /// - /// - /// The to use when writing to the Console - /// standard output stream. - /// - /// - public const string ConsoleOut = "Console.Out"; - - /// - /// The to use when writing to the Console - /// standard error output stream. - /// - /// - /// - /// The to use when writing to the Console - /// standard error output stream. - /// - /// + /// + /// This appender requires a to be set. + /// + /// true + /// + /// + /// This appender requires a to be set. + /// + /// + protected override bool RequiresLayout + { + get { return true; } + } + + /// + /// The to use when writing to the Console + /// standard output stream. + /// + /// + /// + /// The to use when writing to the Console + /// standard output stream. + /// + /// + public const string ConsoleOut = "Console.Out"; + + /// + /// The to use when writing to the Console + /// standard error output stream. + /// + /// + /// + /// The to use when writing to the Console + /// standard error output stream. + /// + /// public const string ConsoleError = "Console.Error"; + private bool m_writeToErrorStream = false; - } -} + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/DebugAppender.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/DebugAppender.cs index 6057b28034c..b9b0e815173 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/DebugAppender.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/DebugAppender.cs @@ -1,177 +1,231 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information - -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#define DEBUG +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.Appender -{ - using log4net.Core; - using log4net.Layout; +#define DEBUG - /// - /// Appends log events to the system. - /// - /// - /// - /// The application configuration file can be used to control what listeners - /// are actually used. See the MSDN documentation for the - /// class for details on configuring the - /// debug system. - /// - /// - /// Events are written using the - /// method. The event's logger name is passed as the value for the category name to the Write method. - /// - /// - /// Nicko Cadell. - public class DebugAppender : AppenderSkeleton +using log4net.Layout; +using log4net.Core; + +namespace log4net.Appender +{ + /// + /// Appends log events to the system. + /// + /// + /// + /// The application configuration file can be used to control what listeners + /// are actually used. See the MSDN documentation for the + /// class for details on configuring the + /// debug system. + /// + /// + /// Events are written using the + /// method. The event's logger name is passed as the value for the category name to the Write method. + /// + /// + /// Nicko Cadell + public class DebugAppender : AppenderSkeleton { /// - /// Initializes a new instance of the class. - /// Initializes a new instance of the . - /// - /// - /// - /// Default constructor. - /// - /// - public DebugAppender() - { + /// Initializes a new instance of the . + /// + /// + /// + /// Default constructor. + /// + /// + public DebugAppender() + { } /// - /// Initializes a new instance of the class. - /// Initializes a new instance of the - /// with a specified layout. - /// - /// The layout to use with this appender. - /// - /// - /// Obsolete constructor. - /// - /// - [System.Obsolete("Instead use the default constructor and set the Layout property")] - public DebugAppender(ILayout layout) - { - this.Layout = layout; + /// Initializes a new instance of the + /// with a specified layout. + /// + /// The layout to use with this appender. + /// + /// + /// Obsolete constructor. + /// + /// + [System.Obsolete("Instead use the default constructor and set the Layout property")] + public DebugAppender(ILayout layout) + { + this.Layout = layout; } - /// - /// Gets or sets a value indicating whether gets or sets a value that indicates whether the appender will - /// flush at the end of each write. - /// - /// - /// The default behavior is to flush at the end of each - /// write. If the option is set tofalse, then the underlying - /// stream can defer writing to physical medium to a later time. - /// - /// - /// Avoiding the flush operation at the end of each append results - /// in a performance gain of 10 to 20 percent. However, there is safety - /// trade-off involved in skipping flushing. Indeed, when flushing is - /// skipped, then it is likely that the last few log events will not - /// be recorded on disk when the application exits. This is a high - /// price to pay even for a 20% performance gain. - /// - /// - public bool ImmediateFlush - { - get { return this.m_immediateFlush; } - set { this.m_immediateFlush = value; } +#if !NETSTANDARD1_3 // System.Diagnostics.Debug has no Flush() in netstandard1.3 + /// + /// Gets or sets a value that indicates whether the appender will + /// flush at the end of each write. + /// + /// + /// The default behavior is to flush at the end of each + /// write. If the option is set tofalse, then the underlying + /// stream can defer writing to physical medium to a later time. + /// + /// + /// Avoiding the flush operation at the end of each append results + /// in a performance gain of 10 to 20 percent. However, there is safety + /// trade-off involved in skipping flushing. Indeed, when flushing is + /// skipped, then it is likely that the last few log events will not + /// be recorded on disk when the application exits. This is a high + /// price to pay even for a 20% performance gain. + /// + /// + public bool ImmediateFlush + { + get { return this.m_immediateFlush; } + set { this.m_immediateFlush = value; } } +#endif // !NETSTANDARD1_3 -#if !NETSTANDARD1_3 - /// - /// Flushes any buffered log data. - /// - /// The maximum time to wait for logging events to be flushed. - /// True if all logging events were flushed successfully, else false. - public override bool Flush(int millisecondsTimeout) + /// + /// Formats the category parameter sent to the Debug method. + /// + /// + /// + /// Defaults to a with %logger as the pattern which will use the logger name of the current + /// as the category parameter. + /// + /// + /// + /// + public PatternLayout Category { - // Nothing to do if ImmediateFlush is true - if (this.m_immediateFlush) + get { return this.m_category; } + set { this.m_category = value; } + } + +#if !NETSTANDARD1_3 + /// + /// Flushes any buffered log data. + /// + /// The maximum time to wait for logging events to be flushed. + /// True if all logging events were flushed successfully, else false. + public override bool Flush(int millisecondsTimeout) { + // Nothing to do if ImmediateFlush is true + if (this.m_immediateFlush) + { + return true; + } + + // System.Diagnostics.Debug is thread-safe, so no need for lock(this). + System.Diagnostics.Debug.Flush(); + return true; } +#endif - // System.Diagnostics.Debug is thread-safe, so no need for lock(this). - System.Diagnostics.Debug.Flush(); - - return true; +#if NETSTANDARD1_3 + /// + /// Writes the logging event to the system. + /// + /// The event to log. + /// + /// + /// Writes the logging event to the system. + /// + /// +#else + /// + /// Writes the logging event to the system. + /// + /// The event to log. + /// + /// + /// Writes the logging event to the system. + /// If is true then the + /// is called. + /// + /// +#endif + protected override void Append(LoggingEvent loggingEvent) + { + // + // Write the string to the Debug system + // + if(this.m_category == null) + { + System.Diagnostics.Debug.Write(this.RenderLoggingEvent(loggingEvent)); + } + else + { + string category = this.m_category.Format(loggingEvent); + if (string.IsNullOrEmpty(category)) + { + System.Diagnostics.Debug.Write(this.RenderLoggingEvent(loggingEvent)); + } + else + { + System.Diagnostics.Debug.Write(this.RenderLoggingEvent(loggingEvent), category); + } + } +#if !NETSTANDARD1_3 + // + // Flush the Debug system if needed + // + if (this.m_immediateFlush) + { + System.Diagnostics.Debug.Flush(); + } +#endif } -#endif - /// - /// Writes the logging event to the system. - /// - /// The event to log. - /// - /// - /// Writes the logging event to the system. - /// If is true then the - /// is called. - /// - /// - protected override void Append(LoggingEvent loggingEvent) - { - // Write the string to the Debug system - System.Diagnostics.Debug.Write(this.RenderLoggingEvent(loggingEvent), loggingEvent.LoggerName); -#if !NETSTANDARD1_3 - // - // Flush the Debug system if needed - if (this.m_immediateFlush) - { - System.Diagnostics.Debug.Flush(); - } -#endif - } - - /// - /// Gets a value indicating whether this appender requires a to be set. - /// - /// true. - /// - /// - /// This appender requires a to be set. - /// - /// - protected override bool RequiresLayout - { - get { return true; } + /// + /// This appender requires a to be set. + /// + /// true + /// + /// + /// This appender requires a to be set. + /// + /// + protected override bool RequiresLayout + { + get { return true; } } - /// - /// Immediate flush means that the underlying writer or output stream - /// will be flushed at the end of each append operation. - /// - /// - /// - /// Immediate flush is slower but ensures that each append request is - /// actually written. If is set to - /// false, then there is a good chance that the last few - /// logs events are not actually written to persistent media if and - /// when the application crashes. - /// - /// - /// The default value is true. - /// +#if !NETSTANDARD1_3 + /// + /// Immediate flush means that the underlying writer or output stream + /// will be flushed at the end of each append operation. + /// + /// + /// + /// Immediate flush is slower but ensures that each append request is + /// actually written. If is set to + /// false, then there is a good chance that the last few + /// logs events are not actually written to persistent media if and + /// when the application crashes. + /// + /// + /// The default value is true. + /// private bool m_immediateFlush = true; - } -} +#endif + + /// + /// Defaults to a with %logger as the pattern. + /// + private PatternLayout m_category = new PatternLayout("%logger"); + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/EventLogAppender.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/EventLogAppender.cs index e217d769526..bd77e3d9c8b 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/EventLogAppender.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/EventLogAppender.cs @@ -1,665 +1,667 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -// MONO 1.0 Beta mcs does not like #if !A && !B && !C syntax - -// .NET Compact Framework 1.0 has no support for EventLog -#if !NETCF -// SSCLI 1.0 has no support for EventLog -#if !SSCLI - -using System; -using System.Diagnostics; -using System.Globalization; - -using log4net.Core; -using log4net.Layout; -using log4net.Util; - -namespace log4net.Appender -{ - /// - /// Writes events to the system event log. - /// - /// - /// - /// The appender will fail if you try to write using an event source that doesn't exist unless it is running with local administrator privileges. - /// See also http://logging.apache.org/log4net/release/faq.html#trouble-EventLog. - /// - /// - /// The EventID of the event log entry can be - /// set using the EventID property () - /// on the . - /// - /// - /// The Category of the event log entry can be - /// set using the Category property () - /// on the . - /// - /// - /// There is a limit of 32K characters for an event log message. - /// - /// - /// When configuring the EventLogAppender a mapping can be - /// specified to map a logging level to an event log entry type. For example: - /// - /// - /// <mapping> - /// <level value="ERROR" /> - /// <eventLogEntryType value="Error" /> - /// </mapping> - /// <mapping> - /// <level value="DEBUG" /> - /// <eventLogEntryType value="Information" /> - /// </mapping> - /// - /// - /// The Level is the standard log4net logging level and eventLogEntryType can be any value - /// from the enum, i.e.: - /// - /// Erroran error event - /// Warninga warning event - /// Informationan informational event - /// - /// - /// - /// Aspi Havewala. - /// Douglas de la Torre. - /// Nicko Cadell. - /// Gert Driesen. - /// Thomas Voss. - public class EventLogAppender : AppenderSkeleton +// MONO 1.0 Beta mcs does not like #if !A && !B && !C syntax + +// netstandard doesn't support EventLog +#if NET_2_0 +// .NET Compact Framework 1.0 has no support for EventLog +#if !NETCF +// SSCLI 1.0 has no support for EventLog +#if !SSCLI + +using System; +using System.Diagnostics; +using System.Globalization; + +using log4net.Util; +using log4net.Layout; +using log4net.Core; + +namespace log4net.Appender +{ + /// + /// Writes events to the system event log. + /// + /// + /// + /// The appender will fail if you try to write using an event source that doesn't exist unless it is running with local administrator privileges. + /// See also http://logging.apache.org/log4net/release/faq.html#trouble-EventLog + /// + /// + /// The EventID of the event log entry can be + /// set using the EventID property () + /// on the . + /// + /// + /// The Category of the event log entry can be + /// set using the Category property () + /// on the . + /// + /// + /// There is a limit of 32K characters for an event log message + /// + /// + /// When configuring the EventLogAppender a mapping can be + /// specified to map a logging level to an event log entry type. For example: + /// + /// + /// <mapping> + /// <level value="ERROR" /> + /// <eventLogEntryType value="Error" /> + /// </mapping> + /// <mapping> + /// <level value="DEBUG" /> + /// <eventLogEntryType value="Information" /> + /// </mapping> + /// + /// + /// The Level is the standard log4net logging level and eventLogEntryType can be any value + /// from the enum, i.e.: + /// + /// Erroran error event + /// Warninga warning event + /// Informationan informational event + /// + /// + /// + /// Aspi Havewala + /// Douglas de la Torre + /// Nicko Cadell + /// Gert Driesen + /// Thomas Voss + public class EventLogAppender : AppenderSkeleton { - /// - /// Initializes a new instance of the class. - /// - /// - /// - /// Default constructor. - /// - /// - public EventLogAppender() - { - this.m_applicationName = System.Threading.Thread.GetDomain().FriendlyName; - this.m_logName = "Application"; // Defaults to application log - this.m_machineName = "."; // Only log on the local machine - } - - /// - /// Initializes a new instance of the class - /// with the specified . - /// - /// The to use with this appender. - /// - /// - /// Obsolete constructor. - /// - /// - [Obsolete("Instead use the default constructor and set the Layout property. Scheduled removal in v10.0.0.")] - public EventLogAppender(ILayout layout) - : this() - { - this.Layout = layout; + /// + /// Initializes a new instance of the class. + /// + /// + /// + /// Default constructor. + /// + /// + public EventLogAppender() + { + this.m_applicationName = System.Threading.Thread.GetDomain().FriendlyName; + this.m_logName = "Application"; // Defaults to application log + this.m_machineName = "."; // Only log on the local machine + } + + /// + /// Initializes a new instance of the class + /// with the specified . + /// + /// The to use with this appender. + /// + /// + /// Obsolete constructor. + /// + /// + [Obsolete("Instead use the default constructor and set the Layout property")] + public EventLogAppender(ILayout layout) : this() + { + this.Layout = layout; + } + + /// + /// The name of the log where messages will be stored. + /// + /// + /// The string name of the log where messages will be stored. + /// + /// + /// This is the name of the log as it appears in the Event Viewer + /// tree. The default value is to log into the Application + /// log, this is where most applications write their events. However + /// if you need a separate log for your application (or applications) + /// then you should set the appropriately. + /// This should not be used to distinguish your event log messages + /// from those of other applications, the + /// property should be used to distinguish events. This property should be + /// used to group together events into a single log. + /// + /// + public string LogName + { + get { return this.m_logName; } + set { this.m_logName = value; } + } + + /// + /// Property used to set the Application name. This appears in the + /// event logs when logging. + /// + /// + /// The string used to distinguish events from different sources. + /// + /// + /// Sets the event log source property. + /// + public string ApplicationName + { + get { return this.m_applicationName; } + set { this.m_applicationName = value; } + } + + /// + /// This property is used to return the name of the computer to use + /// when accessing the event logs. Currently, this is the current + /// computer, denoted by a dot "." + /// + /// + /// The string name of the machine holding the event log that + /// will be logged into. + /// + /// + /// This property cannot be changed. It is currently set to '.' + /// i.e. the local machine. This may be changed in future. + /// + public string MachineName + { + get { return this.m_machineName; } + set { /* Currently we do not allow the machine name to be changed */; } + } + + /// + /// Add a mapping of level to - done by the config file + /// + /// The mapping to add + /// + /// + /// Add a mapping to this appender. + /// Each mapping defines the event log entry type for a level. + /// + /// + public void AddMapping(Level2EventLogEntryType mapping) + { + this.m_levelMapping.Add(mapping); } - /// - /// Gets or sets the name of the log where messages will be stored. - /// - /// - /// The string name of the log where messages will be stored. - /// - /// - /// This is the name of the log as it appears in the Event Viewer - /// tree. The default value is to log into the Application - /// log, this is where most applications write their events. However - /// if you need a separate log for your application (or applications) - /// then you should set the appropriately. - /// This should not be used to distinguish your event log messages - /// from those of other applications, the - /// property should be used to distinguish events. This property should be - /// used to group together events into a single log. - /// - /// - public string LogName - { - get { return this.m_logName; } - set { this.m_logName = value; } - } - - /// - /// Gets or sets property used to set the Application name. This appears in the - /// event logs when logging. - /// - /// - /// The string used to distinguish events from different sources. - /// - /// - /// Sets the event log source property. - /// - public string ApplicationName - { - get { return this.m_applicationName; } - set { this.m_applicationName = value; } - } - - /// - /// Gets or sets this property is used to return the name of the computer to use - /// when accessing the event logs. Currently, this is the current - /// computer, denoted by a dot ".". - /// - /// - /// The string name of the machine holding the event log that - /// will be logged into. - /// - /// - /// This property cannot be changed. It is currently set to '.' - /// i.e. the local machine. This may be changed in future. - /// - public string MachineName - { - get { return this.m_machineName; } - set { /* Currently we do not allow the machine name to be changed */ } - } - - /// - /// Add a mapping of level to - done by the config file. - /// - /// The mapping to add. - /// - /// - /// Add a mapping to this appender. - /// Each mapping defines the event log entry type for a level. - /// - /// - public void AddMapping(Level2EventLogEntryType mapping) - { - this.m_levelMapping.Add(mapping); - } - - /// - /// Gets or sets the used to write to the EventLog. - /// - /// - /// The used to write to the EventLog. - /// - /// - /// - /// The system security context used to write to the EventLog. - /// - /// - /// Unless a specified here for this appender - /// the is queried for the - /// security context to use. The default behavior is to use the security context - /// of the current thread. - /// - /// - public SecurityContext SecurityContext - { - get { return this.m_securityContext; } - set { this.m_securityContext = value; } - } - - /// - /// Gets or sets the EventId to use unless one is explicitly specified via the LoggingEvent's properties. - /// - /// - /// - /// The EventID of the event log entry will normally be - /// set using the EventID property () - /// on the . - /// This property provides the fallback value which defaults to 0. - /// - /// + /// + /// Gets or sets the used to write to the EventLog. + /// + /// + /// The used to write to the EventLog. + /// + /// + /// + /// The system security context used to write to the EventLog. + /// + /// + /// Unless a specified here for this appender + /// the is queried for the + /// security context to use. The default behavior is to use the security context + /// of the current thread. + /// + /// + public SecurityContext SecurityContext + { + get { return this.m_securityContext; } + set { this.m_securityContext = value; } + } + + /// + /// Gets or sets the EventId to use unless one is explicitly specified via the LoggingEvent's properties. + /// + /// + /// + /// The EventID of the event log entry will normally be + /// set using the EventID property () + /// on the . + /// This property provides the fallback value which defaults to 0. + /// + /// public int EventId - { - get { return this.m_eventId; } - set { this.m_eventId = value; } - } - - /// - /// Gets or sets the Category to use unless one is explicitly specified via the LoggingEvent's properties. - /// - /// - /// - /// The Category of the event log entry will normally be - /// set using the Category property () - /// on the . - /// This property provides the fallback value which defaults to 0. - /// - /// - public short Category - { - get { return this.m_category; } - set { this.m_category = value; } + { + get { return this.m_eventId; } + set { this.m_eventId = value; } } - /// - /// Initialize the appender based on the options set. - /// - /// - /// - /// This is part of the delayed object - /// activation scheme. The method must - /// be called on this object after the configuration properties have - /// been set. Until is called this - /// object is in an undefined state and must not be used. - /// - /// - /// If any of the configuration properties are modified then - /// must be called again. - /// - /// - public override void ActivateOptions() - { - try - { - base.ActivateOptions(); - - if (this.m_securityContext == null) - { - this.m_securityContext = SecurityContextProvider.DefaultProvider.CreateSecurityContext(this); - } - - bool sourceAlreadyExists = false; - string currentLogName = null; - - using (this.SecurityContext.Impersonate(this)) - { - sourceAlreadyExists = EventLog.SourceExists(this.m_applicationName); - if (sourceAlreadyExists) - { - currentLogName = EventLog.LogNameFromSourceName(this.m_applicationName, this.m_machineName); - } - } - - if (sourceAlreadyExists && currentLogName != this.m_logName) - { - LogLog.Debug(declaringType, "Changing event source [" + this.m_applicationName + "] from log [" + currentLogName + "] to log [" + this.m_logName + "]"); - } - else if (!sourceAlreadyExists) - { - LogLog.Debug(declaringType, "Creating event source Source [" + this.m_applicationName + "] in log " + this.m_logName + "]"); - } - - string registeredLogName = null; - - using (this.SecurityContext.Impersonate(this)) - { - if (sourceAlreadyExists && currentLogName != this.m_logName) - { - // Re-register this to the current application if the user has changed - // the application / logfile association - EventLog.DeleteEventSource(this.m_applicationName, this.m_machineName); - CreateEventSource(this.m_applicationName, this.m_logName, this.m_machineName); - - registeredLogName = EventLog.LogNameFromSourceName(this.m_applicationName, this.m_machineName); - } - else if (!sourceAlreadyExists) - { - CreateEventSource(this.m_applicationName, this.m_logName, this.m_machineName); - - registeredLogName = EventLog.LogNameFromSourceName(this.m_applicationName, this.m_machineName); - } - } - - this.m_levelMapping.ActivateOptions(); - - LogLog.Debug(declaringType, "Source [" + this.m_applicationName + "] is registered to log [" + registeredLogName + "]"); - } - catch (System.Security.SecurityException ex) - { - this.ErrorHandler.Error( - "Caught a SecurityException trying to access the EventLog. Most likely the event source " - + this.m_applicationName - + " doesn't exist and must be created by a local administrator. Will disable EventLogAppender." - + " See http://logging.apache.org/log4net/release/faq.html#trouble-EventLog", - ex); - this.Threshold = Level.Off; - } + + /// + /// Gets or sets the Category to use unless one is explicitly specified via the LoggingEvent's properties. + /// + /// + /// + /// The Category of the event log entry will normally be + /// set using the Category property () + /// on the . + /// This property provides the fallback value which defaults to 0. + /// + /// + public short Category + { + get { return this.m_category; } + set { this.m_category = value; } } - /// - /// Create an event log source. - /// - /// - /// Uses different API calls under NET_2_0. - /// - private static void CreateEventSource(string source, string logName, string machineName) - { -#if NET_2_0 - EventSourceCreationData eventSourceCreationData = new EventSourceCreationData(source, logName); - eventSourceCreationData.MachineName = machineName; - EventLog.CreateEventSource(eventSourceCreationData); -#else - EventLog.CreateEventSource(source, logName, machineName); -#endif + /// + /// Initialize the appender based on the options set + /// + /// + /// + /// This is part of the delayed object + /// activation scheme. The method must + /// be called on this object after the configuration properties have + /// been set. Until is called this + /// object is in an undefined state and must not be used. + /// + /// + /// If any of the configuration properties are modified then + /// must be called again. + /// + /// + public override void ActivateOptions() + { + try + { + base.ActivateOptions(); + + if (this.m_securityContext == null) + { + this.m_securityContext = SecurityContextProvider.DefaultProvider.CreateSecurityContext(this); + } + + bool sourceAlreadyExists = false; + string currentLogName = null; + + using (this.SecurityContext.Impersonate(this)) + { + sourceAlreadyExists = EventLog.SourceExists(this.m_applicationName); + if (sourceAlreadyExists) { + currentLogName = EventLog.LogNameFromSourceName(this.m_applicationName, this.m_machineName); + } + } + + if (sourceAlreadyExists && currentLogName != this.m_logName) + { + LogLog.Debug(declaringType, "Changing event source [" + this.m_applicationName + "] from log [" + currentLogName + "] to log [" + this.m_logName + "]"); + } + else if (!sourceAlreadyExists) + { + LogLog.Debug(declaringType, "Creating event source Source [" + this.m_applicationName + "] in log " + this.m_logName + "]"); + } + + string registeredLogName = null; + + using (this.SecurityContext.Impersonate(this)) + { + if (sourceAlreadyExists && currentLogName != this.m_logName) + { + // + // Re-register this to the current application if the user has changed + // the application / logfile association + // + EventLog.DeleteEventSource(this.m_applicationName, this.m_machineName); + CreateEventSource(this.m_applicationName, this.m_logName, this.m_machineName); + + registeredLogName = EventLog.LogNameFromSourceName(this.m_applicationName, this.m_machineName); + } + else if (!sourceAlreadyExists) + { + CreateEventSource(this.m_applicationName, this.m_logName, this.m_machineName); + + registeredLogName = EventLog.LogNameFromSourceName(this.m_applicationName, this.m_machineName); + } + } + + this.m_levelMapping.ActivateOptions(); + + LogLog.Debug(declaringType, "Source [" + this.m_applicationName + "] is registered to log [" + registeredLogName + "]"); + } + catch (System.Security.SecurityException ex) + { + this.ErrorHandler.Error("Caught a SecurityException trying to access the EventLog. Most likely the event source " + + this.m_applicationName + + " doesn't exist and must be created by a local administrator. Will disable EventLogAppender." + + " See http://logging.apache.org/log4net/release/faq.html#trouble-EventLog", + ex); + this.Threshold = Level.Off; + } } - /// - /// This method is called by the - /// method. - /// - /// the event to log. - /// - /// Writes the event to the system event log using the - /// . - /// - /// If the event has an EventID property (see ) - /// set then this integer will be used as the event log event id. - /// - /// - /// There is a limit of 32K characters for an event log message. - /// - /// - protected override void Append(LoggingEvent loggingEvent) - { - // Write the resulting string to the event log system - int eventID = this.m_eventId; - - // Look for the EventID property - object eventIDPropertyObj = loggingEvent.LookupProperty("EventID"); - if (eventIDPropertyObj != null) - { - if (eventIDPropertyObj is int) - { - eventID = (int)eventIDPropertyObj; - } - else - { - string eventIDPropertyString = eventIDPropertyObj as string; - if (eventIDPropertyString == null) - { - eventIDPropertyString = eventIDPropertyObj.ToString(); - } - - if (eventIDPropertyString != null && eventIDPropertyString.Length > 0) - { - // Read the string property into a number - int intVal; - if (SystemInfo.TryParse(eventIDPropertyString, out intVal)) - { - eventID = intVal; - } - else - { - this.ErrorHandler.Error("Unable to parse event ID property [" + eventIDPropertyString + "]."); - } - } - } - } - - short category = this.m_category; - - // Look for the Category property - object categoryPropertyObj = loggingEvent.LookupProperty("Category"); - if (categoryPropertyObj != null) - { - if (categoryPropertyObj is short) - { - category = (short)categoryPropertyObj; - } - else - { - string categoryPropertyString = categoryPropertyObj as string; - if (categoryPropertyString == null) - { - categoryPropertyString = categoryPropertyObj.ToString(); - } - - if (categoryPropertyString != null && categoryPropertyString.Length > 0) - { - // Read the string property into a number - short shortVal; - if (SystemInfo.TryParse(categoryPropertyString, out shortVal)) - { - category = shortVal; - } - else - { - this.ErrorHandler.Error("Unable to parse event category property [" + categoryPropertyString + "]."); - } - } - } - } - - // Write to the event log - try - { - string eventTxt = this.RenderLoggingEvent(loggingEvent); - - // There is a limit of about 32K characters for an event log message - if (eventTxt.Length > MAX_EVENTLOG_MESSAGE_SIZE) - { - eventTxt = eventTxt.Substring(0, MAX_EVENTLOG_MESSAGE_SIZE); - } - - EventLogEntryType entryType = this.GetEntryType(loggingEvent.Level); - - using (this.SecurityContext.Impersonate(this)) - { - EventLog.WriteEntry(this.m_applicationName, eventTxt, entryType, eventID, category); - } - } - catch (Exception ex) - { - this.ErrorHandler.Error("Unable to write to event log [" + this.m_logName + "] using source [" + this.m_applicationName + "]", ex); - } - } - - /// - /// Gets a value indicating whether this appender requires a to be set. - /// - /// true. - /// - /// - /// This appender requires a to be set. - /// - /// - protected override bool RequiresLayout - { - get { return true; } + /// + /// Create an event log source + /// + /// + /// Uses different API calls under NET_2_0 + /// + private static void CreateEventSource(string source, string logName, string machineName) + { +#if NET_2_0 + EventSourceCreationData eventSourceCreationData = new EventSourceCreationData(source, logName); + eventSourceCreationData.MachineName = machineName; + EventLog.CreateEventSource(eventSourceCreationData); +#else + EventLog.CreateEventSource(source, logName, machineName); +#endif + } + + /// + /// This method is called by the + /// method. + /// + /// the event to log + /// + /// Writes the event to the system event log using the + /// . + /// + /// If the event has an EventID property (see ) + /// set then this integer will be used as the event log event id. + /// + /// + /// There is a limit of 32K characters for an event log message + /// + /// + protected override void Append(LoggingEvent loggingEvent) + { + // + // Write the resulting string to the event log system + // + int eventID = this.m_eventId; + + // Look for the EventID property + object eventIDPropertyObj = loggingEvent.LookupProperty("EventID"); + if (eventIDPropertyObj != null) + { + if (eventIDPropertyObj is int) + { + eventID = (int)eventIDPropertyObj; + } + else + { + string eventIDPropertyString = eventIDPropertyObj as string; + if (eventIDPropertyString == null) + { + eventIDPropertyString = eventIDPropertyObj.ToString(); + } + if (eventIDPropertyString != null && eventIDPropertyString.Length > 0) + { + // Read the string property into a number + int intVal; + if (SystemInfo.TryParse(eventIDPropertyString, out intVal)) + { + eventID = intVal; + } + else + { + this.ErrorHandler.Error("Unable to parse event ID property [" + eventIDPropertyString + "]."); + } + } + } + } + + short category = this.m_category; + // Look for the Category property + object categoryPropertyObj = loggingEvent.LookupProperty("Category"); + if (categoryPropertyObj != null) + { + if (categoryPropertyObj is short) + { + category = (short) categoryPropertyObj; + } + else + { + string categoryPropertyString = categoryPropertyObj as string; + if (categoryPropertyString == null) + { + categoryPropertyString = categoryPropertyObj.ToString(); + } + if (categoryPropertyString != null && categoryPropertyString.Length > 0) + { + // Read the string property into a number + short shortVal; + if (SystemInfo.TryParse(categoryPropertyString, out shortVal)) + { + category = shortVal; + } + else + { + this.ErrorHandler.Error("Unable to parse event category property [" + categoryPropertyString + "]."); + } + } + } + } + + // Write to the event log + try + { + string eventTxt = this.RenderLoggingEvent(loggingEvent); + + // There is a limit of about 32K characters for an event log message + if (eventTxt.Length > MAX_EVENTLOG_MESSAGE_SIZE) + { + eventTxt = eventTxt.Substring(0, MAX_EVENTLOG_MESSAGE_SIZE); + } + + EventLogEntryType entryType = this.GetEntryType(loggingEvent.Level); + + using(this.SecurityContext.Impersonate(this)) + { + EventLog.WriteEntry(this.m_applicationName, eventTxt, entryType, eventID, category); + } + } + catch(Exception ex) + { + this.ErrorHandler.Error("Unable to write to event log [" + this.m_logName + "] using source [" + this.m_applicationName + "]", ex); + } + } + + /// + /// This appender requires a to be set. + /// + /// true + /// + /// + /// This appender requires a to be set. + /// + /// + protected override bool RequiresLayout + { + get { return true; } } - /// - /// Get the equivalent for a . - /// - /// the Level to convert to an EventLogEntryType. - /// The equivalent for a . - /// - /// Because there are fewer applicable - /// values to use in logging levels than there are in the - /// this is a one way mapping. There is - /// a loss of information during the conversion. - /// - protected virtual EventLogEntryType GetEntryType(Level level) - { - // see if there is a specified lookup. - Level2EventLogEntryType entryType = this.m_levelMapping.Lookup(level) as Level2EventLogEntryType; - if (entryType != null) - { - return entryType.EventLogEntryType; - } - - // Use default behavior - if (level >= Level.Error) - { - return EventLogEntryType.Error; - } - else if (level == Level.Warn) - { - return EventLogEntryType.Warning; - } - - // Default setting - return EventLogEntryType.Information; + /// + /// Get the equivalent for a + /// + /// the Level to convert to an EventLogEntryType + /// The equivalent for a + /// + /// Because there are fewer applicable + /// values to use in logging levels than there are in the + /// this is a one way mapping. There is + /// a loss of information during the conversion. + /// + protected virtual EventLogEntryType GetEntryType(Level level) + { + // see if there is a specified lookup. + Level2EventLogEntryType entryType = this.m_levelMapping.Lookup(level) as Level2EventLogEntryType; + if (entryType != null) + { + return entryType.EventLogEntryType; + } + + // Use default behavior + + if (level >= Level.Error) + { + return EventLogEntryType.Error; + } + else if (level == Level.Warn) + { + return EventLogEntryType.Warning; + } + + // Default setting + return EventLogEntryType.Information; } - /// - /// The log name is the section in the event logs where the messages - /// are stored. - /// - private string m_logName; - - /// - /// Name of the application to use when logging. This appears in the - /// application column of the event log named by . - /// - private string m_applicationName; - - /// - /// The name of the machine which holds the event log. This is - /// currently only allowed to be '.' i.e. the current machine. - /// - private string m_machineName; - - /// - /// Mapping from level object to EventLogEntryType. - /// - private LevelMapping m_levelMapping = new LevelMapping(); - - /// - /// The security context to use for privileged calls. - /// - private SecurityContext m_securityContext; - - /// - /// The event ID to use unless one is explicitly specified via the LoggingEvent's properties. - /// - private int m_eventId = 0; - - /// - /// The event category to use unless one is explicitly specified via the LoggingEvent's properties. - /// + /// + /// The log name is the section in the event logs where the messages + /// are stored. + /// + private string m_logName; + + /// + /// Name of the application to use when logging. This appears in the + /// application column of the event log named by . + /// + private string m_applicationName; + + /// + /// The name of the machine which holds the event log. This is + /// currently only allowed to be '.' i.e. the current machine. + /// + private string m_machineName; + + /// + /// Mapping from level object to EventLogEntryType + /// + private LevelMapping m_levelMapping = new LevelMapping(); + + /// + /// The security context to use for privileged calls + /// + private SecurityContext m_securityContext; + + /// + /// The event ID to use unless one is explicitly specified via the LoggingEvent's properties. + /// + private int m_eventId = 0; + + /// + /// The event category to use unless one is explicitly specified via the LoggingEvent's properties. + /// private short m_category = 0; - /// - /// A class to act as a mapping between the level that a logging call is made at and - /// the color it should be displayed as. - /// - /// - /// - /// Defines the mapping between a level and its event log entry type. - /// - /// - public class Level2EventLogEntryType : LevelMappingEntry - { - private EventLogEntryType m_entryType; - - /// - /// Gets or sets the for this entry. - /// - /// - /// - /// Required property. - /// The for this entry. - /// - /// - public EventLogEntryType EventLogEntryType - { - get { return this.m_entryType; } - set { this.m_entryType = value; } - } + /// + /// A class to act as a mapping between the level that a logging call is made at and + /// the color it should be displayed as. + /// + /// + /// + /// Defines the mapping between a level and its event log entry type. + /// + /// + public class Level2EventLogEntryType : LevelMappingEntry + { + private EventLogEntryType m_entryType; + + /// + /// The for this entry + /// + /// + /// + /// Required property. + /// The for this entry + /// + /// + public EventLogEntryType EventLogEntryType + { + get { return this.m_entryType; } + set { this.m_entryType = value; } + } } - /// - /// The fully qualified type of the EventLogAppender class. - /// - /// - /// Used by the internal logger to record the Type of the - /// log message. - /// - private static readonly Type declaringType = typeof(EventLogAppender); - - /// - /// The maximum size supported by default. - /// - /// - /// http://msdn.microsoft.com/en-us/library/xzwc042w(v=vs.100).aspx - /// The 32766 documented max size is two bytes shy of 32K (I'm assuming 32766 - /// may leave space for a two byte null terminator of #0#0). The 32766 max - /// length is what the .NET 4.0 source code checks for, but this is WRONG! - /// Strings with a length > 31839 on Windows Vista or higher can CORRUPT - /// the event log! See: System.Diagnostics.EventLogInternal.InternalWriteEvent() - /// for the use of the 32766 max size. - /// - private static readonly int MAX_EVENTLOG_MESSAGE_SIZE_DEFAULT = 32766; - - /// - /// The maximum size supported by a windows operating system that is vista - /// or newer. - /// - /// - /// See ReportEvent API: - /// http://msdn.microsoft.com/en-us/library/aa363679(VS.85).aspx - /// ReportEvent's lpStrings parameter: - /// "A pointer to a buffer containing an array of - /// null-terminated strings that are merged into the message before Event Viewer - /// displays the string to the user. This parameter must be a valid pointer - /// (or NULL), even if wNumStrings is zero. Each string is limited to 31,839 characters." - /// - /// Going beyond the size of 31839 will (at some point) corrupt the event log on Windows - /// Vista or higher! It may succeed for a while...but you will eventually run into the - /// error: "System.ComponentModel.Win32Exception : A device attached to the system is - /// not functioning", and the event log will then be corrupt (I was able to corrupt - /// an event log using a length of 31877 on Windows 7). - /// - /// The max size for Windows Vista or higher is documented here: - /// http://msdn.microsoft.com/en-us/library/xzwc042w(v=vs.100).aspx. - /// Going over this size may succeed a few times but the buffer will overrun and - /// eventually corrupt the log (based on testing). - /// - /// The maxEventMsgSize size is based on the max buffer size of the lpStrings parameter of the ReportEvent API. - /// The documented max size for EventLog.WriteEntry for Windows Vista and higher is 31839, but I'm leaving room for a - /// terminator of #0#0, as we cannot see the source of ReportEvent (though we could use an API monitor to examine the - /// buffer, given enough time). - /// - private static readonly int MAX_EVENTLOG_MESSAGE_SIZE_VISTA_OR_NEWER = 31839 - 2; - - /// - /// The maximum size that the operating system supports for - /// a event log message. - /// - /// - /// Used to determine the maximum string length that can be written - /// to the operating system event log and eventually truncate a string - /// that exceeds the limits. - /// - private static readonly int MAX_EVENTLOG_MESSAGE_SIZE = GetMaxEventLogMessageSize(); - - /// - /// This method determines the maximum event log message size allowed for - /// the current environment. - /// - /// - private static int GetMaxEventLogMessageSize() - { + /// + /// The fully qualified type of the EventLogAppender class. + /// + /// + /// Used by the internal logger to record the Type of the + /// log message. + /// + private static readonly Type declaringType = typeof(EventLogAppender); + + /// + /// The maximum size supported by default. + /// + /// + /// http://msdn.microsoft.com/en-us/library/xzwc042w(v=vs.100).aspx + /// The 32766 documented max size is two bytes shy of 32K (I'm assuming 32766 + /// may leave space for a two byte null terminator of #0#0). The 32766 max + /// length is what the .NET 4.0 source code checks for, but this is WRONG! + /// Strings with a length > 31839 on Windows Vista or higher can CORRUPT + /// the event log! See: System.Diagnostics.EventLogInternal.InternalWriteEvent() + /// for the use of the 32766 max size. + /// + private static readonly int MAX_EVENTLOG_MESSAGE_SIZE_DEFAULT = 32766; + + /// + /// The maximum size supported by a windows operating system that is vista + /// or newer. + /// + /// + /// See ReportEvent API: + /// http://msdn.microsoft.com/en-us/library/aa363679(VS.85).aspx + /// ReportEvent's lpStrings parameter: + /// "A pointer to a buffer containing an array of + /// null-terminated strings that are merged into the message before Event Viewer + /// displays the string to the user. This parameter must be a valid pointer + /// (or NULL), even if wNumStrings is zero. Each string is limited to 31,839 characters." + /// + /// Going beyond the size of 31839 will (at some point) corrupt the event log on Windows + /// Vista or higher! It may succeed for a while...but you will eventually run into the + /// error: "System.ComponentModel.Win32Exception : A device attached to the system is + /// not functioning", and the event log will then be corrupt (I was able to corrupt + /// an event log using a length of 31877 on Windows 7). + /// + /// The max size for Windows Vista or higher is documented here: + /// http://msdn.microsoft.com/en-us/library/xzwc042w(v=vs.100).aspx. + /// Going over this size may succeed a few times but the buffer will overrun and + /// eventually corrupt the log (based on testing). + /// + /// The maxEventMsgSize size is based on the max buffer size of the lpStrings parameter of the ReportEvent API. + /// The documented max size for EventLog.WriteEntry for Windows Vista and higher is 31839, but I'm leaving room for a + /// terminator of #0#0, as we cannot see the source of ReportEvent (though we could use an API monitor to examine the + /// buffer, given enough time). + /// + private static readonly int MAX_EVENTLOG_MESSAGE_SIZE_VISTA_OR_NEWER = 31839 - 2; + + /// + /// The maximum size that the operating system supports for + /// a event log message. + /// + /// + /// Used to determine the maximum string length that can be written + /// to the operating system event log and eventually truncate a string + /// that exceeds the limits. + /// + private static readonly int MAX_EVENTLOG_MESSAGE_SIZE = GetMaxEventLogMessageSize(); + + /// + /// This method determines the maximum event log message size allowed for + /// the current environment. + /// + /// + private static int GetMaxEventLogMessageSize() + { if (Environment.OSVersion.Platform == PlatformID.Win32NT && Environment.OSVersion.Version.Major >= 6) { return MAX_EVENTLOG_MESSAGE_SIZE_VISTA_OR_NEWER; } - return MAX_EVENTLOG_MESSAGE_SIZE_DEFAULT; + return MAX_EVENTLOG_MESSAGE_SIZE_DEFAULT; } - } -} - -#endif // !SSCLI -#endif // !NETCF + } +} + +#endif // !SSCLI +#endif // !NETCF +#endif // NET_2_0 diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/FileAppender.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/FileAppender.cs index 373a9e4bb57..9c3c6e79276 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/FileAppender.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/FileAppender.cs @@ -1,1478 +1,1476 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +using System; +using System.IO; +#if !NETCF && !NETSTANDARD1_3 +using System.Runtime.Serialization; +#endif +using System.Text; +using System.Threading; +using log4net.Util; +using log4net.Layout; +using log4net.Core; +#if NET_4_5 || NETSTANDARD +using System.Threading.Tasks; +#endif -#if NET_4_5 || NETSTANDARD1_3 -using System.Threading.Tasks; - -#endif - -namespace log4net.Appender -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; - using System.IO; - using System.Text; - using System.Threading; - - using log4net.Core; - using log4net.Layout; - using log4net.Util; - -#if !NETCF - /// - /// Appends logging events to a file. - /// - /// - /// - /// Logging events are sent to the file specified by - /// the property. - /// - /// - /// The file can be opened in either append or overwrite mode - /// by specifying the property. - /// If the file path is relative it is taken as relative from - /// the application base directory. The file encoding can be - /// specified by setting the property. - /// - /// - /// The layout's and - /// values will be written each time the file is opened and closed - /// respectively. If the property is - /// then the file may contain multiple copies of the header and footer. - /// - /// - /// This appender will first try to open the file for writing when - /// is called. This will typically be during configuration. - /// If the file cannot be opened for writing the appender will attempt - /// to open the file again each time a message is logged to the appender. - /// If the file cannot be opened for writing when a message is logged then - /// the message will be discarded by this appender. - /// - /// - /// The supports pluggable file locking models via - /// the property. - /// The default behavior, implemented by - /// is to obtain an exclusive write lock on the file until this appender is closed. - /// The alternative models only hold a - /// write lock while the appender is writing a logging event () - /// or synchronize by using a named system wide Mutex (). - /// - /// - /// All locking strategies have issues and you should seriously consider using a different strategy that - /// avoids having multiple processes logging to the same file. - /// - /// - /// Nicko Cadell. - /// Gert Driesen. - /// Rodrigo B. de Oliveira. - /// Douglas de la Torre. - /// Niall Daley. -#else - /// - /// Appends logging events to a file. - /// - /// - /// - /// Logging events are sent to the file specified by - /// the property. - /// - /// - /// The file can be opened in either append or overwrite mode - /// by specifying the property. - /// If the file path is relative it is taken as relative from - /// the application base directory. The file encoding can be - /// specified by setting the property. - /// - /// - /// The layout's and - /// values will be written each time the file is opened and closed - /// respectively. If the property is - /// then the file may contain multiple copies of the header and footer. - /// - /// - /// This appender will first try to open the file for writing when - /// is called. This will typically be during configuration. - /// If the file cannot be opened for writing the appender will attempt - /// to open the file again each time a message is logged to the appender. - /// If the file cannot be opened for writing when a message is logged then - /// the message will be discarded by this appender. - /// - /// - /// The supports pluggable file locking models via - /// the property. - /// The default behavior, implemented by - /// is to obtain an exclusive write lock on the file until this appender is closed. - /// The alternative model only holds a - /// write lock while the appender is writing a logging event (). - /// - /// - /// All locking strategies have issues and you should seriously consider using a different strategy that - /// avoids having multiple processes logging to the same file. - /// - /// - /// Nicko Cadell - /// Gert Driesen - /// Rodrigo B. de Oliveira - /// Douglas de la Torre - /// Niall Daley -#endif - public class FileAppender : TextWriterAppender +namespace log4net.Appender +{ +#if !NETCF + /// + /// Appends logging events to a file. + /// + /// + /// + /// Logging events are sent to the file specified by + /// the property. + /// + /// + /// The file can be opened in either append or overwrite mode + /// by specifying the property. + /// If the file path is relative it is taken as relative from + /// the application base directory. The file encoding can be + /// specified by setting the property. + /// + /// + /// The layout's and + /// values will be written each time the file is opened and closed + /// respectively. If the property is + /// then the file may contain multiple copies of the header and footer. + /// + /// + /// This appender will first try to open the file for writing when + /// is called. This will typically be during configuration. + /// If the file cannot be opened for writing the appender will attempt + /// to open the file again each time a message is logged to the appender. + /// If the file cannot be opened for writing when a message is logged then + /// the message will be discarded by this appender. + /// + /// + /// The supports pluggable file locking models via + /// the property. + /// The default behavior, implemented by + /// is to obtain an exclusive write lock on the file until this appender is closed. + /// The alternative models only hold a + /// write lock while the appender is writing a logging event () + /// or synchronize by using a named system wide Mutex (). + /// + /// + /// All locking strategies have issues and you should seriously consider using a different strategy that + /// avoids having multiple processes logging to the same file. + /// + /// + /// Nicko Cadell + /// Gert Driesen + /// Rodrigo B. de Oliveira + /// Douglas de la Torre + /// Niall Daley +#else + /// + /// Appends logging events to a file. + /// + /// + /// + /// Logging events are sent to the file specified by + /// the property. + /// + /// + /// The file can be opened in either append or overwrite mode + /// by specifying the property. + /// If the file path is relative it is taken as relative from + /// the application base directory. The file encoding can be + /// specified by setting the property. + /// + /// + /// The layout's and + /// values will be written each time the file is opened and closed + /// respectively. If the property is + /// then the file may contain multiple copies of the header and footer. + /// + /// + /// This appender will first try to open the file for writing when + /// is called. This will typically be during configuration. + /// If the file cannot be opened for writing the appender will attempt + /// to open the file again each time a message is logged to the appender. + /// If the file cannot be opened for writing when a message is logged then + /// the message will be discarded by this appender. + /// + /// + /// The supports pluggable file locking models via + /// the property. + /// The default behavior, implemented by + /// is to obtain an exclusive write lock on the file until this appender is closed. + /// The alternative model only holds a + /// write lock while the appender is writing a logging event (). + /// + /// + /// All locking strategies have issues and you should seriously consider using a different strategy that + /// avoids having multiple processes logging to the same file. + /// + /// + /// Nicko Cadell + /// Gert Driesen + /// Rodrigo B. de Oliveira + /// Douglas de la Torre + /// Niall Daley +#endif + public class FileAppender : TextWriterAppender { - /// - /// Write only that uses the - /// to manage access to an underlying resource. - /// - private sealed class LockingStream : Stream, IDisposable - { - public sealed class LockStateException : LogException - { - public LockStateException(string message) - : base(message) - { - } - } - - private Stream m_realStream = null; - private LockingModelBase m_lockingModel = null; - private int m_lockLevel = 0; - - public LockingStream(LockingModelBase locking) - : base() - { - if (locking == null) - { - throw new ArgumentException("Locking model may not be null", "locking"); - } - - this.m_lockingModel = locking; + /// + /// Write only that uses the + /// to manage access to an underlying resource. + /// + private sealed class LockingStream : Stream, IDisposable + { +#if !NETCR + [Serializable] +#endif + public sealed class LockStateException : LogException + { + public LockStateException(string message) + : base(message) + { + } + + public LockStateException() + { + } + + public LockStateException(string message, Exception innerException) : base(message, innerException) + { + } + +#if !NETCR && !NETSTANDARD1_3 + private LockStateException(SerializationInfo info, StreamingContext context) : base(info, context) + { + } +#endif + } + + private Stream m_realStream = null; + private LockingModelBase m_lockingModel = null; + private int m_lockLevel = 0; + + public LockingStream(LockingModelBase locking) + : base() + { + if (locking == null) + { + throw new ArgumentException("Locking model may not be null", "locking"); + } + + this.m_lockingModel = locking; + } + +#if NETSTANDARD + protected override void Dispose(bool disposing) + { + m_lockingModel.CloseFile(); + base.Dispose(disposing); + } +#else + + private int m_readTotal = -1; + + // Methods + public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state) + { + this.AssertLocked(); + IAsyncResult ret = this.m_realStream.BeginRead(buffer, offset, count, callback, state); + this.m_readTotal = this.EndRead(ret); + return ret; + } + + /// + /// True asynchronous writes are not supported, the implementation forces a synchronous write. + /// + public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state) + { + this.AssertLocked(); + IAsyncResult ret = this.m_realStream.BeginWrite(buffer, offset, count, callback, state); + this.EndWrite(ret); + return ret; + } + + public override void Close() + { + this.m_lockingModel.CloseFile(); + } + + public override int EndRead(IAsyncResult asyncResult) + { + this.AssertLocked(); + return this.m_readTotal; + } + public override void EndWrite(IAsyncResult asyncResult) + { + //No-op, it has already been handled + } +#endif + +#if NET_4_5 || NETSTANDARD + public override Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) + { + this.AssertLocked(); + return this.m_realStream.ReadAsync(buffer, offset, count, cancellationToken); + } + + public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) + { + this.AssertLocked(); + return base.WriteAsync(buffer, offset, count, cancellationToken); + } +#endif + + public override void Flush() + { + this.AssertLocked(); + this.m_realStream.Flush(); + } + public override int Read(byte[] buffer, int offset, int count) + { + return this.m_realStream.Read(buffer, offset, count); + } + public override int ReadByte() + { + return this.m_realStream.ReadByte(); + } + public override long Seek(long offset, SeekOrigin origin) + { + this.AssertLocked(); + return this.m_realStream.Seek(offset, origin); + } + public override void SetLength(long value) + { + this.AssertLocked(); + this.m_realStream.SetLength(value); + } + void IDisposable.Dispose() + { +#if NETSTANDARD + Dispose(true); +#else + this.Close(); +#endif + } + public override void Write(byte[] buffer, int offset, int count) + { + this.AssertLocked(); + this.m_realStream.Write(buffer, offset, count); + } + public override void WriteByte(byte value) + { + this.AssertLocked(); + this.m_realStream.WriteByte(value); + } + + // Properties + public override bool CanRead + { + get { return false; } + } + public override bool CanSeek + { + get + { + this.AssertLocked(); + return this.m_realStream.CanSeek; + } + } + public override bool CanWrite + { + get + { + this.AssertLocked(); + return this.m_realStream.CanWrite; + } + } + public override long Length + { + get + { + this.AssertLocked(); + return this.m_realStream.Length; + } + } + public override long Position + { + get + { + this.AssertLocked(); + return this.m_realStream.Position; + } + set + { + this.AssertLocked(); + this.m_realStream.Position = value; + } + } + + private void AssertLocked() + { + if (this.m_realStream == null) + { + throw new LockStateException("The file is not currently locked"); + } + } + + public bool AcquireLock() + { + bool ret = false; + lock (this) + { + if (this.m_lockLevel == 0) + { + // If lock is already acquired, nop + this.m_realStream = this.m_lockingModel.AcquireLock(); + } + if (this.m_realStream != null) + { + this.m_lockLevel++; + ret = true; + } + } + return ret; + } + + public void ReleaseLock() + { + lock (this) + { + this.m_lockLevel--; + if (this.m_lockLevel == 0) + { + // If already unlocked, nop + this.m_lockingModel.ReleaseLock(); + this.m_realStream = null; + } + } + } + } + + /// + /// Locking model base class + /// + /// + /// + /// Base class for the locking models available to the derived loggers. + /// + /// + public abstract class LockingModelBase + { + private FileAppender m_appender = null; + + /// + /// Open the output file + /// + /// The filename to use + /// Whether to append to the file, or overwrite + /// The encoding to use + /// + /// + /// Open the file specified and prepare for logging. + /// No writes will be made until is called. + /// Must be called before any calls to , + /// and . + /// + /// + public abstract void OpenFile(string filename, bool append, Encoding encoding); + + /// + /// Close the file + /// + /// + /// + /// Close the file. No further writes will be made. + /// + /// + public abstract void CloseFile(); + + /// + /// Initializes all resources used by this locking model. + /// + public abstract void ActivateOptions(); + + /// + /// Disposes all resources that were initialized by this locking model. + /// + public abstract void OnClose(); + + /// + /// Acquire the lock on the file + /// + /// A stream that is ready to be written to. + /// + /// + /// Acquire the lock on the file in preparation for writing to it. + /// Return a stream pointing to the file. + /// must be called to release the lock on the output file. + /// + /// + public abstract Stream AcquireLock(); + + /// + /// Release the lock on the file + /// + /// + /// + /// Release the lock on the file. No further writes will be made to the + /// stream until is called again. + /// + /// + public abstract void ReleaseLock(); + + /// + /// Gets or sets the for this LockingModel + /// + /// + /// The for this LockingModel + /// + /// + /// + /// The file appender this locking model is attached to and working on + /// behalf of. + /// + /// + /// The file appender is used to locate the security context and the error handler to use. + /// + /// + /// The value of this property will be set before is + /// called. + /// + /// + public FileAppender CurrentAppender + { + get { return this.m_appender; } + set { this.m_appender = value; } } -#if NETSTANDARD1_3 - protected override void Dispose(bool disposing) - { - m_lockingModel.CloseFile(); - base.Dispose(disposing); - } -#else - - private int m_readTotal = -1; - - // Methods - public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state) - { - this.AssertLocked(); - IAsyncResult ret = this.m_realStream.BeginRead(buffer, offset, count, callback, state); - this.m_readTotal = this.EndRead(ret); - return ret; - } - - /// - /// True asynchronous writes are not supported, the implementation forces a synchronous write. - /// - public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state) - { - this.AssertLocked(); - IAsyncResult ret = this.m_realStream.BeginWrite(buffer, offset, count, callback, state); - this.EndWrite(ret); - return ret; - } - - public override void Close() - { - this.m_lockingModel.CloseFile(); - } - - public override int EndRead(IAsyncResult asyncResult) - { - this.AssertLocked(); - return this.m_readTotal; - } - - public override void EndWrite(IAsyncResult asyncResult) - { - // No-op, it has already been handled - } -#endif - -#if NET_4_5 || NETSTANDARD1_3 - public override Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) - { - this.AssertLocked(); - return this.m_realStream.ReadAsync(buffer, offset, count, cancellationToken); - } - - public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) - { - this.AssertLocked(); - return base.WriteAsync(buffer, offset, count, cancellationToken); - } -#endif - - public override void Flush() - { - this.AssertLocked(); - this.m_realStream.Flush(); - } - - public override int Read(byte[] buffer, int offset, int count) - { - return this.m_realStream.Read(buffer, offset, count); - } - - public override int ReadByte() - { - return this.m_realStream.ReadByte(); - } - - public override long Seek(long offset, SeekOrigin origin) - { - this.AssertLocked(); - return this.m_realStream.Seek(offset, origin); - } - - public override void SetLength(long value) - { - this.AssertLocked(); - this.m_realStream.SetLength(value); - } - - void IDisposable.Dispose() - { -#if NETSTANDARD1_3 - Dispose(true); -#else - this.Close(); -#endif - } - - public override void Write(byte[] buffer, int offset, int count) - { - this.AssertLocked(); - this.m_realStream.Write(buffer, offset, count); - } - - public override void WriteByte(byte value) - { - this.AssertLocked(); - this.m_realStream.WriteByte(value); - } - - // Properties - public override bool CanRead - { - get { return false; } - } - - public override bool CanSeek - { - get - { - this.AssertLocked(); - return this.m_realStream.CanSeek; - } - } - - public override bool CanWrite - { - get - { - this.AssertLocked(); - return this.m_realStream.CanWrite; - } - } - - public override long Length - { - get - { - this.AssertLocked(); - return this.m_realStream.Length; - } - } - - public override long Position - { - get - { - this.AssertLocked(); - return this.m_realStream.Position; - } - - set - { - this.AssertLocked(); - this.m_realStream.Position = value; - } + /// + /// Helper method that creates a FileStream under CurrentAppender's SecurityContext. + /// + /// + /// + /// Typically called during OpenFile or AcquireLock. + /// + /// + /// If the directory portion of the does not exist, it is created + /// via Directory.CreateDirecctory. + /// + /// + /// + /// + /// + /// + protected Stream CreateStream(string filename, bool append, FileShare fileShare) + { + using (this.CurrentAppender.SecurityContext.Impersonate(this)) + { + // Ensure that the directory structure exists + string directoryFullName = Path.GetDirectoryName(filename); + + // Only create the directory if it does not exist + // doing this check here resolves some permissions failures + if (!Directory.Exists(directoryFullName)) + { + Directory.CreateDirectory(directoryFullName); + } + + FileMode fileOpenMode = append ? FileMode.Append : FileMode.Create; + return new FileStream(filename, fileOpenMode, FileAccess.Write, fileShare); + } } - private void AssertLocked() - { - if (this.m_realStream == null) - { - throw new LockStateException("The file is not currently locked"); - } - } - - public bool AcquireLock() - { - bool ret = false; - lock (this) - { - if (this.m_lockLevel == 0) - { - // If lock is already acquired, nop - this.m_realStream = this.m_lockingModel.AcquireLock(); - } - - if (this.m_realStream != null) - { - this.m_lockLevel++; - ret = true; - } - } - - return ret; - } - - public void ReleaseLock() - { - lock (this) - { - this.m_lockLevel--; - if (this.m_lockLevel == 0) - { - // If already unlocked, nop - this.m_lockingModel.ReleaseLock(); - this.m_realStream = null; - } - } + /// + /// Helper method to close under CurrentAppender's SecurityContext. + /// + /// + /// Does not set to null. + /// + /// + protected void CloseStream(Stream stream) + { + using (this.CurrentAppender.SecurityContext.Impersonate(this)) + { + stream.Dispose(); + } } } - /// - /// Locking model base class. - /// - /// - /// - /// Base class for the locking models available to the derived loggers. - /// - /// - public abstract class LockingModelBase - { - private FileAppender m_appender = null; - - /// - /// Open the output file. - /// - /// The filename to use. - /// Whether to append to the file, or overwrite. - /// The encoding to use. - /// - /// - /// Open the file specified and prepare for logging. - /// No writes will be made until is called. - /// Must be called before any calls to , - /// and . - /// - /// - public abstract void OpenFile(string filename, bool append, Encoding encoding); - - /// - /// Close the file. - /// - /// - /// - /// Close the file. No further writes will be made. - /// - /// - public abstract void CloseFile(); - - /// - /// Initializes all resources used by this locking model. - /// - public abstract void ActivateOptions(); - - /// - /// Disposes all resources that were initialized by this locking model. - /// - public abstract void OnClose(); - - /// - /// Acquire the lock on the file. - /// - /// A stream that is ready to be written to. - /// - /// - /// Acquire the lock on the file in preparation for writing to it. - /// Return a stream pointing to the file. - /// must be called to release the lock on the output file. - /// - /// - public abstract Stream AcquireLock(); - - /// - /// Release the lock on the file. - /// - /// - /// - /// Release the lock on the file. No further writes will be made to the - /// stream until is called again. - /// - /// - public abstract void ReleaseLock(); - - /// - /// Gets or sets the for this LockingModel. - /// - /// - /// The for this LockingModel. - /// - /// - /// - /// The file appender this locking model is attached to and working on - /// behalf of. - /// - /// - /// The file appender is used to locate the security context and the error handler to use. - /// - /// - /// The value of this property will be set before is - /// called. - /// - /// - public FileAppender CurrentAppender - { - get { return this.m_appender; } - set { this.m_appender = value; } - } - - /// - /// Helper method that creates a FileStream under CurrentAppender's SecurityContext. - /// - /// - /// - /// Typically called during OpenFile or AcquireLock. - /// - /// - /// If the directory portion of the does not exist, it is created - /// via Directory.CreateDirecctory. - /// - /// - /// - /// - /// - /// - protected Stream CreateStream(string filename, bool append, FileShare fileShare) - { - using (this.CurrentAppender.SecurityContext.Impersonate(this)) - { - // Ensure that the directory structure exists - string directoryFullName = Path.GetDirectoryName(filename); - - // Only create the directory if it does not exist - // doing this check here resolves some permissions failures - if (!Directory.Exists(directoryFullName)) - { - Directory.CreateDirectory(directoryFullName); - } - - FileMode fileOpenMode = append ? FileMode.Append : FileMode.Create; - return new FileStream(filename, fileOpenMode, FileAccess.Write, fileShare); - } - } - - /// - /// Helper method to close under CurrentAppender's SecurityContext. - /// - /// - /// Does not set to null. - /// - /// - protected void CloseStream(Stream stream) - { - using (this.CurrentAppender.SecurityContext.Impersonate(this)) - { - stream.Close(); - } - } - } - - /// - /// Hold an exclusive lock on the output file. - /// - /// - /// - /// Open the file once for writing and hold it open until is called. - /// Maintains an exclusive lock on the file during this time. - /// - /// - public class ExclusiveLock : LockingModelBase - { - private Stream m_stream = null; - - /// - /// Open the file specified and prepare for logging. - /// - /// The filename to use. - /// Whether to append to the file, or overwrite. - /// The encoding to use. - /// - /// - /// Open the file specified and prepare for logging. - /// No writes will be made until is called. - /// Must be called before any calls to , - /// and . - /// - /// - public override void OpenFile(string filename, bool append, Encoding encoding) - { - try - { - this.m_stream = this.CreateStream(filename, append, FileShare.Read); - } - catch (Exception e1) - { - this.CurrentAppender.ErrorHandler.Error("Unable to acquire lock on file " + filename + ". " + e1.Message); - } - } - - /// - /// Close the file. - /// - /// - /// - /// Close the file. No further writes will be made. - /// - /// - public override void CloseFile() - { - this.CloseStream(this.m_stream); - this.m_stream = null; - } - - /// - /// Acquire the lock on the file. - /// - /// A stream that is ready to be written to. - /// - /// - /// Does nothing. The lock is already taken. - /// - /// - public override Stream AcquireLock() - { - return this.m_stream; - } - - /// - /// Release the lock on the file. - /// - /// - /// - /// Does nothing. The lock will be released when the file is closed. - /// - /// - public override void ReleaseLock() - { - // NOP - } - - /// - /// Initializes all resources used by this locking model. - /// - public override void ActivateOptions() - { - // NOP - } - - /// - /// Disposes all resources that were initialized by this locking model. - /// - public override void OnClose() - { - // NOP - } - } - - /// - /// Acquires the file lock for each write. - /// - /// - /// - /// Opens the file once for each / cycle, - /// thus holding the lock for the minimal amount of time. This method of locking - /// is considerably slower than but allows - /// other processes to move/delete the log file whilst logging continues. - /// - /// - public class MinimalLock : LockingModelBase - { - private string m_filename; - private bool m_append; - private Stream m_stream = null; - - /// - /// Prepares to open the file when the first message is logged. - /// - /// The filename to use. - /// Whether to append to the file, or overwrite. - /// The encoding to use. - /// - /// - /// Open the file specified and prepare for logging. - /// No writes will be made until is called. - /// Must be called before any calls to , - /// and . - /// - /// - public override void OpenFile(string filename, bool append, Encoding encoding) - { - this.m_filename = filename; - this.m_append = append; - } - - /// - /// Close the file. - /// - /// - /// - /// Close the file. No further writes will be made. - /// - /// - public override void CloseFile() - { - // NOP - } - - /// - /// Acquire the lock on the file. - /// - /// A stream that is ready to be written to. - /// - /// - /// Acquire the lock on the file in preparation for writing to it. - /// Return a stream pointing to the file. - /// must be called to release the lock on the output file. - /// - /// - public override Stream AcquireLock() - { - if (this.m_stream == null) - { - try - { - this.m_stream = this.CreateStream(this.m_filename, this.m_append, FileShare.Read); - this.m_append = true; - } - catch (Exception e1) - { - this.CurrentAppender.ErrorHandler.Error("Unable to acquire lock on file " + this.m_filename + ". " + e1.Message); - } - } - - return this.m_stream; - } - - /// - /// Release the lock on the file. - /// - /// - /// - /// Release the lock on the file. No further writes will be made to the - /// stream until is called again. - /// - /// - public override void ReleaseLock() - { - this.CloseStream(this.m_stream); - this.m_stream = null; - } - - /// - /// Initializes all resources used by this locking model. - /// - public override void ActivateOptions() - { - // NOP - } - - /// - /// Disposes all resources that were initialized by this locking model. - /// - public override void OnClose() - { - // NOP - } - } - -#if !NETCF - /// - /// Provides cross-process file locking. - /// - /// Ron Grabowski. - /// Steve Wranovsky. - public class InterProcessLock : LockingModelBase - { - private Mutex m_mutex = null; - private Stream m_stream = null; + /// + /// Hold an exclusive lock on the output file + /// + /// + /// + /// Open the file once for writing and hold it open until is called. + /// Maintains an exclusive lock on the file during this time. + /// + /// + public class ExclusiveLock : LockingModelBase + { + private Stream m_stream = null; + + /// + /// Open the file specified and prepare for logging. + /// + /// The filename to use + /// Whether to append to the file, or overwrite + /// The encoding to use + /// + /// + /// Open the file specified and prepare for logging. + /// No writes will be made until is called. + /// Must be called before any calls to , + /// and . + /// + /// + public override void OpenFile(string filename, bool append, Encoding encoding) + { + try + { + this.m_stream = this.CreateStream(filename, append, FileShare.Read); + } + catch (Exception e1) + { + this.CurrentAppender.ErrorHandler.Error("Unable to acquire lock on file " + filename + ". " + e1.Message); + } + } + + /// + /// Close the file + /// + /// + /// + /// Close the file. No further writes will be made. + /// + /// + public override void CloseFile() + { + this.CloseStream(this.m_stream); + this.m_stream = null; + } + + /// + /// Acquire the lock on the file + /// + /// A stream that is ready to be written to. + /// + /// + /// Does nothing. The lock is already taken + /// + /// + public override Stream AcquireLock() + { + return this.m_stream; + } + + /// + /// Release the lock on the file + /// + /// + /// + /// Does nothing. The lock will be released when the file is closed. + /// + /// + public override void ReleaseLock() + { + //NOP + } + + /// + /// Initializes all resources used by this locking model. + /// + public override void ActivateOptions() + { + //NOP + } + + /// + /// Disposes all resources that were initialized by this locking model. + /// + public override void OnClose() + { + //NOP + } + } + + /// + /// Acquires the file lock for each write + /// + /// + /// + /// Opens the file once for each / cycle, + /// thus holding the lock for the minimal amount of time. This method of locking + /// is considerably slower than but allows + /// other processes to move/delete the log file whilst logging continues. + /// + /// + public class MinimalLock : LockingModelBase + { + private string m_filename; + private bool m_append; + private Stream m_stream = null; + + /// + /// Prepares to open the file when the first message is logged. + /// + /// The filename to use + /// Whether to append to the file, or overwrite + /// The encoding to use + /// + /// + /// Open the file specified and prepare for logging. + /// No writes will be made until is called. + /// Must be called before any calls to , + /// and . + /// + /// + public override void OpenFile(string filename, bool append, Encoding encoding) + { + this.m_filename = filename; + this.m_append = append; + } + + /// + /// Close the file + /// + /// + /// + /// Close the file. No further writes will be made. + /// + /// + public override void CloseFile() + { + // NOP + } + + /// + /// Acquire the lock on the file + /// + /// A stream that is ready to be written to. + /// + /// + /// Acquire the lock on the file in preparation for writing to it. + /// Return a stream pointing to the file. + /// must be called to release the lock on the output file. + /// + /// + public override Stream AcquireLock() + { + if (this.m_stream == null) + { + try + { + this.m_stream = this.CreateStream(this.m_filename, this.m_append, FileShare.Read); + this.m_append = true; + } + catch (Exception e1) + { + this.CurrentAppender.ErrorHandler.Error("Unable to acquire lock on file " + this.m_filename + ". " + e1.Message); + } + } + return this.m_stream; + } + + /// + /// Release the lock on the file + /// + /// + /// + /// Release the lock on the file. No further writes will be made to the + /// stream until is called again. + /// + /// + public override void ReleaseLock() + { + this.CloseStream(this.m_stream); + this.m_stream = null; + } + + /// + /// Initializes all resources used by this locking model. + /// + public override void ActivateOptions() + { + //NOP + } + + /// + /// Disposes all resources that were initialized by this locking model. + /// + public override void OnClose() + { + //NOP + } + } + +#if !NETCF + /// + /// Provides cross-process file locking. + /// + /// Ron Grabowski + /// Steve Wranovsky + public class InterProcessLock : LockingModelBase + { + private Mutex m_mutex = null; + private Stream m_stream = null; private int m_recursiveWatch = 0; - /// - /// Open the file specified and prepare for logging. - /// - /// The filename to use. - /// Whether to append to the file, or overwrite. - /// The encoding to use. - /// - /// - /// Open the file specified and prepare for logging. - /// No writes will be made until is called. - /// Must be called before any calls to , - /// - and . - /// - /// -#if NET_4_0 || MONO_4_0 || NETSTANDARD1_3 - [System.Security.SecuritySafeCritical] -#endif - public override void OpenFile(string filename, bool append, Encoding encoding) - { - try - { - this.m_stream = this.CreateStream(filename, append, FileShare.ReadWrite); - } - catch (Exception e1) - { - this.CurrentAppender.ErrorHandler.Error("Unable to acquire lock on file " + filename + ". " + e1.Message); - } - } - - /// - /// Close the file. - /// - /// - /// - /// Close the file. No further writes will be made. - /// - /// - public override void CloseFile() - { - try - { - this.CloseStream(this.m_stream); - this.m_stream = null; - } - finally - { - this.ReleaseLock(); - } - } - - /// - /// Acquire the lock on the file. - /// - /// A stream that is ready to be written to. - /// - /// - /// Does nothing. The lock is already taken. - /// - /// - public override Stream AcquireLock() - { - if (this.m_mutex != null) - { - // TODO: add timeout? - this.m_mutex.WaitOne(); - - // increment recursive watch - this.m_recursiveWatch++; - - // should always be true (and fast) for FileStream - if (this.m_stream != null) - { - if (this.m_stream.CanSeek) - { - this.m_stream.Seek(0, SeekOrigin.End); - } - } - else - { - // this can happen when the file appender cannot open a file for writing - } - } - else - { - this.CurrentAppender.ErrorHandler.Error("Programming error, no mutex available to acquire lock! From here on things will be dangerous!"); - } - - return this.m_stream; - } - - /// - /// Releases the lock and allows others to acquire a lock. - /// - public override void ReleaseLock() - { - if (this.m_mutex != null) - { - if (this.m_recursiveWatch > 0) - { - this.m_recursiveWatch--; - this.m_mutex.ReleaseMutex(); - } - } - else - { - this.CurrentAppender.ErrorHandler.Error("Programming error, no mutex available to release the lock!"); - } - } - - /// - /// Initializes all resources used by this locking model. - /// - public override void ActivateOptions() - { - if (this.m_mutex == null) - { - string mutexFriendlyFilename = this.CurrentAppender.File - .Replace("\\", "_") - .Replace(":", "_") - .Replace("/", "_"); - - this.m_mutex = new Mutex(false, mutexFriendlyFilename); - } - else - { - this.CurrentAppender.ErrorHandler.Error("Programming error, mutex already initialized!"); - } - } - - /// - /// Disposes all resources that were initialized by this locking model. - /// - public override void OnClose() - { - if (this.m_mutex != null) - { -#if NET_4_0 || MONO_4_0 || NETSTANDARD1_3 - this.m_mutex.Dispose(); -#else - m_mutex.Close(); -#endif - this.m_mutex = null; - } - else - { - this.CurrentAppender.ErrorHandler.Error("Programming error, mutex not initialized!"); - } - } + /// + /// Open the file specified and prepare for logging. + /// + /// The filename to use + /// Whether to append to the file, or overwrite + /// The encoding to use + /// + /// + /// Open the file specified and prepare for logging. + /// No writes will be made until is called. + /// Must be called before any calls to , + /// - and . + /// + /// +#if NET_4_0 || MONO_4_0 || NETSTANDARD + [System.Security.SecuritySafeCritical] +#endif + public override void OpenFile(string filename, bool append, Encoding encoding) + { + try + { + this.m_stream = this.CreateStream(filename, append, FileShare.ReadWrite); + } + catch (Exception e1) + { + this.CurrentAppender.ErrorHandler.Error("Unable to acquire lock on file " + filename + ". " + e1.Message); + } + } + + /// + /// Close the file + /// + /// + /// + /// Close the file. No further writes will be made. + /// + /// + public override void CloseFile() + { + try + { + this.CloseStream(this.m_stream); + this.m_stream = null; + } + finally + { + this.ReleaseLock(); + } + } + + /// + /// Acquire the lock on the file + /// + /// A stream that is ready to be written to. + /// + /// + /// Does nothing. The lock is already taken + /// + /// + public override Stream AcquireLock() + { + if (this.m_mutex != null) + { + // TODO: add timeout? + this.m_mutex.WaitOne(); + + // increment recursive watch + this.m_recursiveWatch++; + + // should always be true (and fast) for FileStream + if (this.m_stream != null) + { + if (this.m_stream.CanSeek) + { + this.m_stream.Seek(0, SeekOrigin.End); + } + } + else + { + // this can happen when the file appender cannot open a file for writing + } + } + else + { + this.CurrentAppender.ErrorHandler.Error("Programming error, no mutex available to acquire lock! From here on things will be dangerous!"); + } + return this.m_stream; + } + + /// + /// Releases the lock and allows others to acquire a lock. + /// + public override void ReleaseLock() + { + if (this.m_mutex != null) + { + if (this.m_recursiveWatch > 0) + { + this.m_recursiveWatch--; + this.m_mutex.ReleaseMutex(); + } + } + else + { + this.CurrentAppender.ErrorHandler.Error("Programming error, no mutex available to release the lock!"); + } + } + + /// + /// Initializes all resources used by this locking model. + /// + public override void ActivateOptions() + { + if (this.m_mutex == null) + { + string mutexFriendlyFilename = this.CurrentAppender.File + .Replace("\\", "_") + .Replace(":", "_") + .Replace("/", "_"); + + this.m_mutex = new Mutex(false, mutexFriendlyFilename); + } + else + { + this.CurrentAppender.ErrorHandler.Error("Programming error, mutex already initialized!"); + } + } + + /// + /// Disposes all resources that were initialized by this locking model. + /// + public override void OnClose() + { + if (this.m_mutex != null) + { +#if NET_4_0 || MONO_4_0 || NETSTANDARD + this.m_mutex.Dispose(); +#else + m_mutex.Close(); +#endif + this.m_mutex = null; + } + else + { + this.CurrentAppender.ErrorHandler.Error("Programming error, mutex not initialized!"); + } + } } -#endif +#endif /// - /// Initializes a new instance of the class. - /// Default constructor. - /// - /// - /// - /// Default constructor. - /// - /// - public FileAppender() - { + /// Default constructor + /// + /// + /// + /// Default constructor + /// + /// + public FileAppender() + { } /// - /// Initializes a new instance of the class. - /// Construct a new appender using the layout, file and append mode. - /// - /// the layout to use with this appender. - /// the full path to the file to write to. - /// flag to indicate if the file should be appended to. - /// - /// - /// Obsolete constructor. - /// - /// - [Obsolete("Instead use the default constructor and set the Layout, File & AppendToFile properties. Scheduled removal in v10.0.0.")] - public FileAppender(ILayout layout, string filename, bool append) - { - this.Layout = layout; - this.File = filename; - this.AppendToFile = append; - this.ActivateOptions(); + /// Construct a new appender using the layout, file and append mode. + /// + /// the layout to use with this appender + /// the full path to the file to write to + /// flag to indicate if the file should be appended to + /// + /// + /// Obsolete constructor. + /// + /// + [Obsolete("Instead use the default constructor and set the Layout, File & AppendToFile properties")] + public FileAppender(ILayout layout, string filename, bool append) + { + this.Layout = layout; + this.File = filename; + this.AppendToFile = append; + this.ActivateOptions(); } /// - /// Initializes a new instance of the class. - /// Construct a new appender using the layout and file specified. - /// The file will be appended to. - /// - /// the layout to use with this appender. - /// the full path to the file to write to. - /// - /// - /// Obsolete constructor. - /// - /// - [Obsolete("Instead use the default constructor and set the Layout & File properties. Scheduled removal in v10.0.0.")] - public FileAppender(ILayout layout, string filename) - : this(layout, filename, true) - { + /// Construct a new appender using the layout and file specified. + /// The file will be appended to. + /// + /// the layout to use with this appender + /// the full path to the file to write to + /// + /// + /// Obsolete constructor. + /// + /// + [Obsolete("Instead use the default constructor and set the Layout & File properties")] + public FileAppender(ILayout layout, string filename) + : this(layout, filename, true) + { } - /// - /// Gets or sets the path to the file that logging will be written to. - /// - /// - /// The path to the file that logging will be written to. - /// - /// - /// - /// If the path is relative it is taken as relative from - /// the application base directory. - /// - /// - public virtual string File - { - get { return this.m_fileName; } - set { this.m_fileName = value; } - } - - /// - /// Gets or sets a value indicating whether gets or sets a flag that indicates whether the file should be - /// appended to or overwritten. - /// - /// - /// Indicates whether the file should be appended to or overwritten. - /// - /// - /// - /// If the value is set to false then the file will be overwritten, if - /// it is set to true then the file will be appended to. - /// - /// The default value is true. - /// - public bool AppendToFile - { - get { return this.m_appendToFile; } - set { this.m_appendToFile = value; } - } - - /// - /// Gets or sets used to write to the file. - /// - /// - /// The used to write to the file. - /// - /// - /// - /// The default encoding set is - /// which is the encoding for the system's current ANSI code page. - /// - /// - public Encoding Encoding - { - get { return this.m_encoding; } - set { this.m_encoding = value; } - } - - /// - /// Gets or sets the used to write to the file. - /// - /// - /// The used to write to the file. - /// - /// - /// - /// Unless a specified here for this appender - /// the is queried for the - /// security context to use. The default behavior is to use the security context - /// of the current thread. - /// - /// - public SecurityContext SecurityContext - { - get { return this.m_securityContext; } - set { this.m_securityContext = value; } + /// + /// Gets or sets the path to the file that logging will be written to. + /// + /// + /// The path to the file that logging will be written to. + /// + /// + /// + /// If the path is relative it is taken as relative from + /// the application base directory. + /// + /// + public virtual string File + { + get { return this.m_fileName; } + set { this.m_fileName = value; } } -#if NETCF - /// - /// Gets or sets the used to handle locking of the file. - /// - /// - /// The used to lock the file. - /// - /// - /// - /// Gets or sets the used to handle locking of the file. - /// - /// - /// There are two built in locking models, and . - /// The first locks the file from the start of logging to the end, the - /// second locks only for the minimal amount of time when logging each message - /// and the last synchronizes processes using a named system wide Mutex. - /// - /// - /// The default locking model is the . - /// - /// -#else - /// - /// Gets or sets the used to handle locking of the file. - /// - /// - /// The used to lock the file. - /// - /// - /// - /// Gets or sets the used to handle locking of the file. - /// - /// - /// There are three built in locking models, , and . - /// The first locks the file from the start of logging to the end, the - /// second locks only for the minimal amount of time when logging each message - /// and the last synchronizes processes using a named system wide Mutex. - /// - /// - /// The default locking model is the . - /// - /// -#endif - public FileAppender.LockingModelBase LockingModel - { - get { return this.m_lockingModel; } - set { this.m_lockingModel = value; } + /// + /// Gets or sets a flag that indicates whether the file should be + /// appended to or overwritten. + /// + /// + /// Indicates whether the file should be appended to or overwritten. + /// + /// + /// + /// If the value is set to false then the file will be overwritten, if + /// it is set to true then the file will be appended to. + /// + /// The default value is true. + /// + public bool AppendToFile + { + get { return this.m_appendToFile; } + set { this.m_appendToFile = value; } } - /// - /// Activate the options on the file appender. - /// - /// - /// - /// This is part of the delayed object - /// activation scheme. The method must - /// be called on this object after the configuration properties have - /// been set. Until is called this - /// object is in an undefined state and must not be used. - /// - /// - /// If any of the configuration properties are modified then - /// must be called again. - /// - /// - /// This will cause the file to be opened. - /// - /// - public override void ActivateOptions() - { - base.ActivateOptions(); - - if (this.m_securityContext == null) - { - this.m_securityContext = SecurityContextProvider.DefaultProvider.CreateSecurityContext(this); - } - - if (this.m_lockingModel == null) - { - this.m_lockingModel = new FileAppender.ExclusiveLock(); - } - - this.m_lockingModel.CurrentAppender = this; - this.m_lockingModel.ActivateOptions(); - - if (this.m_fileName != null) - { - using (this.SecurityContext.Impersonate(this)) - { - this.m_fileName = ConvertToFullPath(this.m_fileName.Trim()); - } - - this.SafeOpenFile(this.m_fileName, this.m_appendToFile); - } - else - { - LogLog.Warn(declaringType, "FileAppender: File option not set for appender [" + this.Name + "]."); - LogLog.Warn(declaringType, "FileAppender: Are you using FileAppender instead of ConsoleAppender?"); - } + /// + /// Gets or sets used to write to the file. + /// + /// + /// The used to write to the file. + /// + /// + /// + /// The default encoding set is + /// which is the encoding for the system's current ANSI code page. + /// + /// + public Encoding Encoding + { + get { return this.m_encoding; } + set { this.m_encoding = value; } } - /// - /// Closes any previously opened file and calls the parent's . - /// - /// - /// - /// Resets the filename and the file stream. - /// - /// - protected override void Reset() - { - base.Reset(); - this.m_fileName = null; - } - - /// - /// Close this appender instance. The underlying stream or writer is also closed. - /// - protected override void OnClose() - { - base.OnClose(); - this.m_lockingModel.OnClose(); - } - - /// - /// Called to initialize the file writer. - /// - /// - /// - /// Will be called for each logged message until the file is - /// successfully opened. - /// - /// - protected override void PrepareWriter() - { - this.SafeOpenFile(this.m_fileName, this.m_appendToFile); - } - - /// - /// This method is called by the - /// method. - /// - /// The event to log. - /// - /// - /// Writes a log statement to the output stream if the output stream exists - /// and is writable. - /// - /// - /// The format of the output will depend on the appender's layout. - /// - /// - protected override void Append(LoggingEvent loggingEvent) - { - if (this.m_stream.AcquireLock()) - { - try - { - base.Append(loggingEvent); - } - finally - { - this.m_stream.ReleaseLock(); - } - } - } - - /// - /// This method is called by the - /// method. - /// - /// The array of events to log. - /// - /// - /// Acquires the output file locks once before writing all the events to - /// the stream. - /// - /// - protected override void Append(LoggingEvent[] loggingEvents) - { - if (this.m_stream.AcquireLock()) - { - try - { - base.Append(loggingEvents); - } - finally - { - this.m_stream.ReleaseLock(); - } - } - } - - /// - /// Writes a footer as produced by the embedded layout's property. - /// - /// - /// - /// Writes a footer as produced by the embedded layout's property. - /// - /// - protected override void WriteFooter() - { - if (this.m_stream != null) - { - // WriteFooter can be called even before a file is opened - this.m_stream.AcquireLock(); - try - { - base.WriteFooter(); - } - finally - { - this.m_stream.ReleaseLock(); - } - } - } - - /// - /// Writes a header produced by the embedded layout's property. - /// - /// - /// - /// Writes a header produced by the embedded layout's property. - /// - /// - protected override void WriteHeader() - { - if (this.m_stream != null) - { - if (this.m_stream.AcquireLock()) - { - try - { - base.WriteHeader(); - } - finally - { - this.m_stream.ReleaseLock(); - } - } - } - } - - /// - /// Closes the underlying . - /// - /// - /// - /// Closes the underlying . - /// - /// - protected override void CloseWriter() - { - if (this.m_stream != null) - { - this.m_stream.AcquireLock(); - try - { - base.CloseWriter(); - } - finally - { - this.m_stream.ReleaseLock(); - } - } + /// + /// Gets or sets the used to write to the file. + /// + /// + /// The used to write to the file. + /// + /// + /// + /// Unless a specified here for this appender + /// the is queried for the + /// security context to use. The default behavior is to use the security context + /// of the current thread. + /// + /// + public SecurityContext SecurityContext + { + get { return this.m_securityContext; } + set { this.m_securityContext = value; } } - /// - /// Closes the previously opened file. - /// - /// - /// - /// Writes the to the file and then - /// closes the file. - /// - /// - protected void CloseFile() - { - this.WriteFooterAndCloseWriter(); +#if NETCF + /// + /// Gets or sets the used to handle locking of the file. + /// + /// + /// The used to lock the file. + /// + /// + /// + /// Gets or sets the used to handle locking of the file. + /// + /// + /// There are two built in locking models, and . + /// The first locks the file from the start of logging to the end, the + /// second locks only for the minimal amount of time when logging each message + /// and the last synchronizes processes using a named system wide Mutex. + /// + /// + /// The default locking model is the . + /// + /// +#else + /// + /// Gets or sets the used to handle locking of the file. + /// + /// + /// The used to lock the file. + /// + /// + /// + /// Gets or sets the used to handle locking of the file. + /// + /// + /// There are three built in locking models, , and . + /// The first locks the file from the start of logging to the end, the + /// second locks only for the minimal amount of time when logging each message + /// and the last synchronizes processes using a named system wide Mutex. + /// + /// + /// The default locking model is the . + /// + /// +#endif + public LockingModelBase LockingModel + { + get { return this.m_lockingModel; } + set { this.m_lockingModel = value; } } - /// - /// Sets and opens the file where the log output will go. The specified file must be writable. - /// - /// The path to the log file. Must be a fully qualified path. - /// If true will append to fileName. Otherwise will truncate fileName. - /// - /// - /// Calls but guarantees not to throw an exception. - /// Errors are passed to the . - /// - /// - protected virtual void SafeOpenFile(string fileName, bool append) - { - try - { - this.OpenFile(fileName, append); - } - catch (Exception e) - { - this.ErrorHandler.Error("OpenFile(" + fileName + "," + append + ") call failed.", e, ErrorCode.FileOpenFailure); - } - } - - /// - /// Sets and opens the file where the log output will go. The specified file must be writable. - /// - /// The path to the log file. Must be a fully qualified path. - /// If true will append to fileName. Otherwise will truncate fileName. - /// - /// - /// If there was already an opened file, then the previous file - /// is closed first. - /// - /// - /// This method will ensure that the directory structure - /// for the specified exists. - /// - /// - protected virtual void OpenFile(string fileName, bool append) - { - if (LogLog.IsErrorEnabled) - { - // Internal check that the fileName passed in is a rooted path - bool isPathRooted = false; - using (this.SecurityContext.Impersonate(this)) - { - isPathRooted = Path.IsPathRooted(fileName); - } - - if (!isPathRooted) - { - LogLog.Error(declaringType, "INTERNAL ERROR. OpenFile(" + fileName + "): File name is not fully qualified."); - } - } - - lock (this) - { - this.Reset(); - - LogLog.Debug(declaringType, "Opening file for writing [" + fileName + "] append [" + append + "]"); - - // Save these for later, allowing retries if file open fails - this.m_fileName = fileName; - this.m_appendToFile = append; - - this.LockingModel.CurrentAppender = this; - this.LockingModel.OpenFile(fileName, append, this.m_encoding); - this.m_stream = new LockingStream(this.LockingModel); - - if (this.m_stream != null) - { - this.m_stream.AcquireLock(); - try - { - this.SetQWForFiles(this.m_stream); - } - finally - { - this.m_stream.ReleaseLock(); - } - } - - this.WriteHeader(); - } - } - - /// - /// Sets the quiet writer used for file output. - /// - /// the file stream that has been opened for writing. - /// - /// - /// This implementation of creates a - /// over the and passes it to the - /// method. - /// - /// - /// This method can be overridden by sub classes that want to wrap the - /// in some way, for example to encrypt the output - /// data using a System.Security.Cryptography.CryptoStream. - /// - /// - protected virtual void SetQWForFiles(Stream fileStream) - { - this.SetQWForFiles(new StreamWriter(fileStream, this.m_encoding)); - } - - /// - /// Sets the quiet writer being used. - /// - /// the writer over the file stream that has been opened for writing. - /// - /// - /// This method can be overridden by sub classes that want to - /// wrap the in some way. - /// - /// - protected virtual void SetQWForFiles(TextWriter writer) - { - this.QuietWriter = new QuietTextWriter(writer, this.ErrorHandler); + /// + /// Activate the options on the file appender. + /// + /// + /// + /// This is part of the delayed object + /// activation scheme. The method must + /// be called on this object after the configuration properties have + /// been set. Until is called this + /// object is in an undefined state and must not be used. + /// + /// + /// If any of the configuration properties are modified then + /// must be called again. + /// + /// + /// This will cause the file to be opened. + /// + /// + public override void ActivateOptions() + { + base.ActivateOptions(); + + if (this.m_securityContext == null) + { + this.m_securityContext = SecurityContextProvider.DefaultProvider.CreateSecurityContext(this); + } + + if (this.m_lockingModel == null) + { + this.m_lockingModel = new ExclusiveLock(); + } + + this.m_lockingModel.CurrentAppender = this; + this.m_lockingModel.ActivateOptions(); + + if (this.m_fileName != null) + { + using (this.SecurityContext.Impersonate(this)) + { + this.m_fileName = ConvertToFullPath(this.m_fileName.Trim()); + } + + this.SafeOpenFile(this.m_fileName, this.m_appendToFile); + } + else + { + LogLog.Warn(declaringType, "FileAppender: File option not set for appender [" + this.Name + "]."); + LogLog.Warn(declaringType, "FileAppender: Are you using FileAppender instead of ConsoleAppender?"); + } + } + + /// + /// Closes any previously opened file and calls the parent's . + /// + /// + /// + /// Resets the filename and the file stream. + /// + /// + protected override void Reset() + { + base.Reset(); + this.m_fileName = null; + } + + /// + /// Close this appender instance. The underlying stream or writer is also closed. + /// + protected override void OnClose() + { + base.OnClose(); + this.m_lockingModel.OnClose(); + } + + /// + /// Called to initialize the file writer + /// + /// + /// + /// Will be called for each logged message until the file is + /// successfully opened. + /// + /// + protected override void PrepareWriter() + { + this.SafeOpenFile(this.m_fileName, this.m_appendToFile); } - /// - /// Convert a path into a fully qualified path. - /// - /// The path to convert. - /// The fully qualified path. - /// - /// - /// Converts the path specified to a fully - /// qualified path. If the path is relative it is - /// taken as relative from the application base - /// directory. - /// - /// - protected static string ConvertToFullPath(string path) - { - return SystemInfo.ConvertToFullPath(path); + /// + /// This method is called by the + /// method. + /// + /// The event to log. + /// + /// + /// Writes a log statement to the output stream if the output stream exists + /// and is writable. + /// + /// + /// The format of the output will depend on the appender's layout. + /// + /// + protected override void Append(LoggingEvent loggingEvent) + { + if (this.m_stream.AcquireLock()) + { + try + { + base.Append(loggingEvent); + } + finally + { + this.m_stream.ReleaseLock(); + } + } } - /// - /// Flag to indicate if we should append to the file - /// or overwrite the file. The default is to append. - /// - private bool m_appendToFile = true; - - /// - /// The name of the log file. - /// - private string m_fileName = null; - - /// - /// The encoding to use for the file stream. - /// - private Encoding m_encoding = Encoding.GetEncoding(0); - - /// - /// The security context to use for privileged calls. - /// - private SecurityContext m_securityContext; - - /// - /// The stream to log to. Has added locking semantics. - /// - private FileAppender.LockingStream m_stream = null; - - /// - /// The locking model to use. - /// - private FileAppender.LockingModelBase m_lockingModel = new FileAppender.ExclusiveLock(); - - /// - /// The fully qualified type of the FileAppender class. - /// - /// - /// Used by the internal logger to record the Type of the - /// log message. - /// + /// + /// This method is called by the + /// method. + /// + /// The array of events to log. + /// + /// + /// Acquires the output file locks once before writing all the events to + /// the stream. + /// + /// + protected override void Append(LoggingEvent[] loggingEvents) + { + if (this.m_stream.AcquireLock()) + { + try + { + base.Append(loggingEvents); + } + finally + { + this.m_stream.ReleaseLock(); + } + } + } + + /// + /// Writes a footer as produced by the embedded layout's property. + /// + /// + /// + /// Writes a footer as produced by the embedded layout's property. + /// + /// + protected override void WriteFooter() + { + if (this.m_stream != null) + { + //WriteFooter can be called even before a file is opened + this.m_stream.AcquireLock(); + try + { + base.WriteFooter(); + } + finally + { + this.m_stream.ReleaseLock(); + } + } + } + + /// + /// Writes a header produced by the embedded layout's property. + /// + /// + /// + /// Writes a header produced by the embedded layout's property. + /// + /// + protected override void WriteHeader() + { + if (this.m_stream != null) + { + if (this.m_stream.AcquireLock()) + { + try + { + base.WriteHeader(); + } + finally + { + this.m_stream.ReleaseLock(); + } + } + } + } + + /// + /// Closes the underlying . + /// + /// + /// + /// Closes the underlying . + /// + /// + protected override void CloseWriter() + { + if (this.m_stream != null) + { + this.m_stream.AcquireLock(); + try + { + base.CloseWriter(); + } + finally + { + this.m_stream.ReleaseLock(); + } + } + } + + /// + /// Closes the previously opened file. + /// + /// + /// + /// Writes the to the file and then + /// closes the file. + /// + /// + protected void CloseFile() + { + this.WriteFooterAndCloseWriter(); + } + + /// + /// Sets and opens the file where the log output will go. The specified file must be writable. + /// + /// The path to the log file. Must be a fully qualified path. + /// If true will append to fileName. Otherwise will truncate fileName + /// + /// + /// Calls but guarantees not to throw an exception. + /// Errors are passed to the . + /// + /// + protected virtual void SafeOpenFile(string fileName, bool append) + { + try + { + this.OpenFile(fileName, append); + } + catch (Exception e) + { + this.ErrorHandler.Error("OpenFile(" + fileName + "," + append + ") call failed.", e, ErrorCode.FileOpenFailure); + } + } + + /// + /// Sets and opens the file where the log output will go. The specified file must be writable. + /// + /// The path to the log file. Must be a fully qualified path. + /// If true will append to fileName. Otherwise will truncate fileName + /// + /// + /// If there was already an opened file, then the previous file + /// is closed first. + /// + /// + /// This method will ensure that the directory structure + /// for the specified exists. + /// + /// + protected virtual void OpenFile(string fileName, bool append) + { + if (LogLog.IsErrorEnabled) + { + // Internal check that the fileName passed in is a rooted path + bool isPathRooted = false; + using (this.SecurityContext.Impersonate(this)) + { + isPathRooted = Path.IsPathRooted(fileName); + } + if (!isPathRooted) + { + LogLog.Error(declaringType, "INTERNAL ERROR. OpenFile(" + fileName + "): File name is not fully qualified."); + } + } + + lock (this) + { + this.Reset(); + + LogLog.Debug(declaringType, "Opening file for writing [" + fileName + "] append [" + append + "]"); + + // Save these for later, allowing retries if file open fails + this.m_fileName = fileName; + this.m_appendToFile = append; + + this.LockingModel.CurrentAppender = this; + this.LockingModel.OpenFile(fileName, append, this.m_encoding); + this.m_stream = new LockingStream(this.LockingModel); + + if (this.m_stream != null) + { + this.m_stream.AcquireLock(); + try + { + this.SetQWForFiles(this.m_stream); + } + finally + { + this.m_stream.ReleaseLock(); + } + } + + this.WriteHeader(); + } + } + + /// + /// Sets the quiet writer used for file output + /// + /// the file stream that has been opened for writing + /// + /// + /// This implementation of creates a + /// over the and passes it to the + /// method. + /// + /// + /// This method can be overridden by sub classes that want to wrap the + /// in some way, for example to encrypt the output + /// data using a System.Security.Cryptography.CryptoStream. + /// + /// + protected virtual void SetQWForFiles(Stream fileStream) + { +#pragma warning disable CA2000 // Dispose objects before losing scope + StreamWriter writer = new StreamWriter(fileStream, this.m_encoding); +#pragma warning restore CA2000 // Dispose objects before losing scope + this.SetQWForFiles(writer); + } + + /// + /// Sets the quiet writer being used. + /// + /// the writer over the file stream that has been opened for writing + /// + /// + /// This method can be overridden by sub classes that want to + /// wrap the in some way. + /// + /// + protected virtual void SetQWForFiles(TextWriter writer) + { + this.QuietWriter = new QuietTextWriter(writer, this.ErrorHandler); + } + + /// + /// Convert a path into a fully qualified path. + /// + /// The path to convert. + /// The fully qualified path. + /// + /// + /// Converts the path specified to a fully + /// qualified path. If the path is relative it is + /// taken as relative from the application base + /// directory. + /// + /// + protected static string ConvertToFullPath(string path) + { + return SystemInfo.ConvertToFullPath(path); + } + + /// + /// Flag to indicate if we should append to the file + /// or overwrite the file. The default is to append. + /// + private bool m_appendToFile = true; + + /// + /// The name of the log file. + /// + private string m_fileName = null; + + /// + /// The encoding to use for the file stream. + /// + private Encoding m_encoding = Encoding.GetEncoding(0); + + /// + /// The security context to use for privileged calls + /// + private SecurityContext m_securityContext; + + /// + /// The stream to log to. Has added locking semantics + /// + private LockingStream m_stream = null; + + /// + /// The locking model to use + /// + private LockingModelBase m_lockingModel = new ExclusiveLock(); + + /// + /// The fully qualified type of the FileAppender class. + /// + /// + /// Used by the internal logger to record the Type of the + /// log message. + /// private static readonly Type declaringType = typeof(FileAppender); - } -} + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/ForwardingAppender.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/ForwardingAppender.cs index 3aba0389fc1..4293d0899b5 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/ForwardingAppender.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/ForwardingAppender.cs @@ -1,268 +1,265 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.Appender -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; +using System; - using log4net.Core; - using log4net.Layout; - using log4net.Util; +using log4net.Util; +using log4net.Layout; +using log4net.Core; - /// - /// This appender forwards logging events to attached appenders. - /// - /// - /// - /// The forwarding appender can be used to specify different thresholds - /// and filters for the same appender at different locations within the hierarchy. - /// - /// - /// Nicko Cadell. - /// Gert Driesen. - public class ForwardingAppender : AppenderSkeleton, IAppenderAttachable +namespace log4net.Appender +{ + /// + /// This appender forwards logging events to attached appenders. + /// + /// + /// + /// The forwarding appender can be used to specify different thresholds + /// and filters for the same appender at different locations within the hierarchy. + /// + /// + /// Nicko Cadell + /// Gert Driesen + public class ForwardingAppender : AppenderSkeleton, IAppenderAttachable { - /// - /// Initializes a new instance of the class. - /// - /// - /// - /// Default constructor. - /// - /// - public ForwardingAppender() - { + /// + /// Initializes a new instance of the class. + /// + /// + /// + /// Default constructor. + /// + /// + public ForwardingAppender() + { } - /// - /// Closes the appender and releases resources. - /// - /// - /// - /// Releases any resources allocated within the appender such as file handles, - /// network connections, etc. - /// - /// - /// It is a programming error to append to a closed appender. - /// - /// - protected override void OnClose() - { - // Remove all the attached appenders - lock (this) - { - if (this.m_appenderAttachedImpl != null) - { - this.m_appenderAttachedImpl.RemoveAllAppenders(); - } - } - } - - /// - /// Forward the logging event to the attached appenders. - /// - /// The event to log. - /// - /// - /// Delivers the logging event to all the attached appenders. - /// - /// - protected override void Append(LoggingEvent loggingEvent) - { - // Pass the logging event on the the attached appenders - if (this.m_appenderAttachedImpl != null) - { - this.m_appenderAttachedImpl.AppendLoopOnAppenders(loggingEvent); - } - } - - /// - /// Forward the logging events to the attached appenders. - /// - /// The array of events to log. - /// - /// - /// Delivers the logging events to all the attached appenders. - /// - /// - protected override void Append(LoggingEvent[] loggingEvents) - { - // Pass the logging event on the the attached appenders - if (this.m_appenderAttachedImpl != null) - { - this.m_appenderAttachedImpl.AppendLoopOnAppenders(loggingEvents); - } + /// + /// Closes the appender and releases resources. + /// + /// + /// + /// Releases any resources allocated within the appender such as file handles, + /// network connections, etc. + /// + /// + /// It is a programming error to append to a closed appender. + /// + /// + protected override void OnClose() + { + // Remove all the attached appenders + lock(this) + { + if (this.m_appenderAttachedImpl != null) + { + this.m_appenderAttachedImpl.RemoveAllAppenders(); + } + } } - /// - /// Adds an to the list of appenders of this - /// instance. - /// - /// The to add to this appender. - /// - /// - /// If the specified is already in the list of - /// appenders, then it won't be added again. - /// - /// - public virtual void AddAppender(IAppender newAppender) - { - if (newAppender == null) - { - throw new ArgumentNullException("newAppender"); - } + /// + /// Forward the logging event to the attached appenders + /// + /// The event to log. + /// + /// + /// Delivers the logging event to all the attached appenders. + /// + /// + protected override void Append(LoggingEvent loggingEvent) + { + // Pass the logging event on the the attached appenders + if (this.m_appenderAttachedImpl != null) + { + this.m_appenderAttachedImpl.AppendLoopOnAppenders(loggingEvent); + } + } - lock (this) - { - if (this.m_appenderAttachedImpl == null) - { - this.m_appenderAttachedImpl = new log4net.Util.AppenderAttachedImpl(); - } + /// + /// Forward the logging events to the attached appenders + /// + /// The array of events to log. + /// + /// + /// Delivers the logging events to all the attached appenders. + /// + /// + protected override void Append(LoggingEvent[] loggingEvents) + { + // Pass the logging event on the the attached appenders + if (this.m_appenderAttachedImpl != null) + { + this.m_appenderAttachedImpl.AppendLoopOnAppenders(loggingEvents); + } + } + + /// + /// Adds an to the list of appenders of this + /// instance. + /// + /// The to add to this appender. + /// + /// + /// If the specified is already in the list of + /// appenders, then it won't be added again. + /// + /// + public virtual void AddAppender(IAppender newAppender) + { + if (newAppender == null) + { + throw new ArgumentNullException("newAppender"); + } + lock(this) + { + if (this.m_appenderAttachedImpl == null) + { + this.m_appenderAttachedImpl = new AppenderAttachedImpl(); + } + + this.m_appenderAttachedImpl.AddAppender(newAppender); + } + } + + /// + /// Gets the appenders contained in this appender as an + /// . + /// + /// + /// If no appenders can be found, then an + /// is returned. + /// + /// + /// A collection of the appenders in this appender. + /// + public virtual AppenderCollection Appenders + { + get + { + lock(this) + { + if (this.m_appenderAttachedImpl == null) + { + return AppenderCollection.EmptyCollection; + } + else + { + return this.m_appenderAttachedImpl.Appenders; + } + } + } + } - this.m_appenderAttachedImpl.AddAppender(newAppender); - } - } - - /// - /// Gets the appenders contained in this appender as an - /// . - /// - /// - /// If no appenders can be found, then an - /// is returned. - /// - /// - /// A collection of the appenders in this appender. - /// - public virtual AppenderCollection Appenders - { - get - { - lock (this) - { - if (this.m_appenderAttachedImpl == null) - { - return AppenderCollection.EmptyCollection; - } - else - { - return this.m_appenderAttachedImpl.Appenders; - } - } - } - } - - /// - /// Looks for the appender with the specified name. - /// - /// The name of the appender to lookup. - /// - /// The appender with the specified name, or null. - /// - /// - /// - /// Get the named appender attached to this appender. - /// - /// - public virtual IAppender GetAppender(string name) - { - lock (this) - { - if (this.m_appenderAttachedImpl == null || name == null) - { - return null; - } - - return this.m_appenderAttachedImpl.GetAppender(name); - } - } - - /// - /// Removes all previously added appenders from this appender. - /// - /// - /// - /// This is useful when re-reading configuration information. - /// - /// - public virtual void RemoveAllAppenders() - { - lock (this) - { - if (this.m_appenderAttachedImpl != null) - { - this.m_appenderAttachedImpl.RemoveAllAppenders(); - this.m_appenderAttachedImpl = null; - } - } - } - - /// - /// Removes the specified appender from the list of appenders. - /// - /// The appender to remove. - /// The appender removed from the list. - /// - /// The appender removed is not closed. - /// If you are discarding the appender you must call - /// on the appender removed. - /// - public virtual IAppender RemoveAppender(IAppender appender) - { - lock (this) - { - if (appender != null && this.m_appenderAttachedImpl != null) - { - return this.m_appenderAttachedImpl.RemoveAppender(appender); - } - } + /// + /// Looks for the appender with the specified name. + /// + /// The name of the appender to lookup. + /// + /// The appender with the specified name, or null. + /// + /// + /// + /// Get the named appender attached to this appender. + /// + /// + public virtual IAppender GetAppender(string name) + { + lock(this) + { + if (this.m_appenderAttachedImpl == null || name == null) + { + return null; + } - return null; - } - - /// - /// Removes the appender with the specified name from the list of appenders. - /// - /// The name of the appender to remove. - /// The appender removed from the list. - /// - /// The appender removed is not closed. - /// If you are discarding the appender you must call - /// on the appender removed. - /// - public virtual IAppender RemoveAppender(string name) - { - lock (this) - { - if (name != null && this.m_appenderAttachedImpl != null) - { - return this.m_appenderAttachedImpl.RemoveAppender(name); - } - } + return this.m_appenderAttachedImpl.GetAppender(name); + } + } + + /// + /// Removes all previously added appenders from this appender. + /// + /// + /// + /// This is useful when re-reading configuration information. + /// + /// + public virtual void RemoveAllAppenders() + { + lock(this) + { + if (this.m_appenderAttachedImpl != null) + { + this.m_appenderAttachedImpl.RemoveAllAppenders(); + this.m_appenderAttachedImpl = null; + } + } + } + + /// + /// Removes the specified appender from the list of appenders. + /// + /// The appender to remove. + /// The appender removed from the list + /// + /// The appender removed is not closed. + /// If you are discarding the appender you must call + /// on the appender removed. + /// + public virtual IAppender RemoveAppender(IAppender appender) + { + lock(this) + { + if (appender != null && this.m_appenderAttachedImpl != null) + { + return this.m_appenderAttachedImpl.RemoveAppender(appender); + } + } + return null; + } - return null; + /// + /// Removes the appender with the specified name from the list of appenders. + /// + /// The name of the appender to remove. + /// The appender removed from the list + /// + /// The appender removed is not closed. + /// If you are discarding the appender you must call + /// on the appender removed. + /// + public virtual IAppender RemoveAppender(string name) + { + lock(this) + { + if (name != null && this.m_appenderAttachedImpl != null) + { + return this.m_appenderAttachedImpl.RemoveAppender(name); + } + } + return null; } - /// - /// Implementation of the interface. - /// + /// + /// Implementation of the interface + /// private AppenderAttachedImpl m_appenderAttachedImpl; - } -} + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/IAppender.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/IAppender.cs index 78a5457b3b9..0ed3c14d371 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/IAppender.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/IAppender.cs @@ -1,79 +1,79 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.Appender -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using log4net.Core; - using log4net.Filter; - using log4net.Layout; +using log4net.Filter; +using log4net.Layout; +using log4net.Core; - /// - /// Implement this interface for your own strategies for printing log statements. - /// - /// - /// - /// Implementors should consider extending the - /// class which provides a default implementation of this interface. - /// - /// - /// Appenders can also implement the interface. Therefore - /// they would require that the method - /// be called after the appenders properties have been configured. - /// - /// - /// Nicko Cadell. - /// Gert Driesen. - public interface IAppender - { - /// - /// Closes the appender and releases resources. - /// - /// - /// - /// Releases any resources allocated within the appender such as file handles, - /// network connections, etc. - /// - /// - /// It is a programming error to append to a closed appender. - /// - /// - void Close(); - - /// - /// Log the logging event in Appender specific way. - /// - /// The event to log. - /// - /// - /// This method is called to log a message into this appender. - /// - /// - void DoAppend(LoggingEvent loggingEvent); - - /// - /// Gets or sets the name of this appender. - /// - /// The name of the appender. - /// - /// The name uniquely identifies the appender. - /// - string Name { get; set; } - } -} +namespace log4net.Appender +{ + /// + /// Implement this interface for your own strategies for printing log statements. + /// + /// + /// + /// Implementors should consider extending the + /// class which provides a default implementation of this interface. + /// + /// + /// Appenders can also implement the interface. Therefore + /// they would require that the method + /// be called after the appenders properties have been configured. + /// + /// + /// Nicko Cadell + /// Gert Driesen + public interface IAppender + { + /// + /// Closes the appender and releases resources. + /// + /// + /// + /// Releases any resources allocated within the appender such as file handles, + /// network connections, etc. + /// + /// + /// It is a programming error to append to a closed appender. + /// + /// + void Close(); + + /// + /// Log the logging event in Appender specific way. + /// + /// The event to log + /// + /// + /// This method is called to log a message into this appender. + /// + /// + void DoAppend(LoggingEvent loggingEvent); + + /// + /// Gets or sets the name of this appender. + /// + /// The name of the appender. + /// + /// The name uniquely identifies the appender. + /// + string Name { get; set; } + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/IBulkAppender.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/IBulkAppender.cs index eeba2989703..9efae52d70d 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/IBulkAppender.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/IBulkAppender.cs @@ -1,49 +1,49 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.Appender -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using log4net.Core; +using log4net.Core; - /// - /// Interface for appenders that support bulk logging. - /// - /// - /// - /// This interface extends the interface to - /// support bulk logging of objects. Appenders - /// should only implement this interface if they can bulk log efficiently. - /// - /// - /// Nicko Cadell. - public interface IBulkAppender : IAppender - { - /// - /// Log the array of logging events in Appender specific way. - /// - /// The events to log. - /// - /// - /// This method is called to log an array of events into this appender. - /// - /// - void DoAppend(LoggingEvent[] loggingEvents); - } -} +namespace log4net.Appender +{ + /// + /// Interface for appenders that support bulk logging. + /// + /// + /// + /// This interface extends the interface to + /// support bulk logging of objects. Appenders + /// should only implement this interface if they can bulk log efficiently. + /// + /// + /// Nicko Cadell + public interface IBulkAppender : IAppender + { + /// + /// Log the array of logging events in Appender specific way. + /// + /// The events to log + /// + /// + /// This method is called to log an array of events into this appender. + /// + /// + void DoAppend(LoggingEvent[] loggingEvents); + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/IFlushable.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/IFlushable.cs index 4d81ef9aaea..2cc93ba9a44 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/IFlushable.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/IFlushable.cs @@ -1,60 +1,60 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.Appender -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; +using System; - /// - /// Interface that can be implemented by Appenders that buffer logging data and expose a method. - /// - public interface IFlushable - { - /// - /// Flushes any buffered log data. - /// - /// - /// Appenders that implement the method must do so in a thread-safe manner: it can be called concurrently with - /// the method. - /// - /// Typically this is done by locking on the Appender instance, e.g.: - /// - /// - /// - /// - /// - /// The parameter is only relevant for appenders that process logging events asynchronously, - /// such as . - /// - /// - /// The maximum time to wait for logging events to be flushed. - /// True if all logging events were flushed successfully, else false. - bool Flush(int millisecondsTimeout); - } -} +namespace log4net.Appender +{ + /// + /// Interface that can be implemented by Appenders that buffer logging data and expose a method. + /// + public interface IFlushable + { + /// + /// Flushes any buffered log data. + /// + /// + /// Appenders that implement the method must do so in a thread-safe manner: it can be called concurrently with + /// the method. + /// + /// Typically this is done by locking on the Appender instance, e.g.: + /// + /// + /// + /// + /// + /// The parameter is only relevant for appenders that process logging events asynchronously, + /// such as . + /// + /// + /// The maximum time to wait for logging events to be flushed. + /// True if all logging events were flushed successfully, else false. + bool Flush(int millisecondsTimeout); + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/LocalSyslogAppender.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/LocalSyslogAppender.cs index ca2e165de88..863922d4cc7 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/LocalSyslogAppender.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/LocalSyslogAppender.cs @@ -1,567 +1,566 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -// .NET Compact Framework 1.0 has no support for Marshal.StringToHGlobalAnsi -// SSCLI 1.0 has no support for Marshal.StringToHGlobalAnsi -#if !NETCF && !SSCLI - -using System; -using System.Runtime.InteropServices; - -using log4net.Appender; -using log4net.Core; -using log4net.Layout; -using log4net.Util; - -namespace log4net.Appender -{ - /// - /// Logs events to a local syslog service. - /// - /// - /// - /// This appender uses the POSIX libc library functions openlog, syslog, and closelog. - /// If these functions are not available on the local system then this appender will not work!. - /// - /// - /// The functions openlog, syslog, and closelog are specified in SUSv2 and - /// POSIX 1003.1-2001 standards. These are used to log messages to the local syslog service. - /// - /// - /// This appender talks to a local syslog service. If you need to log to a remote syslog - /// daemon and you cannot configure your local syslog service to do this you may be - /// able to use the to log via UDP. - /// - /// - /// Syslog messages must have a facility and and a severity. The severity - /// is derived from the Level of the logging event. - /// The facility must be chosen from the set of defined syslog - /// values. The facilities list is predefined - /// and cannot be extended. - /// - /// - /// An identifier is specified with each log message. This can be specified - /// by setting the property. The identity (also know - /// as the tag) must not contain white space. The default value for the - /// identity is the application name (from ). - /// - /// - /// Rob Lyon. - /// Nicko Cadell. - public class LocalSyslogAppender : AppenderSkeleton +// .NET Compact Framework 1.0 has no support for Marshal.StringToHGlobalAnsi +// SSCLI 1.0 has no support for Marshal.StringToHGlobalAnsi +#if !NETCF && !SSCLI + +using System; +using System.Runtime.InteropServices; + +using log4net.Core; +using log4net.Util; + +namespace log4net.Appender +{ + /// + /// Logs events to a local syslog service. + /// + /// + /// + /// This appender uses the POSIX libc library functions openlog, syslog, and closelog. + /// If these functions are not available on the local system then this appender will not work! + /// + /// + /// The functions openlog, syslog, and closelog are specified in SUSv2 and + /// POSIX 1003.1-2001 standards. These are used to log messages to the local syslog service. + /// + /// + /// This appender talks to a local syslog service. If you need to log to a remote syslog + /// daemon and you cannot configure your local syslog service to do this you may be + /// able to use the to log via UDP. + /// + /// + /// Syslog messages must have a facility and and a severity. The severity + /// is derived from the Level of the logging event. + /// The facility must be chosen from the set of defined syslog + /// values. The facilities list is predefined + /// and cannot be extended. + /// + /// + /// An identifier is specified with each log message. This can be specified + /// by setting the property. The identity (also know + /// as the tag) must not contain white space. The default value for the + /// identity is the application name (from ). + /// + /// + /// Rob Lyon + /// Nicko Cadell + public class LocalSyslogAppender : AppenderSkeleton { - /// - /// syslog severities. - /// - /// - /// - /// The log4net Level maps to a syslog severity using the - /// method and the - /// class. The severity is set on . - /// - /// - public enum SyslogSeverity - { - /// - /// system is unusable - /// - Emergency = 0, - - /// - /// action must be taken immediately - /// - Alert = 1, - - /// - /// critical conditions - /// - Critical = 2, - - /// - /// error conditions - /// - Error = 3, - - /// - /// warning conditions - /// - Warning = 4, - - /// - /// normal but significant condition - /// - Notice = 5, - - /// - /// informational - /// - Informational = 6, - - /// - /// debug-level messages - /// - Debug = 7, - } - - /// - /// syslog facilities. - /// - /// - /// - /// The syslog facility defines which subsystem the logging comes from. - /// This is set on the property. - /// - /// - public enum SyslogFacility - { - /// - /// kernel messages - /// - Kernel = 0, - - /// - /// random user-level messages - /// - User = 1, - - /// - /// mail system - /// - Mail = 2, - - /// - /// system daemons - /// - Daemons = 3, - - /// - /// security/authorization messages - /// - Authorization = 4, - - /// - /// messages generated internally by syslogd - /// - Syslog = 5, - - /// - /// line printer subsystem - /// - Printer = 6, - - /// - /// network news subsystem - /// - News = 7, - - /// - /// UUCP subsystem - /// - Uucp = 8, - - /// - /// clock (cron/at) daemon - /// - Clock = 9, - - /// - /// security/authorization messages (private) - /// - Authorization2 = 10, - - /// - /// ftp daemon - /// - Ftp = 11, - - /// - /// NTP subsystem - /// - Ntp = 12, - - /// - /// log audit - /// - Audit = 13, - - /// - /// log alert - /// - Alert = 14, - - /// - /// clock daemon - /// - Clock2 = 15, - - /// - /// reserved for local use - /// - Local0 = 16, - - /// - /// reserved for local use - /// - Local1 = 17, - - /// - /// reserved for local use - /// - Local2 = 18, - - /// - /// reserved for local use - /// - Local3 = 19, - - /// - /// reserved for local use - /// - Local4 = 20, - - /// - /// reserved for local use - /// - Local5 = 21, - - /// - /// reserved for local use - /// - Local6 = 22, - - /// - /// reserved for local use - /// - Local7 = 23, + /// + /// syslog severities + /// + /// + /// + /// The log4net Level maps to a syslog severity using the + /// method and the + /// class. The severity is set on . + /// + /// + public enum SyslogSeverity + { + /// + /// system is unusable + /// + Emergency = 0, + + /// + /// action must be taken immediately + /// + Alert = 1, + + /// + /// critical conditions + /// + Critical = 2, + + /// + /// error conditions + /// + Error = 3, + + /// + /// warning conditions + /// + Warning = 4, + + /// + /// normal but significant condition + /// + Notice = 5, + + /// + /// informational + /// + Informational = 6, + + /// + /// debug-level messages + /// + Debug = 7 + }; + + /// + /// syslog facilities + /// + /// + /// + /// The syslog facility defines which subsystem the logging comes from. + /// This is set on the property. + /// + /// + public enum SyslogFacility + { + /// + /// kernel messages + /// + Kernel = 0, + + /// + /// random user-level messages + /// + User = 1, + + /// + /// mail system + /// + Mail = 2, + + /// + /// system daemons + /// + Daemons = 3, + + /// + /// security/authorization messages + /// + Authorization = 4, + + /// + /// messages generated internally by syslogd + /// + Syslog = 5, + + /// + /// line printer subsystem + /// + Printer = 6, + + /// + /// network news subsystem + /// + News = 7, + + /// + /// UUCP subsystem + /// + Uucp = 8, + + /// + /// clock (cron/at) daemon + /// + Clock = 9, + + /// + /// security/authorization messages (private) + /// + Authorization2 = 10, + + /// + /// ftp daemon + /// + Ftp = 11, + + /// + /// NTP subsystem + /// + Ntp = 12, + + /// + /// log audit + /// + Audit = 13, + + /// + /// log alert + /// + Alert = 14, + + /// + /// clock daemon + /// + Clock2 = 15, + + /// + /// reserved for local use + /// + Local0 = 16, + + /// + /// reserved for local use + /// + Local1 = 17, + + /// + /// reserved for local use + /// + Local2 = 18, + + /// + /// reserved for local use + /// + Local3 = 19, + + /// + /// reserved for local use + /// + Local4 = 20, + + /// + /// reserved for local use + /// + Local5 = 21, + + /// + /// reserved for local use + /// + Local6 = 22, + + /// + /// reserved for local use + /// + Local7 = 23 } - /// - /// Initializes a new instance of the class. - /// - /// - /// This instance of the class is set up to write - /// to a local syslog service. - /// - public LocalSyslogAppender() - { + /// + /// Initializes a new instance of the class. + /// + /// + /// This instance of the class is set up to write + /// to a local syslog service. + /// + public LocalSyslogAppender() + { } - /// - /// Gets or sets message identity. - /// - /// - /// - /// An identifier is specified with each log message. This can be specified - /// by setting the property. The identity (also know - /// as the tag) must not contain white space. The default value for the - /// identity is the application name (from ). - /// - /// - public string Identity - { - get { return this.m_identity; } - set { this.m_identity = value; } - } - - /// - /// Gets or sets syslog facility. - /// - /// - /// Set to one of the values. The list of - /// facilities is predefined and cannot be extended. The default value - /// is . - /// - public SyslogFacility Facility - { - get { return this.m_facility; } - set { this.m_facility = value; } + /// + /// Message identity + /// + /// + /// + /// An identifier is specified with each log message. This can be specified + /// by setting the property. The identity (also know + /// as the tag) must not contain white space. The default value for the + /// identity is the application name (from ). + /// + /// + public string Identity + { + get { return this.m_identity; } + set { this.m_identity = value; } } - /// - /// Add a mapping of level to severity. - /// - /// The mapping to add. - /// - /// - /// Adds a to this appender. - /// - /// - public void AddMapping(LevelSeverity mapping) - { - this.m_levelMapping.Add(mapping); + /// + /// Syslog facility + /// + /// + /// Set to one of the values. The list of + /// facilities is predefined and cannot be extended. The default value + /// is . + /// + public SyslogFacility Facility + { + get { return this.m_facility; } + set { this.m_facility = value; } + } + + /// + /// Add a mapping of level to severity + /// + /// The mapping to add + /// + /// + /// Adds a to this appender. + /// + /// + public void AddMapping(LevelSeverity mapping) + { + this.m_levelMapping.Add(mapping); + } + + /// + /// Initialize the appender based on the options set. + /// + /// + /// + /// This is part of the delayed object + /// activation scheme. The method must + /// be called on this object after the configuration properties have + /// been set. Until is called this + /// object is in an undefined state and must not be used. + /// + /// + /// If any of the configuration properties are modified then + /// must be called again. + /// + /// +#if NET_4_0 || MONO_4_0 || NETSTANDARD + [System.Security.SecuritySafeCritical] +#endif + public override void ActivateOptions() + { + base.ActivateOptions(); + + this.m_levelMapping.ActivateOptions(); + + string identString = this.m_identity; + if (identString == null) + { + // Set to app name by default + identString = SystemInfo.ApplicationFriendlyName; + } + + // create the native heap ansi string. Note this is a copy of our string + // so we do not need to hold on to the string itself, holding on to the + // handle will keep the heap ansi string alive. + this.m_handleToIdentity = Marshal.StringToHGlobalAnsi(identString); + + // open syslog + openlog(this.m_handleToIdentity, 1, this.m_facility); } - /// - /// Initialize the appender based on the options set. - /// - /// - /// - /// This is part of the delayed object - /// activation scheme. The method must - /// be called on this object after the configuration properties have - /// been set. Until is called this - /// object is in an undefined state and must not be used. - /// - /// - /// If any of the configuration properties are modified then - /// must be called again. - /// - /// -#if NET_4_0 || MONO_4_0 || NETSTANDARD1_3 - [System.Security.SecuritySafeCritical] -#endif - public override void ActivateOptions() - { - base.ActivateOptions(); - - this.m_levelMapping.ActivateOptions(); - - string identString = this.m_identity; - if (identString == null) - { - // Set to app name by default - identString = SystemInfo.ApplicationFriendlyName; - } - - // create the native heap ansi string. Note this is a copy of our string - // so we do not need to hold on to the string itself, holding on to the - // handle will keep the heap ansi string alive. - this.m_handleToIdentity = Marshal.StringToHGlobalAnsi(identString); - - // open syslog - openlog(this.m_handleToIdentity, 1, this.m_facility); + /// + /// This method is called by the method. + /// + /// The event to log. + /// + /// + /// Writes the event to a remote syslog daemon. + /// + /// + /// The format of the output will depend on the appender's layout. + /// + /// +#if NET_4_0 || MONO_4_0 || NETSTANDARD + [System.Security.SecuritySafeCritical] +#endif +#if !NETSTANDARD1_3 + [System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Demand, UnmanagedCode = true)] +#endif + protected override void Append(LoggingEvent loggingEvent) + { + int priority = GeneratePriority(this.m_facility, this.GetSeverity(loggingEvent.Level)); + string message = this.RenderLoggingEvent(loggingEvent); + + // Call the local libc syslog method + // The second argument is a printf style format string + syslog(priority, "%s", message); } - /// - /// This method is called by the method. - /// - /// The event to log. - /// - /// - /// Writes the event to a remote syslog daemon. - /// - /// - /// The format of the output will depend on the appender's layout. - /// - /// -#if NET_4_0 || MONO_4_0 || NETSTANDARD1_3 - [System.Security.SecuritySafeCritical] -#endif -#if !NETSTANDARD1_3 - [System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Demand, UnmanagedCode = true)] -#endif - protected override void Append(LoggingEvent loggingEvent) - { - int priority = GeneratePriority(this.m_facility, this.GetSeverity(loggingEvent.Level)); - string message = this.RenderLoggingEvent(loggingEvent); - - // Call the local libc syslog method - // The second argument is a printf style format string - syslog(priority, "%s", message); + /// + /// Close the syslog when the appender is closed + /// + /// + /// + /// Close the syslog when the appender is closed + /// + /// +#if NET_4_0 || MONO_4_0 || NETSTANDARD + [System.Security.SecuritySafeCritical] +#endif + protected override void OnClose() + { + base.OnClose(); + + try + { + // close syslog + closelog(); + } + catch(DllNotFoundException) + { + // Ignore dll not found at this point + } + + if (this.m_handleToIdentity != IntPtr.Zero) + { + // free global ident + Marshal.FreeHGlobal(this.m_handleToIdentity); + } } - /// - /// Close the syslog when the appender is closed. - /// - /// - /// - /// Close the syslog when the appender is closed. - /// - /// -#if NET_4_0 || MONO_4_0 || NETSTANDARD1_3 - [System.Security.SecuritySafeCritical] -#endif - protected override void OnClose() - { - base.OnClose(); - - try - { - // close syslog - closelog(); - } - catch (DllNotFoundException) - { - // Ignore dll not found at this point - } - - if (this.m_handleToIdentity != IntPtr.Zero) - { - // free global ident - Marshal.FreeHGlobal(this.m_handleToIdentity); - } - } - - /// - /// Gets a value indicating whether this appender requires a to be set. - /// - /// true. - /// - /// - /// This appender requires a to be set. - /// - /// - protected override bool RequiresLayout - { - get { return true; } + /// + /// This appender requires a to be set. + /// + /// true + /// + /// + /// This appender requires a to be set. + /// + /// + protected override bool RequiresLayout + { + get { return true; } } - /// - /// Translates a log4net level to a syslog severity. - /// - /// A log4net level. - /// A syslog severity. - /// - /// - /// Translates a log4net level to a syslog severity. - /// - /// - protected virtual SyslogSeverity GetSeverity(Level level) - { - LevelSeverity levelSeverity = this.m_levelMapping.Lookup(level) as LevelSeverity; - if (levelSeverity != null) - { - return levelSeverity.Severity; - } - - // Fallback to sensible default values - if (level >= Level.Alert) - { - return SyslogSeverity.Alert; - } - else if (level >= Level.Critical) - { - return SyslogSeverity.Critical; - } - else if (level >= Level.Error) - { - return SyslogSeverity.Error; - } - else if (level >= Level.Warn) - { - return SyslogSeverity.Warning; - } - else if (level >= Level.Notice) - { - return SyslogSeverity.Notice; - } - else if (level >= Level.Info) - { - return SyslogSeverity.Informational; - } - - // Default setting - return SyslogSeverity.Debug; + /// + /// Translates a log4net level to a syslog severity. + /// + /// A log4net level. + /// A syslog severity. + /// + /// + /// Translates a log4net level to a syslog severity. + /// + /// + protected virtual SyslogSeverity GetSeverity(Level level) + { + LevelSeverity levelSeverity = this.m_levelMapping.Lookup(level) as LevelSeverity; + if (levelSeverity != null) + { + return levelSeverity.Severity; + } + + // + // Fallback to sensible default values + // + + if (level >= Level.Alert) + { + return SyslogSeverity.Alert; + } + else if (level >= Level.Critical) + { + return SyslogSeverity.Critical; + } + else if (level >= Level.Error) + { + return SyslogSeverity.Error; + } + else if (level >= Level.Warn) + { + return SyslogSeverity.Warning; + } + else if (level >= Level.Notice) + { + return SyslogSeverity.Notice; + } + else if (level >= Level.Info) + { + return SyslogSeverity.Informational; + } + // Default setting + return SyslogSeverity.Debug; } - /// - /// Generate a syslog priority. - /// - /// The syslog facility. - /// The syslog severity. - /// A syslog priority. - private static int GeneratePriority(SyslogFacility facility, SyslogSeverity severity) - { - return ((int)facility * 8) + (int)severity; + /// + /// Generate a syslog priority. + /// + /// The syslog facility. + /// The syslog severity. + /// A syslog priority. + private static int GeneratePriority(SyslogFacility facility, SyslogSeverity severity) + { + return ((int)facility * 8) + (int)severity; } - /// - /// The facility. The default facility is . - /// - private SyslogFacility m_facility = SyslogFacility.User; - - /// - /// The message identity. - /// - private string m_identity; - - /// - /// Marshaled handle to the identity string. We have to hold on to the - /// string as the openlog and syslog APIs just hold the - /// pointer to the ident and dereference it for each log message. - /// - private IntPtr m_handleToIdentity = IntPtr.Zero; - - /// - /// Mapping from level object to syslog severity. - /// + /// + /// The facility. The default facility is . + /// + private SyslogFacility m_facility = SyslogFacility.User; + + /// + /// The message identity + /// + private string m_identity; + + /// + /// Marshaled handle to the identity string. We have to hold on to the + /// string as the openlog and syslog APIs just hold the + /// pointer to the ident and dereference it for each log message. + /// + private IntPtr m_handleToIdentity = IntPtr.Zero; + + /// + /// Mapping from level object to syslog severity + /// private LevelMapping m_levelMapping = new LevelMapping(); - /// - /// Open connection to system logger. - /// - [DllImport("libc")] - private static extern void openlog(IntPtr ident, int option, SyslogFacility facility); - - /// - /// Generate a log message. - /// - /// - /// - /// The libc syslog method takes a format string and a variable argument list similar - /// to the classic printf function. As this type of vararg list is not supported - /// by C# we need to specify the arguments explicitly. Here we have specified the - /// format string with a single message argument. The caller must set the format - /// string to "%s". - /// - /// - [DllImport("libc", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)] - private static extern void syslog(int priority, string format, string message); - - /// - /// Close descriptor used to write to system logger. - /// - [DllImport("libc")] + /// + /// Open connection to system logger. + /// + [DllImport("libc")] + private static extern void openlog(IntPtr ident, int option, SyslogFacility facility); + + /// + /// Generate a log message. + /// + /// + /// + /// The libc syslog method takes a format string and a variable argument list similar + /// to the classic printf function. As this type of vararg list is not supported + /// by C# we need to specify the arguments explicitly. Here we have specified the + /// format string with a single message argument. The caller must set the format + /// string to "%s". + /// + /// + [DllImport("libc", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)] + private static extern void syslog(int priority, string format, string message); + + /// + /// Close descriptor used to write to system logger. + /// + [DllImport("libc")] private static extern void closelog(); - /// - /// A class to act as a mapping between the level that a logging call is made at and - /// the syslog severity that is should be logged at. - /// - /// - /// - /// A class to act as a mapping between the level that a logging call is made at and - /// the syslog severity that is should be logged at. - /// - /// - public class LevelSeverity : LevelMappingEntry - { - private SyslogSeverity m_severity; - - /// - /// Gets or sets the mapped syslog severity for the specified level. - /// - /// - /// - /// Required property. - /// The mapped syslog severity for the specified level. - /// - /// - public SyslogSeverity Severity - { - get { return this.m_severity; } - set { this.m_severity = value; } - } + /// + /// A class to act as a mapping between the level that a logging call is made at and + /// the syslog severity that is should be logged at. + /// + /// + /// + /// A class to act as a mapping between the level that a logging call is made at and + /// the syslog severity that is should be logged at. + /// + /// + public class LevelSeverity : LevelMappingEntry + { + private SyslogSeverity m_severity; + + /// + /// The mapped syslog severity for the specified level + /// + /// + /// + /// Required property. + /// The mapped syslog severity for the specified level + /// + /// + public SyslogSeverity Severity + { + get { return this.m_severity; } + set { this.m_severity = value; } + } } - } -} - -#endif + } +} + +#endif diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/ManagedColoredConsoleAppender.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/ManagedColoredConsoleAppender.cs index c5fb431ebcd..f2403730051 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/ManagedColoredConsoleAppender.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/ManagedColoredConsoleAppender.cs @@ -1,183 +1,181 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -// Compatibility: -// http://msdn.microsoft.com/en-us/library/system.console.foregroundcolor.aspx -// Disable for unsupported targets -#if !NETCF -#if !SSCLI -#if !CLI_1_0 -#if !MONO_1_0 -#if !NET_1_0 -#if !NET_1_1 - -// The original ColoredConsoleAppender was written before the .NET framework -// (and Mono) had built-in support for console colors so it was written using -// Win32 API calls. The AnsiColorTerminalAppender, while it works, isn't -// understood by the Windows command prompt. -// This is a replacement for both that uses the new (.NET 2) Console colors -// and works on both platforms. - -// On Mono/Linux (at least), setting the background color to 'Black' is -// not the same as the default background color, as it is after -// Console.Reset(). The difference becomes apparent while running in a -// terminal application that supports background transparency; the -// default color is treated as transparent while 'Black' isn't. -// For this reason, we always reset the colors and only set those -// explicitly specified in the configuration (Console.BackgroundColor -// isn't set if ommited). -using System; +// Compatibility: +// http://msdn.microsoft.com/en-us/library/system.console.foregroundcolor.aspx +// Disable for unsupported targets +#if !NETCF +#if !SSCLI +#if !CLI_1_0 +#if !MONO_1_0 +#if !NET_1_0 +#if !NET_1_1 -using log4net.Util; - -namespace log4net.Appender -{ - /// - /// Appends colorful logging events to the console, using the .NET 2 - /// built-in capabilities. - /// - /// - /// - /// ManagedColoredConsoleAppender appends log events to the standard output stream - /// or the error output stream using a layout specified by the - /// user. It also allows the color of a specific type of message to be set. - /// - /// - /// By default, all output is written to the console's standard output stream. - /// The property can be set to direct the output to the - /// error stream. - /// - /// - /// When configuring the colored console appender, mappings should be - /// specified to map logging levels to colors. For example: - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// The Level is the standard log4net logging level while - /// ForeColor and BackColor are the values of - /// enumeration. - /// - /// - /// Based on the ColoredConsoleAppender. - /// - /// - /// Rick Hobbs. - /// Nicko Cadell. - /// Pavlos Touboulidis. - public class ManagedColoredConsoleAppender : AppenderSkeleton - { - /// - /// Initializes a new instance of the class. - /// - /// - /// The instance of the class is set up to write - /// to the standard output stream. - /// - public ManagedColoredConsoleAppender() - { +// The original ColoredConsoleAppender was written before the .NET framework +// (and Mono) had built-in support for console colors so it was written using +// Win32 API calls. The AnsiColorTerminalAppender, while it works, isn't +// understood by the Windows command prompt. +// This is a replacement for both that uses the new (.NET 2) Console colors +// and works on both platforms. + +// On Mono/Linux (at least), setting the background color to 'Black' is +// not the same as the default background color, as it is after +// Console.Reset(). The difference becomes apparent while running in a +// terminal application that supports background transparency; the +// default color is treated as transparent while 'Black' isn't. +// For this reason, we always reset the colors and only set those +// explicitly specified in the configuration (Console.BackgroundColor +// isn't set if ommited). + +using System; +using log4net.Util; + +namespace log4net.Appender +{ + /// + /// Appends colorful logging events to the console, using the .NET 2 + /// built-in capabilities. + /// + /// + /// + /// ManagedColoredConsoleAppender appends log events to the standard output stream + /// or the error output stream using a layout specified by the + /// user. It also allows the color of a specific type of message to be set. + /// + /// + /// By default, all output is written to the console's standard output stream. + /// The property can be set to direct the output to the + /// error stream. + /// + /// + /// When configuring the colored console appender, mappings should be + /// specified to map logging levels to colors. For example: + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// The Level is the standard log4net logging level while + /// ForeColor and BackColor are the values of + /// enumeration. + /// + /// + /// Based on the ColoredConsoleAppender + /// + /// + /// Rick Hobbs + /// Nicko Cadell + /// Pavlos Touboulidis + public class ManagedColoredConsoleAppender: AppenderSkeleton + { + /// + /// Initializes a new instance of the class. + /// + /// + /// The instance of the class is set up to write + /// to the standard output stream. + /// + public ManagedColoredConsoleAppender() + { } - /// - /// Gets or sets target is the value of the console output stream. - /// This is either "Console.Out" or "Console.Error". - /// - /// - /// Target is the value of the console output stream. - /// This is either "Console.Out" or "Console.Error". - /// - /// - /// - /// Target is the value of the console output stream. - /// This is either "Console.Out" or "Console.Error". - /// - /// - public virtual string Target - { - get { return this.m_writeToErrorStream ? ConsoleError : ConsoleOut; } + /// + /// Target is the value of the console output stream. + /// This is either "Console.Out" or "Console.Error". + /// + /// + /// Target is the value of the console output stream. + /// This is either "Console.Out" or "Console.Error". + /// + /// + /// + /// Target is the value of the console output stream. + /// This is either "Console.Out" or "Console.Error". + /// + /// + public virtual string Target + { + get { return this.m_writeToErrorStream ? ConsoleError : ConsoleOut; } + set + { + string v = value.Trim(); + + if (SystemInfo.EqualsIgnoringCase(ConsoleError, v)) + { + this.m_writeToErrorStream = true; + } + else + { + this.m_writeToErrorStream = false; + } + } + } - set - { - string v = value.Trim(); - - if (SystemInfo.EqualsIgnoringCase(ConsoleError, v)) - { - this.m_writeToErrorStream = true; - } - else - { - this.m_writeToErrorStream = false; - } - } - } - - /// - /// Add a mapping of level to color - done by the config file. - /// - /// The mapping to add. - /// - /// - /// Add a mapping to this appender. - /// Each mapping defines the foreground and background colors - /// for a level. - /// - /// - public void AddMapping(LevelColors mapping) - { - this.m_levelMapping.Add(mapping); + /// + /// Add a mapping of level to color - done by the config file + /// + /// The mapping to add + /// + /// + /// Add a mapping to this appender. + /// Each mapping defines the foreground and background colors + /// for a level. + /// + /// + public void AddMapping(LevelColors mapping) + { + this.m_levelMapping.Add(mapping); } - /// - /// This method is called by the method. - /// - /// The event to log. - /// - /// - /// Writes the event to the console. - /// - /// - /// The format of the output will depend on the appender's layout. - /// - /// - protected override void Append(log4net.Core.LoggingEvent loggingEvent) - { - System.IO.TextWriter writer; - + /// + /// This method is called by the method. + /// + /// The event to log. + /// + /// + /// Writes the event to the console. + /// + /// + /// The format of the output will depend on the appender's layout. + /// + /// + protected override void Append(Core.LoggingEvent loggingEvent) + { + System.IO.TextWriter writer; + if (this.m_writeToErrorStream) { writer = Console.Error; @@ -188,13 +186,13 @@ protected override void Append(log4net.Core.LoggingEvent loggingEvent) } // Reset color - Console.ResetColor(); - - // see if there is a specified lookup - LevelColors levelColors = this.m_levelMapping.Lookup(loggingEvent.Level) as LevelColors; - if (levelColors != null) - { - // if the backColor has been explicitly set + Console.ResetColor(); + + // see if there is a specified lookup + LevelColors levelColors = this.m_levelMapping.Lookup(loggingEvent.Level) as LevelColors; + if (levelColors != null) + { + // if the backColor has been explicitly set if (levelColors.HasBackColor) { Console.BackgroundColor = levelColors.BackColor; @@ -205,163 +203,156 @@ protected override void Append(log4net.Core.LoggingEvent loggingEvent) { Console.ForegroundColor = levelColors.ForeColor; } - } - - // Render the event to a string - string strLoggingMessage = this.RenderLoggingEvent(loggingEvent); + } + + // Render the event to a string + string strLoggingMessage = this.RenderLoggingEvent(loggingEvent); + // and write it + writer.Write(strLoggingMessage); - // and write it - writer.Write(strLoggingMessage); - - // Reset color again - Console.ResetColor(); - } - - /// - /// Gets a value indicating whether this appender requires a to be set. - /// - /// true. - /// - /// - /// This appender requires a to be set. - /// - /// - protected override bool RequiresLayout - { - get { return true; } - } - - /// - /// Initialize the options for this appender. - /// - /// - /// - /// Initialize the level to color mappings set on this appender. - /// - /// - public override void ActivateOptions() - { - base.ActivateOptions(); - this.m_levelMapping.ActivateOptions(); + // Reset color again + Console.ResetColor(); } - /// - /// The to use when writing to the Console - /// standard output stream. - /// - /// - /// - /// The to use when writing to the Console - /// standard output stream. - /// - /// - public const string ConsoleOut = "Console.Out"; - - /// - /// The to use when writing to the Console - /// standard error output stream. - /// - /// - /// - /// The to use when writing to the Console - /// standard error output stream. - /// - /// + /// + /// This appender requires a to be set. + /// + /// true + /// + /// + /// This appender requires a to be set. + /// + /// + protected override bool RequiresLayout + { + get { return true; } + } + + /// + /// Initialize the options for this appender + /// + /// + /// + /// Initialize the level to color mappings set on this appender. + /// + /// + public override void ActivateOptions() + { + base.ActivateOptions(); + this.m_levelMapping.ActivateOptions(); + } + + /// + /// The to use when writing to the Console + /// standard output stream. + /// + /// + /// + /// The to use when writing to the Console + /// standard output stream. + /// + /// + public const string ConsoleOut = "Console.Out"; + + /// + /// The to use when writing to the Console + /// standard error output stream. + /// + /// + /// + /// The to use when writing to the Console + /// standard error output stream. + /// + /// public const string ConsoleError = "Console.Error"; - /// - /// Flag to write output to the error stream rather than the standard output stream. - /// - private bool m_writeToErrorStream = false; - - /// - /// Mapping from level object to color value. - /// - private LevelMapping m_levelMapping = new LevelMapping(); + /// + /// Flag to write output to the error stream rather than the standard output stream + /// + private bool m_writeToErrorStream = false; - /// - /// A class to act as a mapping between the level that a logging call is made at and - /// the color it should be displayed as. - /// - /// - /// - /// Defines the mapping between a level and the color it should be displayed in. - /// - /// - public class LevelColors : LevelMappingEntry - { - /// - /// Gets or sets the mapped foreground color for the specified level. - /// - /// - /// - /// Required property. - /// The mapped foreground color for the specified level. - /// - /// - public ConsoleColor ForeColor - { - get { return this.foreColor; } + /// + /// Mapping from level object to color value + /// + private LevelMapping m_levelMapping = new LevelMapping(); - // Keep a flag that the color has been set - // and is no longer the default. + /// + /// A class to act as a mapping between the level that a logging call is made at and + /// the color it should be displayed as. + /// + /// + /// + /// Defines the mapping between a level and the color it should be displayed in. + /// + /// + public class LevelColors : LevelMappingEntry + { + /// + /// The mapped foreground color for the specified level + /// + /// + /// + /// Required property. + /// The mapped foreground color for the specified level. + /// + /// + public ConsoleColor ForeColor + { + get { return (this.foreColor); } + // Keep a flag that the color has been set + // and is no longer the default. set { this.foreColor = value; this.hasForeColor = true; - } - } - - private ConsoleColor foreColor; - private bool hasForeColor; - + } + } + private ConsoleColor foreColor; + private bool hasForeColor; internal bool HasForeColor - { + { get - { - return this.hasForeColor; - } - } - - /// - /// Gets or sets the mapped background color for the specified level. - /// - /// - /// - /// Required property. - /// The mapped background color for the specified level. - /// - /// - public ConsoleColor BackColor - { - get { return this.backColor; } + { + return this.hasForeColor; + } + } - // Keep a flag that the color has been set - // and is no longer the default. + /// + /// The mapped background color for the specified level + /// + /// + /// + /// Required property. + /// The mapped background color for the specified level. + /// + /// + public ConsoleColor BackColor + { + get { return (this.backColor); } + // Keep a flag that the color has been set + // and is no longer the default. set { this.backColor = value; this.hasBackColor = true; - } - } - - private ConsoleColor backColor; - private bool hasBackColor; - + } + } + private ConsoleColor backColor; + private bool hasBackColor; internal bool HasBackColor - { + { get - { - return this.hasBackColor; - } - } + { + return this.hasBackColor; + } + } } - } -} - -#endif -#endif -#endif // !MONO_1_0 -#endif // !CLI_1_0 -#endif // !SSCLI -#endif // !NETCF + } +} + +#endif +#endif +#endif // !MONO_1_0 +#endif // !CLI_1_0 +#endif // !SSCLI +#endif // !NETCF diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/MemoryAppender.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/MemoryAppender.cs index 2892a581d5e..62e2f152a46 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/MemoryAppender.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/MemoryAppender.cs @@ -1,208 +1,206 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.Appender -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; - using System.Collections; +using System; +using System.Collections; - using log4net.Core; +using log4net.Core; - /// - /// Stores logging events in an array. - /// - /// - /// - /// The memory appender stores all the logging events - /// that are appended in an in-memory array. - /// - /// - /// Use the method to get - /// and clear the current list of events that have been appended. - /// - /// - /// Use the method to get the current - /// list of events that have been appended. Note there is a - /// race-condition when calling and - /// in pairs, you better use in that case. - /// - /// - /// Use the method to clear the - /// current list of events. Note there is a - /// race-condition when calling and - /// in pairs, you better use in that case. - /// - /// - /// Julian Biddle. - /// Nicko Cadell. - /// Gert Driesen. - public class MemoryAppender : AppenderSkeleton +namespace log4net.Appender +{ + /// + /// Stores logging events in an array. + /// + /// + /// + /// The memory appender stores all the logging events + /// that are appended in an in-memory array. + /// + /// + /// Use the method to get + /// and clear the current list of events that have been appended. + /// + /// + /// Use the method to get the current + /// list of events that have been appended. Note there is a + /// race-condition when calling and + /// in pairs, you better use in that case. + /// + /// + /// Use the method to clear the + /// current list of events. Note there is a + /// race-condition when calling and + /// in pairs, you better use in that case. + /// + /// + /// Julian Biddle + /// Nicko Cadell + /// Gert Driesen + public class MemoryAppender : AppenderSkeleton { - /// - /// Initializes a new instance of the class. - /// - /// - /// - /// Default constructor. - /// - /// - public MemoryAppender() - : base() - { - this.m_eventsList = new ArrayList(); + /// + /// Initializes a new instance of the class. + /// + /// + /// + /// Default constructor. + /// + /// + public MemoryAppender() : base() + { + this.m_eventsList = new ArrayList(); } - /// - /// Gets the events that have been logged. - /// - /// The events that have been logged. - /// - /// - /// Gets the events that have been logged. - /// - /// - public virtual LoggingEvent[] GetEvents() - { - lock (this.m_eventsList.SyncRoot) - { - return (LoggingEvent[])this.m_eventsList.ToArray(typeof(LoggingEvent)); - } - } - - /// - /// Gets or sets a value indicating whether only part of the logging event - /// data should be fixed. - /// - /// - /// true if the appender should only fix part of the logging event - /// data, otherwise false. The default is false. - /// - /// - /// - /// Setting this property to true will cause only part of the event - /// data to be fixed and stored in the appender, hereby improving performance. - /// - /// - /// See for more information. - /// - /// - [Obsolete("Use Fix property. Scheduled removal in v10.0.0.")] - public virtual bool OnlyFixPartialEventData - { - get { return this.Fix == FixFlags.Partial; } + /// + /// Gets the events that have been logged. + /// + /// The events that have been logged + /// + /// + /// Gets the events that have been logged. + /// + /// + public virtual LoggingEvent[] GetEvents() + { + lock (this.m_eventsList.SyncRoot) + { + return (LoggingEvent[])this.m_eventsList.ToArray(typeof(LoggingEvent)); + } + } + + /// + /// Gets or sets a value indicating whether only part of the logging event + /// data should be fixed. + /// + /// + /// true if the appender should only fix part of the logging event + /// data, otherwise false. The default is false. + /// + /// + /// + /// Setting this property to true will cause only part of the event + /// data to be fixed and stored in the appender, hereby improving performance. + /// + /// + /// See for more information. + /// + /// + [Obsolete("Use Fix property")] + public virtual bool OnlyFixPartialEventData + { + get { return (this.Fix == FixFlags.Partial); } + set + { + if (value) + { + this.Fix = FixFlags.Partial; + } + else + { + this.Fix = FixFlags.All; + } + } + } - set - { - if (value) - { - this.Fix = FixFlags.Partial; - } - else - { - this.Fix = FixFlags.All; - } - } - } - - /// - /// Gets or sets the fields that will be fixed in the event. - /// - /// - /// - /// The logging event needs to have certain thread specific values - /// captured before it can be buffered. See - /// for details. - /// - /// - public virtual FixFlags Fix - { - get { return this.m_fixFlags; } - set { this.m_fixFlags = value; } + /// + /// Gets or sets the fields that will be fixed in the event + /// + /// + /// + /// The logging event needs to have certain thread specific values + /// captured before it can be buffered. See + /// for details. + /// + /// + public virtual FixFlags Fix + { + get { return this.m_fixFlags; } + set { this.m_fixFlags = value; } } - /// - /// This method is called by the method. - /// - /// the event to log. - /// - /// Stores the in the events list. - /// - protected override void Append(LoggingEvent loggingEvent) - { - // Because we are caching the LoggingEvent beyond the - // lifetime of the Append() method we must fix any - // volatile data in the event. - loggingEvent.Fix = this.Fix; - - lock (this.m_eventsList.SyncRoot) - { - this.m_eventsList.Add(loggingEvent); - } + /// + /// This method is called by the method. + /// + /// the event to log + /// + /// Stores the in the events list. + /// + protected override void Append(LoggingEvent loggingEvent) + { + // Because we are caching the LoggingEvent beyond the + // lifetime of the Append() method we must fix any + // volatile data in the event. + loggingEvent.Fix = this.Fix; + + lock (this.m_eventsList.SyncRoot) + { + this.m_eventsList.Add(loggingEvent); + } } - /// - /// Clear the list of events. - /// - /// - /// Clear the list of events. - /// - public virtual void Clear() - { - lock (this.m_eventsList.SyncRoot) - { - this.m_eventsList.Clear(); - } - } - - /// - /// Gets the events that have been logged and clears the list of events. - /// - /// The events that have been logged. - /// - /// - /// Gets the events that have been logged and clears the list of events. - /// - /// - public virtual LoggingEvent[] PopAllEvents() - { - lock (this.m_eventsList.SyncRoot) - { - LoggingEvent[] tmp = (LoggingEvent[])this.m_eventsList.ToArray(typeof(LoggingEvent)); - this.m_eventsList.Clear(); - return tmp; - } + /// + /// Clear the list of events + /// + /// + /// Clear the list of events + /// + public virtual void Clear() + { + lock (this.m_eventsList.SyncRoot) + { + this.m_eventsList.Clear(); + } } - /// - /// The list of events that have been appended. - /// - protected ArrayList m_eventsList; - - /// - /// Value indicating which fields in the event should be fixed. - /// - /// - /// By default all fields are fixed. - /// + /// + /// Gets the events that have been logged and clears the list of events. + /// + /// The events that have been logged + /// + /// + /// Gets the events that have been logged and clears the list of events. + /// + /// + public virtual LoggingEvent[] PopAllEvents() + { + lock (this.m_eventsList.SyncRoot) + { + LoggingEvent[] tmp = (LoggingEvent[])this.m_eventsList.ToArray(typeof (LoggingEvent)); + this.m_eventsList.Clear(); + return tmp; + } + } + + /// + /// The list of events that have been appended. + /// + protected ArrayList m_eventsList; + + /// + /// Value indicating which fields in the event should be fixed + /// + /// + /// By default all fields are fixed + /// protected FixFlags m_fixFlags = FixFlags.All; - } -} + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/NetSendAppender.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/NetSendAppender.cs index bcb00acef4b..d0b96842021 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/NetSendAppender.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/NetSendAppender.cs @@ -1,405 +1,402 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -// MONO 1.0 Beta mcs does not like #if !A && !B && !C syntax - -// .NET Compact Framework 1.0 has no support for Win32 NetMessageBufferSend API -#if !NETCF -// MONO 1.0 has no support for Win32 NetMessageBufferSend API -#if !MONO -// SSCLI 1.0 has no support for Win32 NetMessageBufferSend API -#if !SSCLI -// We don't want framework or platform specific code in the CLI version of log4net -#if !CLI_1_0 - -using System; -using System.Globalization; -using System.Runtime.InteropServices; +// MONO 1.0 Beta mcs does not like #if !A && !B && !C syntax -using log4net.Core; -using log4net.Layout; -using log4net.Util; - -namespace log4net.Appender -{ - /// - /// Logs entries by sending network messages using the - /// native function. - /// - /// - /// - /// You can send messages only to names that are active - /// on the network. If you send the message to a user name, - /// that user must be logged on and running the Messenger - /// service to receive the message. - /// - /// - /// The receiver will get a top most window displaying the - /// messages one at a time, therefore this appender should - /// not be used to deliver a high volume of messages. - /// - /// - /// The following table lists some possible uses for this appender : - /// - /// - /// - /// - /// Action - /// Property Value(s) - /// - /// - /// Send a message to a user account on the local machine - /// - /// - /// = <name of the local machine> - /// - /// - /// = <user name> - /// - /// - /// - /// - /// Send a message to a user account on a remote machine - /// - /// - /// = <name of the remote machine> - /// - /// - /// = <user name> - /// - /// - /// - /// - /// Send a message to a domain user account - /// - /// - /// = <name of a domain controller | uninitialized> - /// - /// - /// = <user name> - /// - /// - /// - /// - /// Send a message to all the names in a workgroup or domain - /// - /// - /// = <workgroup name | domain name>* - /// - /// - /// - /// - /// Send a message from the local machine to a remote machine - /// - /// - /// = <name of the local machine | uninitialized> - /// - /// - /// = <name of the remote machine> - /// - /// - /// - /// - /// - /// - /// Note : security restrictions apply for sending - /// network messages, see - /// for more information. - /// - /// - /// - /// - /// An example configuration section to log information - /// using this appender from the local machine, named - /// LOCAL_PC, to machine OPERATOR_PC : - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// Nicko Cadell. - /// Gert Driesen. - public class NetSendAppender : AppenderSkeleton +// .NET Compact Framework 1.0 has no support for Win32 NetMessageBufferSend API +#if !NETCF +// MONO 1.0 has no support for Win32 NetMessageBufferSend API +#if !MONO +// SSCLI 1.0 has no support for Win32 NetMessageBufferSend API +#if !SSCLI +// We don't want framework or platform specific code in the CLI version of log4net +#if !CLI_1_0 + +using System; +using System.Runtime.InteropServices; + +using log4net.Util; +using log4net.Core; + + +namespace log4net.Appender +{ + /// + /// Logs entries by sending network messages using the + /// native function. + /// + /// + /// + /// You can send messages only to names that are active + /// on the network. If you send the message to a user name, + /// that user must be logged on and running the Messenger + /// service to receive the message. + /// + /// + /// The receiver will get a top most window displaying the + /// messages one at a time, therefore this appender should + /// not be used to deliver a high volume of messages. + /// + /// + /// The following table lists some possible uses for this appender : + /// + /// + /// + /// + /// Action + /// Property Value(s) + /// + /// + /// Send a message to a user account on the local machine + /// + /// + /// = <name of the local machine> + /// + /// + /// = <user name> + /// + /// + /// + /// + /// Send a message to a user account on a remote machine + /// + /// + /// = <name of the remote machine> + /// + /// + /// = <user name> + /// + /// + /// + /// + /// Send a message to a domain user account + /// + /// + /// = <name of a domain controller | uninitialized> + /// + /// + /// = <user name> + /// + /// + /// + /// + /// Send a message to all the names in a workgroup or domain + /// + /// + /// = <workgroup name | domain name>* + /// + /// + /// + /// + /// Send a message from the local machine to a remote machine + /// + /// + /// = <name of the local machine | uninitialized> + /// + /// + /// = <name of the remote machine> + /// + /// + /// + /// + /// + /// + /// Note : security restrictions apply for sending + /// network messages, see + /// for more information. + /// + /// + /// + /// + /// An example configuration section to log information + /// using this appender from the local machine, named + /// LOCAL_PC, to machine OPERATOR_PC : + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// Nicko Cadell + /// Gert Driesen + public class NetSendAppender : AppenderSkeleton { - /// - /// The DNS or NetBIOS name of the server on which the function is to execute. - /// - private string m_server; - - /// - /// The sender of the network message. - /// - private string m_sender; - - /// - /// The message alias to which the message should be sent. - /// - private string m_recipient; - - /// - /// The security context to use for privileged calls. - /// + /// + /// The DNS or NetBIOS name of the server on which the function is to execute. + /// + private string m_server; + + /// + /// The sender of the network message. + /// + private string m_sender; + + /// + /// The message alias to which the message should be sent. + /// + private string m_recipient; + + /// + /// The security context to use for privileged calls + /// private SecurityContext m_securityContext; /// - /// Initializes a new instance of the class. - /// Initializes the appender. - /// - /// - /// The default constructor initializes all fields to their default values. - /// - public NetSendAppender() - { + /// Initializes the appender. + /// + /// + /// The default constructor initializes all fields to their default values. + /// + public NetSendAppender() + { + } + + /// + /// Gets or sets the sender of the message. + /// + /// + /// The sender of the message. + /// + /// + /// If this property is not specified, the message is sent from the local computer. + /// + public string Sender + { + get { return this.m_sender; } + set { this.m_sender = value; } + } + + /// + /// Gets or sets the message alias to which the message should be sent. + /// + /// + /// The recipient of the message. + /// + /// + /// This property should always be specified in order to send a message. + /// + public string Recipient + { + get { return this.m_recipient; } + set { this.m_recipient = value; } + } + + /// + /// Gets or sets the DNS or NetBIOS name of the remote server on which the function is to execute. + /// + /// + /// DNS or NetBIOS name of the remote server on which the function is to execute. + /// + /// + /// + /// For Windows NT 4.0 and earlier, the string should begin with \\. + /// + /// + /// If this property is not specified, the local computer is used. + /// + /// + public string Server + { + get { return this.m_server; } + set { this.m_server = value; } + } + + /// + /// Gets or sets the used to call the NetSend method. + /// + /// + /// The used to call the NetSend method. + /// + /// + /// + /// Unless a specified here for this appender + /// the is queried for the + /// security context to use. The default behavior is to use the security context + /// of the current thread. + /// + /// + public SecurityContext SecurityContext + { + get { return this.m_securityContext; } + set { this.m_securityContext = value; } } - /// - /// Gets or sets the sender of the message. - /// - /// - /// The sender of the message. - /// - /// - /// If this property is not specified, the message is sent from the local computer. - /// - public string Sender - { - get { return this.m_sender; } - set { this.m_sender = value; } - } - - /// - /// Gets or sets the message alias to which the message should be sent. - /// - /// - /// The recipient of the message. - /// - /// - /// This property should always be specified in order to send a message. - /// - public string Recipient - { - get { return this.m_recipient; } - set { this.m_recipient = value; } - } - - /// - /// Gets or sets the DNS or NetBIOS name of the remote server on which the function is to execute. - /// - /// - /// DNS or NetBIOS name of the remote server on which the function is to execute. - /// - /// - /// - /// For Windows NT 4.0 and earlier, the string should begin with \\. - /// - /// - /// If this property is not specified, the local computer is used. - /// - /// - public string Server - { - get { return this.m_server; } - set { this.m_server = value; } - } - - /// - /// Gets or sets the used to call the NetSend method. - /// - /// - /// The used to call the NetSend method. - /// - /// - /// - /// Unless a specified here for this appender - /// the is queried for the - /// security context to use. The default behavior is to use the security context - /// of the current thread. - /// - /// - public SecurityContext SecurityContext - { - get { return this.m_securityContext; } - set { this.m_securityContext = value; } + /// + /// Initialize the appender based on the options set. + /// + /// + /// + /// This is part of the delayed object + /// activation scheme. The method must + /// be called on this object after the configuration properties have + /// been set. Until is called this + /// object is in an undefined state and must not be used. + /// + /// + /// If any of the configuration properties are modified then + /// must be called again. + /// + /// + /// The appender will be ignored if no was specified. + /// + /// + /// The required property was not specified. + public override void ActivateOptions() + { + base.ActivateOptions(); + + if (this.Recipient == null) + { + throw new ArgumentNullException("Recipient", "The required property 'Recipient' was not specified."); + } + + if (this.m_securityContext == null) + { + this.m_securityContext = SecurityContextProvider.DefaultProvider.CreateSecurityContext(this); + } } - /// - /// Initialize the appender based on the options set. - /// - /// - /// - /// This is part of the delayed object - /// activation scheme. The method must - /// be called on this object after the configuration properties have - /// been set. Until is called this - /// object is in an undefined state and must not be used. - /// - /// - /// If any of the configuration properties are modified then - /// must be called again. - /// - /// - /// The appender will be ignored if no was specified. - /// - /// - /// The required property was not specified. - public override void ActivateOptions() - { - base.ActivateOptions(); - - if (this.Recipient == null) - { - throw new ArgumentNullException("Recipient", "The required property 'Recipient' was not specified."); - } - - if (this.m_securityContext == null) - { - this.m_securityContext = SecurityContextProvider.DefaultProvider.CreateSecurityContext(this); - } + /// + /// This method is called by the method. + /// + /// The event to log. + /// + /// + /// Sends the event using a network message. + /// + /// +#if NET_4_0 || MONO_4_0 || NETSTANDARD + [System.Security.SecuritySafeCritical] +#endif +#if !NETSTANDARD1_3 + [System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Demand, UnmanagedCode = true)] +#endif + protected override void Append(LoggingEvent loggingEvent) + { + NativeError nativeError = null; + + // Render the event in the callers security context + string renderedLoggingEvent = this.RenderLoggingEvent(loggingEvent); + + using(this.m_securityContext.Impersonate(this)) + { + // Send the message + int returnValue = NetMessageBufferSend(this.Server, this.Recipient, this.Sender, renderedLoggingEvent, renderedLoggingEvent.Length * Marshal.SystemDefaultCharSize); + + // Log the error if the message could not be sent + if (returnValue != 0) + { + // Lookup the native error + nativeError = NativeError.GetError(returnValue); + } + } + + if (nativeError != null) + { + // Handle the error over to the ErrorHandler + this.ErrorHandler.Error(nativeError.ToString() + " (Params: Server=" + this.Server + ", Recipient=" + this.Recipient + ", Sender=" + this.Sender + ")"); + } } - /// - /// This method is called by the method. - /// - /// The event to log. - /// - /// - /// Sends the event using a network message. - /// - /// -#if NET_4_0 || MONO_4_0 || NETSTANDARD1_3 - [System.Security.SecuritySafeCritical] -#endif -#if !NETSTANDARD1_3 - [System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Demand, UnmanagedCode = true)] -#endif - protected override void Append(LoggingEvent loggingEvent) - { - NativeError nativeError = null; - - // Render the event in the callers security context - string renderedLoggingEvent = this.RenderLoggingEvent(loggingEvent); - - using (this.m_securityContext.Impersonate(this)) - { - // Send the message - int returnValue = NetMessageBufferSend(this.Server, this.Recipient, this.Sender, renderedLoggingEvent, renderedLoggingEvent.Length * Marshal.SystemDefaultCharSize); - - // Log the error if the message could not be sent - if (returnValue != 0) - { - // Lookup the native error - nativeError = NativeError.GetError(returnValue); - } - } - - if (nativeError != null) - { - // Handle the error over to the ErrorHandler - this.ErrorHandler.Error(nativeError.ToString() + " (Params: Server=" + this.Server + ", Recipient=" + this.Recipient + ", Sender=" + this.Sender + ")"); - } - } - - /// - /// Gets a value indicating whether this appender requires a to be set. - /// - /// true. - /// - /// - /// This appender requires a to be set. - /// - /// - protected override bool RequiresLayout - { - get { return true; } + /// + /// This appender requires a to be set. + /// + /// true + /// + /// + /// This appender requires a to be set. + /// + /// + protected override bool RequiresLayout + { + get { return true; } } - /// - /// Sends a buffer of information to a registered message alias. - /// - /// The DNS or NetBIOS name of the server on which the function is to execute. - /// The message alias to which the message buffer should be sent. - /// The originator of the message. - /// The message text. - /// The length, in bytes, of the message text. - /// - /// - /// The following restrictions apply for sending network messages: - /// - /// - /// - /// - /// Platform - /// Requirements - /// - /// - /// Windows NT - /// - /// - /// No special group membership is required to send a network message. - /// - /// - /// Admin, Accounts, Print, or Server Operator group membership is required to - /// successfully send a network message on a remote server. - /// - /// - /// - /// - /// Windows 2000 or later - /// - /// - /// If you send a message on a domain controller that is running Active Directory, - /// access is allowed or denied based on the access control list (ACL) for the securable - /// object. The default ACL permits only Domain Admins and Account Operators to send a network message. - /// - /// - /// On a member server or workstation, only Administrators and Server Operators can send a network message. - /// - /// - /// - /// - /// - /// - /// For more information see Security Requirements for the Network Management Functions. - /// - /// - /// - /// - /// If the function succeeds, the return value is zero. - /// - /// - [DllImport("netapi32.dll", SetLastError = true)] - protected static extern int NetMessageBufferSend( - [MarshalAs(UnmanagedType.LPWStr)] string serverName, - [MarshalAs(UnmanagedType.LPWStr)] string msgName, - [MarshalAs(UnmanagedType.LPWStr)] string fromName, - [MarshalAs(UnmanagedType.LPWStr)] string buffer, + /// + /// Sends a buffer of information to a registered message alias. + /// + /// The DNS or NetBIOS name of the server on which the function is to execute. + /// The message alias to which the message buffer should be sent + /// The originator of the message. + /// The message text. + /// The length, in bytes, of the message text. + /// + /// + /// The following restrictions apply for sending network messages: + /// + /// + /// + /// + /// Platform + /// Requirements + /// + /// + /// Windows NT + /// + /// + /// No special group membership is required to send a network message. + /// + /// + /// Admin, Accounts, Print, or Server Operator group membership is required to + /// successfully send a network message on a remote server. + /// + /// + /// + /// + /// Windows 2000 or later + /// + /// + /// If you send a message on a domain controller that is running Active Directory, + /// access is allowed or denied based on the access control list (ACL) for the securable + /// object. The default ACL permits only Domain Admins and Account Operators to send a network message. + /// + /// + /// On a member server or workstation, only Administrators and Server Operators can send a network message. + /// + /// + /// + /// + /// + /// + /// For more information see Security Requirements for the Network Management Functions. + /// + /// + /// + /// + /// If the function succeeds, the return value is zero. + /// + /// + [DllImport("netapi32.dll", SetLastError=true)] + protected static extern int NetMessageBufferSend( + [MarshalAs(UnmanagedType.LPWStr)] string serverName, + [MarshalAs(UnmanagedType.LPWStr)] string msgName, + [MarshalAs(UnmanagedType.LPWStr)] string fromName, + [MarshalAs(UnmanagedType.LPWStr)] string buffer, int bufferSize); - } -} - -#endif // !CLI_1_0 -#endif // !SSCLI -#endif // !MONO -#endif // !NETCF + } +} + +#endif // !CLI_1_0 +#endif // !SSCLI +#endif // !MONO +#endif // !NETCF diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/OutputDebugStringAppender.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/OutputDebugStringAppender.cs index ecbbc7b26ba..ac92497e7a1 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/OutputDebugStringAppender.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/OutputDebugStringAppender.cs @@ -1,125 +1,124 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -// MONO 1.0 has no support for Win32 OutputDebugString API -#if !MONO -// SSCLI 1.0 has no support for Win32 OutputDebugString API -#if !SSCLI -// We don't want framework or platform specific code in the CLI version of log4net -#if !CLI_1_0 - -using System.Runtime.InteropServices; +// MONO 1.0 has no support for Win32 OutputDebugString API +#if !MONO +// SSCLI 1.0 has no support for Win32 OutputDebugString API +#if !SSCLI +// We don't want framework or platform specific code in the CLI version of log4net +#if !CLI_1_0 -using log4net.Core; -using log4net.Layout; - -namespace log4net.Appender -{ - /// - /// Appends log events to the OutputDebugString system. - /// - /// - /// - /// OutputDebugStringAppender appends log events to the - /// OutputDebugString system. - /// - /// - /// The string is passed to the native OutputDebugString - /// function. - /// - /// - /// Nicko Cadell. - /// Gert Driesen. - public class OutputDebugStringAppender : AppenderSkeleton +using System.Runtime.InteropServices; + +using log4net.Core; + +namespace log4net.Appender +{ + /// + /// Appends log events to the OutputDebugString system. + /// + /// + /// + /// OutputDebugStringAppender appends log events to the + /// OutputDebugString system. + /// + /// + /// The string is passed to the native OutputDebugString + /// function. + /// + /// + /// Nicko Cadell + /// Gert Driesen + public class OutputDebugStringAppender : AppenderSkeleton { - /// - /// Initializes a new instance of the class. - /// - /// - /// - /// Default constructor. - /// - /// - public OutputDebugStringAppender() - { + /// + /// Initializes a new instance of the class. + /// + /// + /// + /// Default constructor. + /// + /// + public OutputDebugStringAppender() + { } - /// - /// Write the logging event to the output debug string API. - /// - /// the event to log. - /// - /// - /// Write the logging event to the output debug string API. - /// - /// -#if NET_4_0 || MONO_4_0 || NETSTANDARD1_3 - [System.Security.SecuritySafeCritical] -#elif !NETCF - [System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Demand, UnmanagedCode = true)] -#endif - protected override void Append(LoggingEvent loggingEvent) - { -#if NETSTANDARD1_3 - if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) - { - throw new System.PlatformNotSupportedException("OutputDebugString is only available on Windows"); - } -#endif - - OutputDebugString(this.RenderLoggingEvent(loggingEvent)); - } - - /// - /// Gets a value indicating whether this appender requires a to be set. - /// - /// true. - /// - /// - /// This appender requires a to be set. - /// - /// - protected override bool RequiresLayout - { - get { return true; } + /// + /// Write the logging event to the output debug string API + /// + /// the event to log + /// + /// + /// Write the logging event to the output debug string API + /// + /// +#if NET_4_0 || MONO_4_0 || NETSTANDARD + [System.Security.SecuritySafeCritical] +#endif +#if !NETCF && !NETSTANDARD1_3 + [System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Demand, UnmanagedCode = true)] +#endif + protected override void Append(LoggingEvent loggingEvent) + { +#if NETSTANDARD + if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + { + throw new System.PlatformNotSupportedException("OutputDebugString is only available on Windows"); + } +#endif + + OutputDebugString(this.RenderLoggingEvent(loggingEvent)); + } + + /// + /// This appender requires a to be set. + /// + /// true + /// + /// + /// This appender requires a to be set. + /// + /// + protected override bool RequiresLayout + { + get { return true; } } - /// - /// Stub for OutputDebugString native method. - /// - /// the string to output. - /// - /// - /// Stub for OutputDebugString native method. - /// - /// -#if NETCF - [DllImport("CoreDll.dll")] -#else - [DllImport("Kernel32.dll")] -#endif + /// + /// Stub for OutputDebugString native method + /// + /// the string to output + /// + /// + /// Stub for OutputDebugString native method + /// + /// +#if NETCF || NETSTANDARD + [DllImport("CoreDll.dll")] +#else + [DllImport("Kernel32.dll")] +#endif protected static extern void OutputDebugString(string message); - } -} - -#endif // !CLI_1_0 -#endif // !SSCLI -#endif // !MONO + } +} + +#endif // !CLI_1_0 +#endif // !SSCLI +#endif // !MONO diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/RemoteSyslogAppender.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/RemoteSyslogAppender.cs index aca29e4a43a..e68501ab1b7 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/RemoteSyslogAppender.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/RemoteSyslogAppender.cs @@ -1,566 +1,566 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.Appender -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; - using System.Text; - - using log4net.Appender; - using log4net.Core; - using log4net.Layout; - using log4net.Util; - - /// - /// Logs events to a remote syslog daemon. - /// - /// - /// - /// The BSD syslog protocol is used to remotely log to - /// a syslog daemon. The syslogd listens for for messages - /// on UDP port 514. - /// - /// - /// The syslog UDP protocol is not authenticated. Most syslog daemons - /// do not accept remote log messages because of the security implications. - /// You may be able to use the LocalSyslogAppender to talk to a local - /// syslog service. - /// - /// - /// There is an RFC 3164 that claims to document the BSD Syslog Protocol. - /// This RFC can be seen here: http://www.faqs.org/rfcs/rfc3164.html. - /// This appender generates what the RFC calls an "Original Device Message", - /// i.e. does not include the TIMESTAMP or HOSTNAME fields. By observation - /// this format of message will be accepted by all current syslog daemon - /// implementations. The daemon will attach the current time and the source - /// hostname or IP address to any messages received. - /// - /// - /// Syslog messages must have a facility and and a severity. The severity - /// is derived from the Level of the logging event. - /// The facility must be chosen from the set of defined syslog - /// values. The facilities list is predefined - /// and cannot be extended. - /// - /// - /// An identifier is specified with each log message. This can be specified - /// by setting the property. The identity (also know - /// as the tag) must not contain white space. The default value for the - /// identity is the application name (from ). - /// - /// - /// Rob Lyon. - /// Nicko Cadell. - public class RemoteSyslogAppender : UdpAppender - { - /// - /// Syslog port 514. - /// +using System; + +using log4net.Core; +using log4net.Appender; +using log4net.Util; +using log4net.Layout; +using System.Text; + +namespace log4net.Appender +{ + /// + /// Logs events to a remote syslog daemon. + /// + /// + /// + /// The BSD syslog protocol is used to remotely log to + /// a syslog daemon. The syslogd listens for for messages + /// on UDP port 514. + /// + /// + /// The syslog UDP protocol is not authenticated. Most syslog daemons + /// do not accept remote log messages because of the security implications. + /// You may be able to use the LocalSyslogAppender to talk to a local + /// syslog service. + /// + /// + /// There is an RFC 3164 that claims to document the BSD Syslog Protocol. + /// This RFC can be seen here: http://www.faqs.org/rfcs/rfc3164.html. + /// This appender generates what the RFC calls an "Original Device Message", + /// i.e. does not include the TIMESTAMP or HOSTNAME fields. By observation + /// this format of message will be accepted by all current syslog daemon + /// implementations. The daemon will attach the current time and the source + /// hostname or IP address to any messages received. + /// + /// + /// Syslog messages must have a facility and and a severity. The severity + /// is derived from the Level of the logging event. + /// The facility must be chosen from the set of defined syslog + /// values. The facilities list is predefined + /// and cannot be extended. + /// + /// + /// An identifier is specified with each log message. This can be specified + /// by setting the property. The identity (also know + /// as the tag) must not contain white space. The default value for the + /// identity is the application name (from ). + /// + /// + /// Rob Lyon + /// Nicko Cadell + public class RemoteSyslogAppender : UdpAppender + { + /// + /// Syslog port 514 + /// private const int DefaultSyslogPort = 514; - /// - /// syslog severities. - /// - /// - /// - /// The syslog severities. - /// - /// - public enum SyslogSeverity - { - /// - /// system is unusable - /// - Emergency = 0, - - /// - /// action must be taken immediately - /// - Alert = 1, - - /// - /// critical conditions - /// - Critical = 2, - - /// - /// error conditions - /// - Error = 3, - - /// - /// warning conditions - /// - Warning = 4, - - /// - /// normal but significant condition - /// - Notice = 5, - - /// - /// informational - /// - Informational = 6, - - /// - /// debug-level messages - /// - Debug = 7, - } - - /// - /// syslog facilities. - /// - /// - /// - /// The syslog facilities. - /// - /// - public enum SyslogFacility - { - /// - /// kernel messages - /// - Kernel = 0, - - /// - /// random user-level messages - /// - User = 1, - - /// - /// mail system - /// - Mail = 2, - - /// - /// system daemons - /// - Daemons = 3, - - /// - /// security/authorization messages - /// - Authorization = 4, - - /// - /// messages generated internally by syslogd - /// - Syslog = 5, - - /// - /// line printer subsystem - /// - Printer = 6, - - /// - /// network news subsystem - /// - News = 7, - - /// - /// UUCP subsystem - /// - Uucp = 8, - - /// - /// clock (cron/at) daemon - /// - Clock = 9, - - /// - /// security/authorization messages (private) - /// - Authorization2 = 10, - - /// - /// ftp daemon - /// - Ftp = 11, - - /// - /// NTP subsystem - /// - Ntp = 12, - - /// - /// log audit - /// - Audit = 13, - - /// - /// log alert - /// - Alert = 14, - - /// - /// clock daemon - /// - Clock2 = 15, - - /// - /// reserved for local use - /// - Local0 = 16, - - /// - /// reserved for local use - /// - Local1 = 17, - - /// - /// reserved for local use - /// - Local2 = 18, - - /// - /// reserved for local use - /// - Local3 = 19, - - /// - /// reserved for local use - /// - Local4 = 20, - - /// - /// reserved for local use - /// - Local5 = 21, - - /// - /// reserved for local use - /// - Local6 = 22, - - /// - /// reserved for local use - /// - Local7 = 23, + /// + /// syslog severities + /// + /// + /// + /// The syslog severities. + /// + /// + public enum SyslogSeverity + { + /// + /// system is unusable + /// + Emergency = 0, + + /// + /// action must be taken immediately + /// + Alert = 1, + + /// + /// critical conditions + /// + Critical = 2, + + /// + /// error conditions + /// + Error = 3, + + /// + /// warning conditions + /// + Warning = 4, + + /// + /// normal but significant condition + /// + Notice = 5, + + /// + /// informational + /// + Informational = 6, + + /// + /// debug-level messages + /// + Debug = 7 + }; + + /// + /// syslog facilities + /// + /// + /// + /// The syslog facilities + /// + /// + public enum SyslogFacility + { + /// + /// kernel messages + /// + Kernel = 0, + + /// + /// random user-level messages + /// + User = 1, + + /// + /// mail system + /// + Mail = 2, + + /// + /// system daemons + /// + Daemons = 3, + + /// + /// security/authorization messages + /// + Authorization = 4, + + /// + /// messages generated internally by syslogd + /// + Syslog = 5, + + /// + /// line printer subsystem + /// + Printer = 6, + + /// + /// network news subsystem + /// + News = 7, + + /// + /// UUCP subsystem + /// + Uucp = 8, + + /// + /// clock (cron/at) daemon + /// + Clock = 9, + + /// + /// security/authorization messages (private) + /// + Authorization2 = 10, + + /// + /// ftp daemon + /// + Ftp = 11, + + /// + /// NTP subsystem + /// + Ntp = 12, + + /// + /// log audit + /// + Audit = 13, + + /// + /// log alert + /// + Alert = 14, + + /// + /// clock daemon + /// + Clock2 = 15, + + /// + /// reserved for local use + /// + Local0 = 16, + + /// + /// reserved for local use + /// + Local1 = 17, + + /// + /// reserved for local use + /// + Local2 = 18, + + /// + /// reserved for local use + /// + Local3 = 19, + + /// + /// reserved for local use + /// + Local4 = 20, + + /// + /// reserved for local use + /// + Local5 = 21, + + /// + /// reserved for local use + /// + Local6 = 22, + + /// + /// reserved for local use + /// + Local7 = 23 } - /// - /// Initializes a new instance of the class. - /// - /// - /// This instance of the class is set up to write - /// to a remote syslog daemon. - /// - public RemoteSyslogAppender() - { - // syslog udp defaults - this.RemotePort = DefaultSyslogPort; - this.RemoteAddress = System.Net.IPAddress.Parse("127.0.0.1"); - this.Encoding = System.Text.Encoding.ASCII; + /// + /// Initializes a new instance of the class. + /// + /// + /// This instance of the class is set up to write + /// to a remote syslog daemon. + /// + public RemoteSyslogAppender() + { + // syslog udp defaults + this.RemotePort = DefaultSyslogPort; + this.RemoteAddress = System.Net.IPAddress.Parse("127.0.0.1"); + this.Encoding = Encoding.ASCII; } - /// - /// Gets or sets message identity. - /// - /// - /// - /// An identifier is specified with each log message. This can be specified - /// by setting the property. The identity (also know - /// as the tag) must not contain white space. The default value for the - /// identity is the application name (from ). - /// - /// - public PatternLayout Identity - { - get { return this.m_identity; } - set { this.m_identity = value; } - } - - /// - /// Gets or sets syslog facility. - /// - /// - /// Set to one of the values. The list of - /// facilities is predefined and cannot be extended. The default value - /// is . - /// - public SyslogFacility Facility - { - get { return this.m_facility; } - set { this.m_facility = value; } + /// + /// Message identity + /// + /// + /// + /// An identifier is specified with each log message. This can be specified + /// by setting the property. The identity (also know + /// as the tag) must not contain white space. The default value for the + /// identity is the application name (from ). + /// + /// + public PatternLayout Identity + { + get { return this.m_identity; } + set { this.m_identity = value; } } - /// - /// Add a mapping of level to severity. - /// - /// The mapping to add. - /// - /// - /// Add a mapping to this appender. - /// - /// - public void AddMapping(LevelSeverity mapping) - { - this.m_levelMapping.Add(mapping); + /// + /// Syslog facility + /// + /// + /// Set to one of the values. The list of + /// facilities is predefined and cannot be extended. The default value + /// is . + /// + public SyslogFacility Facility + { + get { return this.m_facility; } + set { this.m_facility = value; } } - /// - /// This method is called by the method. - /// - /// The event to log. - /// - /// - /// Writes the event to a remote syslog daemon. - /// - /// - /// The format of the output will depend on the appender's layout. - /// - /// - protected override void Append(LoggingEvent loggingEvent) - { - try - { - // Priority - int priority = GeneratePriority(this.m_facility, this.GetSeverity(loggingEvent.Level)); - - // Identity - string identity; - - if (this.m_identity != null) - { - identity = this.m_identity.Format(loggingEvent); - } - else - { - identity = loggingEvent.Domain; - } - - // Message. The message goes after the tag/identity - string message = this.RenderLoggingEvent(loggingEvent); - - byte[] buffer; - int i = 0; - char c; - - StringBuilder builder = new StringBuilder(); - - while (i < message.Length) - { - // Clear StringBuilder - builder.Length = 0; - - // Write priority - builder.Append('<'); - builder.Append(priority); - builder.Append('>'); - - // Write identity - builder.Append(identity); - builder.Append(": "); - - for (; i < message.Length; i++) - { - c = message[i]; - - // Accept only visible ASCII characters and space. See RFC 3164 section 4.1.3 - if (((int)c >= 32) && ((int)c <= 126)) - { - builder.Append(c); - } - - // If character is newline, break and send the current line - else if ((c == '\r') || (c == '\n')) - { - // Check the next character to handle \r\n or \n\r - if ((message.Length > i + 1) && ((message[i + 1] == '\r') || (message[i + 1] == '\n'))) - { - i++; - } - - i++; - break; - } - } - - // Grab as a byte array - buffer = this.Encoding.GetBytes(builder.ToString()); - -#if NETSTANDARD1_3 - Client.SendAsync(buffer, buffer.Length, RemoteEndPoint).Wait(); -#else - this.Client.Send(buffer, buffer.Length, this.RemoteEndPoint); -#endif - } - } - catch (Exception e) - { - this.ErrorHandler.Error( - "Unable to send logging event to remote syslog " + - this.RemoteAddress.ToString() + - " on port " + - this.RemotePort + ".", - e, - ErrorCode.WriteFailure); - } - } - - /// - /// Initialize the options for this appender. - /// - /// - /// - /// Initialize the level to syslog severity mappings set on this appender. - /// - /// - public override void ActivateOptions() - { - base.ActivateOptions(); - this.m_levelMapping.ActivateOptions(); + /// + /// Add a mapping of level to severity + /// + /// The mapping to add + /// + /// + /// Add a mapping to this appender. + /// + /// + public void AddMapping(LevelSeverity mapping) + { + this.m_levelMapping.Add(mapping); } - /// - /// Translates a log4net level to a syslog severity. - /// - /// A log4net level. - /// A syslog severity. - /// - /// - /// Translates a log4net level to a syslog severity. - /// - /// - protected virtual SyslogSeverity GetSeverity(Level level) - { - LevelSeverity levelSeverity = this.m_levelMapping.Lookup(level) as LevelSeverity; - if (levelSeverity != null) - { - return levelSeverity.Severity; - } - - // Fallback to sensible default values - if (level >= Level.Alert) - { - return SyslogSeverity.Alert; - } - else if (level >= Level.Critical) - { - return SyslogSeverity.Critical; - } - else if (level >= Level.Error) - { - return SyslogSeverity.Error; - } - else if (level >= Level.Warn) - { - return SyslogSeverity.Warning; - } - else if (level >= Level.Notice) - { - return SyslogSeverity.Notice; - } - else if (level >= Level.Info) - { - return SyslogSeverity.Informational; - } - - // Default setting - return SyslogSeverity.Debug; + /// + /// This method is called by the method. + /// + /// The event to log. + /// + /// + /// Writes the event to a remote syslog daemon. + /// + /// + /// The format of the output will depend on the appender's layout. + /// + /// + protected override void Append(LoggingEvent loggingEvent) + { + try + { + // Priority + int priority = GeneratePriority(this.m_facility, this.GetSeverity(loggingEvent.Level)); + + // Identity + string identity; + + if (this.m_identity != null) + { + identity = this.m_identity.Format(loggingEvent); + } + else + { + identity = loggingEvent.Domain; + } + + // Message. The message goes after the tag/identity + string message = this.RenderLoggingEvent(loggingEvent); + + Byte[] buffer; + int i = 0; + char c; + + StringBuilder builder = new StringBuilder(); + + while (i < message.Length) + { + // Clear StringBuilder + builder.Length = 0; + + // Write priority + builder.Append('<'); + builder.Append(priority); + builder.Append('>'); + + // Write identity + builder.Append(identity); + builder.Append(": "); + + for (; i < message.Length; i++) + { + c = message[i]; + + // Accept only visible ASCII characters and space. See RFC 3164 section 4.1.3 + if (((int)c >= 32) && ((int)c <= 126)) + { + builder.Append(c); + } + // If character is newline, break and send the current line + else if ((c == '\r') || (c == '\n')) + { + // Check the next character to handle \r\n or \n\r + if ((message.Length > i + 1) && ((message[i + 1] == '\r') || (message[i + 1] == '\n'))) + { + i++; + } + i++; + break; + } + } + + // Grab as a byte array + buffer = this.Encoding.GetBytes(builder.ToString()); + +#if NET_4_5 || NETSTANDARD + this.Client.SendAsync(buffer, buffer.Length, this.RemoteEndPoint).Wait(); +#else + this.Client.Send(buffer, buffer.Length, this.RemoteEndPoint); +#endif + } + } + catch (Exception e) + { + this.ErrorHandler.Error( + "Unable to send logging event to remote syslog " + + this.RemoteAddress.ToString() + + " on port " + + this.RemotePort + ".", + e, + ErrorCode.WriteFailure); + } + } + + /// + /// Initialize the options for this appender + /// + /// + /// + /// Initialize the level to syslog severity mappings set on this appender. + /// + /// + public override void ActivateOptions() + { + base.ActivateOptions(); + this.m_levelMapping.ActivateOptions(); + } + + /// + /// Translates a log4net level to a syslog severity. + /// + /// A log4net level. + /// A syslog severity. + /// + /// + /// Translates a log4net level to a syslog severity. + /// + /// + protected virtual SyslogSeverity GetSeverity(Level level) + { + LevelSeverity levelSeverity = this.m_levelMapping.Lookup(level) as LevelSeverity; + if (levelSeverity != null) + { + return levelSeverity.Severity; + } + + // + // Fallback to sensible default values + // + + if (level >= Level.Alert) + { + return SyslogSeverity.Alert; + } + else if (level >= Level.Critical) + { + return SyslogSeverity.Critical; + } + else if (level >= Level.Error) + { + return SyslogSeverity.Error; + } + else if (level >= Level.Warn) + { + return SyslogSeverity.Warning; + } + else if (level >= Level.Notice) + { + return SyslogSeverity.Notice; + } + else if (level >= Level.Info) + { + return SyslogSeverity.Informational; + } + // Default setting + return SyslogSeverity.Debug; } - /// - /// Generate a syslog priority. - /// - /// The syslog facility. - /// The syslog severity. - /// A syslog priority. - /// - /// - /// Generate a syslog priority. - /// - /// - public static int GeneratePriority(SyslogFacility facility, SyslogSeverity severity) - { - if (facility < SyslogFacility.Kernel || facility > SyslogFacility.Local7) - { - throw new ArgumentException("SyslogFacility out of range", "facility"); - } - - if (severity < SyslogSeverity.Emergency || severity > SyslogSeverity.Debug) - { - throw new ArgumentException("SyslogSeverity out of range", "severity"); - } - - unchecked - { - return ((int)facility * 8) + (int)severity; - } + /// + /// Generate a syslog priority. + /// + /// The syslog facility. + /// The syslog severity. + /// A syslog priority. + /// + /// + /// Generate a syslog priority. + /// + /// + public static int GeneratePriority(SyslogFacility facility, SyslogSeverity severity) + { + if (facility < SyslogFacility.Kernel || facility > SyslogFacility.Local7) + { + throw new ArgumentException("SyslogFacility out of range", "facility"); + } + + if (severity < SyslogSeverity.Emergency || severity > SyslogSeverity.Debug) + { + throw new ArgumentException("SyslogSeverity out of range", "severity"); + } + + unchecked + { + return ((int)facility * 8) + (int)severity; + } } - /// - /// The facility. The default facility is . - /// - private SyslogFacility m_facility = SyslogFacility.User; - - /// - /// The message identity. - /// - private PatternLayout m_identity; - - /// - /// Mapping from level object to syslog severity. - /// - private LevelMapping m_levelMapping = new LevelMapping(); - - /// - /// Initial buffer size. - /// - private const int c_renderBufferSize = 256; - - /// - /// Maximum buffer size before it is recycled. - /// + /// + /// The facility. The default facility is . + /// + private SyslogFacility m_facility = SyslogFacility.User; + + /// + /// The message identity + /// + private PatternLayout m_identity; + + /// + /// Mapping from level object to syslog severity + /// + private LevelMapping m_levelMapping = new LevelMapping(); + + /// + /// Initial buffer size + /// + private const int c_renderBufferSize = 256; + + /// + /// Maximum buffer size before it is recycled + /// private const int c_renderBufferMaxCapacity = 1024; - /// - /// A class to act as a mapping between the level that a logging call is made at and - /// the syslog severity that is should be logged at. - /// - /// - /// - /// A class to act as a mapping between the level that a logging call is made at and - /// the syslog severity that is should be logged at. - /// - /// - public class LevelSeverity : LevelMappingEntry - { - private SyslogSeverity m_severity; - - /// - /// Gets or sets the mapped syslog severity for the specified level. - /// - /// - /// - /// Required property. - /// The mapped syslog severity for the specified level. - /// - /// - public SyslogSeverity Severity - { - get { return this.m_severity; } - set { this.m_severity = value; } - } + /// + /// A class to act as a mapping between the level that a logging call is made at and + /// the syslog severity that is should be logged at. + /// + /// + /// + /// A class to act as a mapping between the level that a logging call is made at and + /// the syslog severity that is should be logged at. + /// + /// + public class LevelSeverity : LevelMappingEntry + { + private SyslogSeverity m_severity; + + /// + /// The mapped syslog severity for the specified level + /// + /// + /// + /// Required property. + /// The mapped syslog severity for the specified level + /// + /// + public SyslogSeverity Severity + { + get { return this.m_severity; } + set { this.m_severity = value; } + } } - } -} + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/RemotingAppender.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/RemotingAppender.cs index 579244514a6..1a4f0ce670e 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/RemotingAppender.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/RemotingAppender.cs @@ -1,320 +1,320 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -// .NET Compact Framework 1.0 has no support for System.Runtime.Remoting -#if !NETCF - -using System; -using System.Collections; -using System.Runtime.Remoting.Messaging; -using System.Threading; +// .NET Compact Framework 1.0 && netstandard has no support for System.Runtime.Remoting +#if NET_2_0 -using log4net.Core; -using log4net.Layout; -using log4net.Util; - -namespace log4net.Appender -{ - /// - /// Delivers logging events to a remote logging sink. - /// - /// - /// - /// This Appender is designed to deliver events to a remote sink. - /// That is any object that implements the - /// interface. It delivers the events using .NET remoting. The - /// object to deliver events to is specified by setting the - /// appenders property. - /// - /// The RemotingAppender buffers events before sending them. This allows it to - /// make more efficient use of the remoting infrastructure. - /// - /// Once the buffer is full the events are still not sent immediately. - /// They are scheduled to be sent using a pool thread. The effect is that - /// the send occurs asynchronously. This is very important for a - /// number of non obvious reasons. The remoting infrastructure will - /// flow thread local variables (stored in the ), - /// if they are marked as , across the - /// remoting boundary. If the server is not contactable then - /// the remoting infrastructure will clear the - /// objects from the . To prevent a logging failure from - /// having side effects on the calling application the remoting call must be made - /// from a separate thread to the one used by the application. A - /// thread is used for this. If no thread is available then - /// the events will block in the thread pool manager until a thread is available. - /// - /// Because the events are sent asynchronously using pool threads it is possible to close - /// this appender before all the queued events have been sent. - /// When closing the appender attempts to wait until all the queued events have been sent, but - /// this will timeout after 30 seconds regardless. - /// - /// If this appender is being closed because the - /// event has fired it may not be possible to send all the queued events. During process - /// exit the runtime limits the time that a - /// event handler is allowed to run for. If the runtime terminates the threads before - /// the queued events have been sent then they will be lost. To ensure that all events - /// are sent the appender must be closed before the application exits. See - /// for details on how to shutdown - /// log4net programmatically. - /// - /// - /// Nicko Cadell. - /// Gert Driesen. - /// Daniel Cazzulino. - public class RemotingAppender : BufferingAppenderSkeleton +using System; +using System.Collections; +using System.Threading; + +using System.Runtime.Remoting.Messaging; + +using log4net.Layout; +using log4net.Core; +using log4net.Util; + +namespace log4net.Appender +{ + /// + /// Delivers logging events to a remote logging sink. + /// + /// + /// + /// This Appender is designed to deliver events to a remote sink. + /// That is any object that implements the + /// interface. It delivers the events using .NET remoting. The + /// object to deliver events to is specified by setting the + /// appenders property. + /// + /// The RemotingAppender buffers events before sending them. This allows it to + /// make more efficient use of the remoting infrastructure. + /// + /// Once the buffer is full the events are still not sent immediately. + /// They are scheduled to be sent using a pool thread. The effect is that + /// the send occurs asynchronously. This is very important for a + /// number of non obvious reasons. The remoting infrastructure will + /// flow thread local variables (stored in the ), + /// if they are marked as , across the + /// remoting boundary. If the server is not contactable then + /// the remoting infrastructure will clear the + /// objects from the . To prevent a logging failure from + /// having side effects on the calling application the remoting call must be made + /// from a separate thread to the one used by the application. A + /// thread is used for this. If no thread is available then + /// the events will block in the thread pool manager until a thread is available. + /// + /// Because the events are sent asynchronously using pool threads it is possible to close + /// this appender before all the queued events have been sent. + /// When closing the appender attempts to wait until all the queued events have been sent, but + /// this will timeout after 30 seconds regardless. + /// + /// If this appender is being closed because the + /// event has fired it may not be possible to send all the queued events. During process + /// exit the runtime limits the time that a + /// event handler is allowed to run for. If the runtime terminates the threads before + /// the queued events have been sent then they will be lost. To ensure that all events + /// are sent the appender must be closed before the application exits. See + /// for details on how to shutdown + /// log4net programmatically. + /// + /// + /// Nicko Cadell + /// Gert Driesen + /// Daniel Cazzulino + public class RemotingAppender : BufferingAppenderSkeleton { - /// - /// Initializes a new instance of the class. - /// - /// - /// - /// Default constructor. - /// - /// - public RemotingAppender() - { + /// + /// Initializes a new instance of the class. + /// + /// + /// + /// Default constructor. + /// + /// + public RemotingAppender() + { } - /// - /// Gets or sets the URL of the well-known object that will accept - /// the logging events. - /// - /// - /// The well-known URL of the remote sink. - /// - /// - /// - /// The URL of the remoting sink that will accept logging events. - /// The sink must implement the - /// interface. - /// - /// - public string Sink - { - get { return this.m_sinkUrl; } - set { this.m_sinkUrl = value; } + /// + /// Gets or sets the URL of the well-known object that will accept + /// the logging events. + /// + /// + /// The well-known URL of the remote sink. + /// + /// + /// + /// The URL of the remoting sink that will accept logging events. + /// The sink must implement the + /// interface. + /// + /// + public string Sink + { + get { return this.m_sinkUrl; } + set { this.m_sinkUrl = value; } + } + + /// + /// Initialize the appender based on the options set + /// + /// + /// + /// This is part of the delayed object + /// activation scheme. The method must + /// be called on this object after the configuration properties have + /// been set. Until is called this + /// object is in an undefined state and must not be used. + /// + /// + /// If any of the configuration properties are modified then + /// must be called again. + /// + /// +#if NET_4_0 || MONO_4_0 + [System.Security.SecuritySafeCritical] +#endif + public override void ActivateOptions() + { + base.ActivateOptions(); + + IDictionary channelProperties = new Hashtable(); + channelProperties["typeFilterLevel"] = "Full"; + + this.m_sinkObj = (IRemoteLoggingSink)Activator.GetObject(typeof(IRemoteLoggingSink), this.m_sinkUrl, channelProperties); } - /// - /// Initialize the appender based on the options set. - /// - /// - /// - /// This is part of the delayed object - /// activation scheme. The method must - /// be called on this object after the configuration properties have - /// been set. Until is called this - /// object is in an undefined state and must not be used. - /// - /// - /// If any of the configuration properties are modified then - /// must be called again. - /// - /// -#if NET_4_0 || MONO_4_0 - [System.Security.SecuritySafeCritical] -#endif - public override void ActivateOptions() - { - base.ActivateOptions(); - - IDictionary channelProperties = new Hashtable(); - channelProperties["typeFilterLevel"] = "Full"; - - this.m_sinkObj = (IRemoteLoggingSink)Activator.GetObject(typeof(IRemoteLoggingSink), this.m_sinkUrl, channelProperties); + /// + /// Send the contents of the buffer to the remote sink. + /// + /// + /// The events are not sent immediately. They are scheduled to be sent + /// using a pool thread. The effect is that the send occurs asynchronously. + /// This is very important for a number of non obvious reasons. The remoting + /// infrastructure will flow thread local variables (stored in the ), + /// if they are marked as , across the + /// remoting boundary. If the server is not contactable then + /// the remoting infrastructure will clear the + /// objects from the . To prevent a logging failure from + /// having side effects on the calling application the remoting call must be made + /// from a separate thread to the one used by the application. A + /// thread is used for this. If no thread is available then + /// the events will block in the thread pool manager until a thread is available. + /// + /// The events to send. + protected override void SendBuffer(LoggingEvent[] events) + { + // Setup for an async send + this.BeginAsyncSend(); + + // Send the events + if (!ThreadPool.QueueUserWorkItem(new WaitCallback(this.SendBufferCallback), events)) + { + // Cancel the async send + this.EndAsyncSend(); + + this.ErrorHandler.Error("RemotingAppender [" + this.Name + "] failed to ThreadPool.QueueUserWorkItem logging events in SendBuffer."); + } } - /// - /// Send the contents of the buffer to the remote sink. - /// - /// - /// The events are not sent immediately. They are scheduled to be sent - /// using a pool thread. The effect is that the send occurs asynchronously. - /// This is very important for a number of non obvious reasons. The remoting - /// infrastructure will flow thread local variables (stored in the ), - /// if they are marked as , across the - /// remoting boundary. If the server is not contactable then - /// the remoting infrastructure will clear the - /// objects from the . To prevent a logging failure from - /// having side effects on the calling application the remoting call must be made - /// from a separate thread to the one used by the application. A - /// thread is used for this. If no thread is available then - /// the events will block in the thread pool manager until a thread is available. - /// - /// The events to send. - protected override void SendBuffer(LoggingEvent[] events) - { - // Setup for an async send - this.BeginAsyncSend(); - - // Send the events - if (!ThreadPool.QueueUserWorkItem(new WaitCallback(this.SendBufferCallback), events)) - { - // Cancel the async send - this.EndAsyncSend(); - - this.ErrorHandler.Error("RemotingAppender [" + this.Name + "] failed to ThreadPool.QueueUserWorkItem logging events in SendBuffer."); - } - } - - /// - /// Override base class close. - /// - /// - /// - /// This method waits while there are queued work items. The events are - /// sent asynchronously using work items. These items - /// will be sent once a thread pool thread is available to send them, therefore - /// it is possible to close the appender before all the queued events have been - /// sent. - /// - /// This method attempts to wait until all the queued events have been sent, but this - /// method will timeout after 30 seconds regardless. - /// - /// If the appender is being closed because the - /// event has fired it may not be possible to send all the queued events. During process - /// exit the runtime limits the time that a - /// event handler is allowed to run for. - /// - protected override void OnClose() - { - base.OnClose(); - - // Wait for the work queue to become empty before closing, timeout 30 seconds - if (!this.m_workQueueEmptyEvent.WaitOne(30 * 1000, false)) - { - this.ErrorHandler.Error("RemotingAppender [" + this.Name + "] failed to send all queued events before close, in OnClose."); - } - } - - /// - /// Flushes any buffered log data. - /// - /// The maximum time to wait for logging events to be flushed. - /// True if all logging events were flushed successfully, else false. - public override bool Flush(int millisecondsTimeout) - { - this.Flush(); - return this.m_workQueueEmptyEvent.WaitOne(millisecondsTimeout, false); + /// + /// Override base class close. + /// + /// + /// + /// This method waits while there are queued work items. The events are + /// sent asynchronously using work items. These items + /// will be sent once a thread pool thread is available to send them, therefore + /// it is possible to close the appender before all the queued events have been + /// sent. + /// + /// This method attempts to wait until all the queued events have been sent, but this + /// method will timeout after 30 seconds regardless. + /// + /// If the appender is being closed because the + /// event has fired it may not be possible to send all the queued events. During process + /// exit the runtime limits the time that a + /// event handler is allowed to run for. + /// + protected override void OnClose() + { + base.OnClose(); + + // Wait for the work queue to become empty before closing, timeout 30 seconds + if (!this.m_workQueueEmptyEvent.WaitOne(30 * 1000, false)) + { + this.ErrorHandler.Error("RemotingAppender [" + this.Name + "] failed to send all queued events before close, in OnClose."); + } } - /// - /// A work item is being queued into the thread pool. - /// - private void BeginAsyncSend() - { - // The work queue is not empty - this.m_workQueueEmptyEvent.Reset(); - - // Increment the queued count - Interlocked.Increment(ref this.m_queuedCallbackCount); - } - - /// - /// A work item from the thread pool has completed. - /// - private void EndAsyncSend() - { - // Decrement the queued count - if (Interlocked.Decrement(ref this.m_queuedCallbackCount) <= 0) - { - // If the work queue is empty then set the event - this.m_workQueueEmptyEvent.Set(); - } - } - - /// - /// Send the contents of the buffer to the remote sink. - /// - /// - /// This method is designed to be used with the . - /// This method expects to be passed an array of - /// objects in the state param. - /// - /// the logging events to send. - private void SendBufferCallback(object state) - { - try - { - LoggingEvent[] events = (LoggingEvent[])state; - - // Send the events - this.m_sinkObj.LogEvents(events); - } - catch (Exception ex) - { - this.ErrorHandler.Error("Failed in SendBufferCallback", ex); - } - finally - { - this.EndAsyncSend(); - } + /// + /// Flushes any buffered log data. + /// + /// The maximum time to wait for logging events to be flushed. + /// True if all logging events were flushed successfully, else false. + public override bool Flush(int millisecondsTimeout) + { + base.Flush(); + return this.m_workQueueEmptyEvent.WaitOne(millisecondsTimeout, false); } - /// - /// The URL of the remote sink. - /// - private string m_sinkUrl; - - /// - /// The local proxy (.NET remoting) for the remote logging sink. - /// - private IRemoteLoggingSink m_sinkObj; - - /// - /// The number of queued callbacks currently waiting or executing. - /// - private int m_queuedCallbackCount = 0; - - /// - /// Event used to signal when there are no queued work items. - /// - /// - /// This event is set when there are no queued work items. In this - /// state it is safe to close the appender. - /// + /// + /// A work item is being queued into the thread pool + /// + private void BeginAsyncSend() + { + // The work queue is not empty + this.m_workQueueEmptyEvent.Reset(); + + // Increment the queued count + Interlocked.Increment(ref this.m_queuedCallbackCount); + } + + /// + /// A work item from the thread pool has completed + /// + private void EndAsyncSend() + { + // Decrement the queued count + if (Interlocked.Decrement(ref this.m_queuedCallbackCount) <= 0) + { + // If the work queue is empty then set the event + this.m_workQueueEmptyEvent.Set(); + } + } + + /// + /// Send the contents of the buffer to the remote sink. + /// + /// + /// This method is designed to be used with the . + /// This method expects to be passed an array of + /// objects in the state param. + /// + /// the logging events to send + private void SendBufferCallback(object state) + { + try + { + LoggingEvent[] events = (LoggingEvent[])state; + + // Send the events + this.m_sinkObj.LogEvents(events); + } + catch(Exception ex) + { + this.ErrorHandler.Error("Failed in SendBufferCallback", ex); + } + finally + { + this.EndAsyncSend(); + } + } + + /// + /// The URL of the remote sink. + /// + private string m_sinkUrl; + + /// + /// The local proxy (.NET remoting) for the remote logging sink. + /// + private IRemoteLoggingSink m_sinkObj; + + /// + /// The number of queued callbacks currently waiting or executing + /// + private int m_queuedCallbackCount = 0; + + /// + /// Event used to signal when there are no queued work items + /// + /// + /// This event is set when there are no queued work items. In this + /// state it is safe to close the appender. + /// private ManualResetEvent m_workQueueEmptyEvent = new ManualResetEvent(true); - /// - /// Interface used to deliver objects to a remote sink. - /// - /// - /// This interface must be implemented by a remoting sink - /// if the is to be used - /// to deliver logging events to the sink. - /// - public interface IRemoteLoggingSink - { - /// - /// Delivers logging events to the remote sink. - /// - /// Array of events to log. - /// - /// - /// Delivers logging events to the remote sink. - /// - /// - void LogEvents(LoggingEvent[] events); - } - } -} - -#endif // !NETCF + /// + /// Interface used to deliver objects to a remote sink. + /// + /// + /// This interface must be implemented by a remoting sink + /// if the is to be used + /// to deliver logging events to the sink. + /// + public interface IRemoteLoggingSink + { + /// + /// Delivers logging events to the remote sink + /// + /// Array of events to log. + /// + /// + /// Delivers logging events to the remote sink + /// + /// + void LogEvents(LoggingEvent[] events); + } + } +} + +#endif // NET_2_0 diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/RollingFileAppender.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/RollingFileAppender.cs index 20ba3e6e683..aec164fc4ca 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/RollingFileAppender.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/RollingFileAppender.cs @@ -1,1741 +1,1748 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.Appender -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; - using System.Collections; - using System.Globalization; - using System.IO; - using System.Threading; - - using log4net.Core; - using log4net.Util; - -#if CONFIRM_WIN32_FILE_SHAREMODES - // The following sounds good, and I though it was the case, but after - // further testing on Windows I have not been able to confirm it. - - /// On the Windows platform if another process has a write lock on the file - /// that is to be deleted, but allows shared read access to the file then the - /// file can be moved, but cannot be deleted. If the other process also allows - /// shared delete access to the file then the file will be deleted once that - /// process closes the file. If it is necessary to open the log file or any - /// of the backup files outside of this appender for either read or - /// write access please ensure that read and delete share modes are enabled. -#endif - - /// - /// Appender that rolls log files based on size or date or both. - /// - /// - /// - /// RollingFileAppender can roll log files based on size or date or both - /// depending on the setting of the property. - /// When set to the log file will be rolled - /// once its size exceeds the . - /// When set to the log file will be rolled - /// once the date boundary specified in the property - /// is crossed. - /// When set to the log file will be - /// rolled once the date boundary specified in the property - /// is crossed, but within a date boundary the file will also be rolled - /// once its size exceeds the . - /// When set to the log file will be rolled when - /// the appender is configured. This effectively means that the log file can be - /// rolled once per program execution. - /// - /// - /// A of few additional optional features have been added: - /// - /// Attach date pattern for current log file - /// Backup number increments for newer files - /// Infinite number of backups by file size - /// - /// - /// - /// - /// - /// For large or infinite numbers of backup files a - /// greater than zero is highly recommended, otherwise all the backup files need - /// to be renamed each time a new backup is created. - /// - /// - /// When Date/Time based rolling is used setting - /// to will reduce the number of file renamings to few or none. - /// - /// - /// - /// - /// - /// Changing or without clearing - /// the log file directory of backup files will cause unexpected and unwanted side effects. - /// - /// - /// - /// - /// If Date/Time based rolling is enabled this appender will attempt to roll existing files - /// in the directory without a Date/Time tag based on the last write date of the base log file. - /// The appender only rolls the log file when a message is logged. If Date/Time based rolling - /// is enabled then the appender will not roll the log file at the Date/Time boundary but - /// at the point when the next message is logged after the boundary has been crossed. - /// - /// - /// - /// The extends the and - /// has the same behavior when opening the log file. - /// The appender will first try to open the file for writing when - /// is called. This will typically be during configuration. - /// If the file cannot be opened for writing the appender will attempt - /// to open the file again each time a message is logged to the appender. - /// If the file cannot be opened for writing when a message is logged then - /// the message will be discarded by this appender. - /// - /// - /// When rolling a backup file necessitates deleting an older backup file the - /// file to be deleted is moved to a temporary name before being deleted. - /// - /// - /// - /// - /// A maximum number of backup files when rolling on date/time boundaries is not supported. - /// - /// - /// - /// Nicko Cadell. - /// Gert Driesen. - /// Aspi Havewala. - /// Douglas de la Torre. - /// Edward Smit. - public class RollingFileAppender : FileAppender +using System; +using System.Collections; +using System.Globalization; +using System.IO; + +using log4net.Util; +using log4net.Core; +using System.Threading; + +namespace log4net.Appender +{ +#if CONFIRM_WIN32_FILE_SHAREMODES + // The following sounds good, and I though it was the case, but after + // further testing on Windows I have not been able to confirm it. + + /// On the Windows platform if another process has a write lock on the file + /// that is to be deleted, but allows shared read access to the file then the + /// file can be moved, but cannot be deleted. If the other process also allows + /// shared delete access to the file then the file will be deleted once that + /// process closes the file. If it is necessary to open the log file or any + /// of the backup files outside of this appender for either read or + /// write access please ensure that read and delete share modes are enabled. +#endif + + /// + /// Appender that rolls log files based on size or date or both. + /// + /// + /// + /// RollingFileAppender can roll log files based on size or date or both + /// depending on the setting of the property. + /// When set to the log file will be rolled + /// once its size exceeds the . + /// When set to the log file will be rolled + /// once the date boundary specified in the property + /// is crossed. + /// When set to the log file will be + /// rolled once the date boundary specified in the property + /// is crossed, but within a date boundary the file will also be rolled + /// once its size exceeds the . + /// When set to the log file will be rolled when + /// the appender is configured. This effectively means that the log file can be + /// rolled once per program execution. + /// + /// + /// A of few additional optional features have been added: + /// + /// Attach date pattern for current log file + /// Backup number increments for newer files + /// Infinite number of backups by file size + /// + /// + /// + /// + /// + /// For large or infinite numbers of backup files a + /// greater than zero is highly recommended, otherwise all the backup files need + /// to be renamed each time a new backup is created. + /// + /// + /// When Date/Time based rolling is used setting + /// to will reduce the number of file renamings to few or none. + /// + /// + /// + /// + /// + /// Changing or without clearing + /// the log file directory of backup files will cause unexpected and unwanted side effects. + /// + /// + /// + /// + /// If Date/Time based rolling is enabled this appender will attempt to roll existing files + /// in the directory without a Date/Time tag based on the last write date of the base log file. + /// The appender only rolls the log file when a message is logged. If Date/Time based rolling + /// is enabled then the appender will not roll the log file at the Date/Time boundary but + /// at the point when the next message is logged after the boundary has been crossed. + /// + /// + /// + /// The extends the and + /// has the same behavior when opening the log file. + /// The appender will first try to open the file for writing when + /// is called. This will typically be during configuration. + /// If the file cannot be opened for writing the appender will attempt + /// to open the file again each time a message is logged to the appender. + /// If the file cannot be opened for writing when a message is logged then + /// the message will be discarded by this appender. + /// + /// + /// When rolling a backup file necessitates deleting an older backup file the + /// file to be deleted is moved to a temporary name before being deleted. + /// + /// + /// + /// + /// A maximum number of backup files when rolling on date/time boundaries is not supported. + /// + /// + /// + /// Nicko Cadell + /// Gert Driesen + /// Aspi Havewala + /// Douglas de la Torre + /// Edward Smit + public class RollingFileAppender : FileAppender { - /// - /// Style of rolling to use. - /// - /// - /// - /// Style of rolling to use. - /// - /// - public enum RollingMode - { - /// - /// Roll files once per program execution - /// - /// - /// - /// Roll files once per program execution. - /// Well really once each time this appender is - /// configured. - /// - /// - /// Setting this option also sets AppendToFile to - /// false on the RollingFileAppender, otherwise - /// this appender would just be a normal file appender. - /// - /// - Once = 0, - - /// - /// Roll files based only on the size of the file - /// - Size = 1, - - /// - /// Roll files based only on the date - /// - Date = 2, - - /// - /// Roll files based on both the size and date of the file - /// - Composite = 3, + /// + /// Style of rolling to use + /// + /// + /// + /// Style of rolling to use + /// + /// + public enum RollingMode + { + /// + /// Roll files once per program execution + /// + /// + /// + /// Roll files once per program execution. + /// Well really once each time this appender is + /// configured. + /// + /// + /// Setting this option also sets AppendToFile to + /// false on the RollingFileAppender, otherwise + /// this appender would just be a normal file appender. + /// + /// + Once = 0, + + /// + /// Roll files based only on the size of the file + /// + Size = 1, + + /// + /// Roll files based only on the date + /// + Date = 2, + + /// + /// Roll files based on both the size and date of the file + /// + Composite = 3 + } + + /// + /// The code assumes that the following 'time' constants are in a increasing sequence. + /// + /// + /// + /// The code assumes that the following 'time' constants are in a increasing sequence. + /// + /// + protected enum RollPoint + { + /// + /// Roll the log not based on the date + /// + InvalidRollPoint =-1, + + /// + /// Roll the log for each minute + /// + TopOfMinute = 0, + + /// + /// Roll the log for each hour + /// + TopOfHour = 1, + + /// + /// Roll the log twice a day (midday and midnight) + /// + HalfDay = 2, + + /// + /// Roll the log each day (midnight) + /// + TopOfDay = 3, + + /// + /// Roll the log each week + /// + TopOfWeek = 4, + + /// + /// Roll the log each month + /// + TopOfMonth = 5 + } + + /// + /// Initializes a new instance of the class. + /// + /// + /// + /// Default constructor. + /// + /// + public RollingFileAppender() + { + } + + /// + /// Cleans up all resources used by this appender. + /// + ~RollingFileAppender() + { +#if !NETCF + if (this.m_mutexForRolling != null) + { +#if NET_4_0 || MONO_4_0 || NETSTANDARD + this.m_mutexForRolling.Dispose(); +#else + m_mutexForRolling.Close(); +#endif + this.m_mutexForRolling = null; + } +#endif + } + +#if !NET_1_0 && !CLI_1_0 && !NETCF + /// + /// Gets or sets the strategy for determining the current date and time. The default + /// implementation is to use LocalDateTime which internally calls through to DateTime.Now. + /// DateTime.UtcNow may be used on frameworks newer than .NET 1.0 by specifying + /// . + /// + /// + /// An implementation of the interface which returns the current date and time. + /// + /// + /// + /// Gets or sets the used to return the current date and time. + /// + /// + /// There are two built strategies for determining the current date and time, + /// + /// and . + /// + /// + /// The default strategy is . + /// + /// +#else + /// + /// Gets or sets the strategy for determining the current date and time. The default + /// implementation is to use LocalDateTime which internally calls through to DateTime.Now. + /// + /// + /// An implementation of the interface which returns the current date and time. + /// + /// + /// + /// Gets or sets the used to return the current date and time. + /// + /// + /// The default strategy is . + /// + /// +#endif + public IDateTime DateTimeStrategy + { + get { return this.m_dateTime; } + set { this.m_dateTime = value; } + } + + /// + /// Gets or sets the date pattern to be used for generating file names + /// when rolling over on date. + /// + /// + /// The date pattern to be used for generating file names when rolling + /// over on date. + /// + /// + /// + /// Takes a string in the same format as expected by + /// . + /// + /// + /// This property determines the rollover schedule when rolling over + /// on date. + /// + /// + public string DatePattern + { + get { return this.m_datePattern; } + set { this.m_datePattern = value; } + } + + /// + /// Gets or sets the maximum number of backup files that are kept before + /// the oldest is erased. + /// + /// + /// The maximum number of backup files that are kept before the oldest is + /// erased. + /// + /// + /// + /// If set to zero, then there will be no backup files and the log file + /// will be truncated when it reaches . + /// + /// + /// If a negative number is supplied then no deletions will be made. Note + /// that this could result in very slow performance as a large number of + /// files are rolled over unless is used. + /// + /// + /// The maximum applies to each time based group of files and + /// not the total. + /// + /// + public int MaxSizeRollBackups + { + get { return this.m_maxSizeRollBackups; } + set { this.m_maxSizeRollBackups = value; } + } + + /// + /// Gets or sets the maximum size that the output file is allowed to reach + /// before being rolled over to backup files. + /// + /// + /// The maximum size in bytes that the output file is allowed to reach before being + /// rolled over to backup files. + /// + /// + /// + /// This property is equivalent to except + /// that it is required for differentiating the setter taking a + /// argument from the setter taking a + /// argument. + /// + /// + /// The default maximum file size is 10MB (10*1024*1024). + /// + /// + public long MaxFileSize + { + get { return this.m_maxFileSize; } + set { this.m_maxFileSize = value; } + } + + /// + /// Gets or sets the maximum size that the output file is allowed to reach + /// before being rolled over to backup files. + /// + /// + /// The maximum size that the output file is allowed to reach before being + /// rolled over to backup files. + /// + /// + /// + /// This property allows you to specify the maximum size with the + /// suffixes "KB", "MB" or "GB" so that the size is interpreted being + /// expressed respectively in kilobytes, megabytes or gigabytes. + /// + /// + /// For example, the value "10KB" will be interpreted as 10240 bytes. + /// + /// + /// The default maximum file size is 10MB. + /// + /// + /// If you have the option to set the maximum file size programmatically + /// consider using the property instead as this + /// allows you to set the size in bytes as a . + /// + /// + public string MaximumFileSize + { + get { return this.m_maxFileSize.ToString(NumberFormatInfo.InvariantInfo); } + set { this.m_maxFileSize = OptionConverter.ToFileSize(value, this.m_maxFileSize + 1); } } - /// - /// The code assumes that the following 'time' constants are in a increasing sequence. - /// - /// - /// - /// The code assumes that the following 'time' constants are in a increasing sequence. - /// - /// - protected enum RollPoint - { - /// - /// Roll the log not based on the date - /// - InvalidRollPoint = -1, - - /// - /// Roll the log for each minute - /// - TopOfMinute = 0, - - /// - /// Roll the log for each hour - /// - TopOfHour = 1, - - /// - /// Roll the log twice a day (midday and midnight) - /// - HalfDay = 2, - - /// - /// Roll the log each day (midnight) - /// - TopOfDay = 3, - - /// - /// Roll the log each week - /// - TopOfWeek = 4, - - /// - /// Roll the log each month - /// - TopOfMonth = 5, + /// + /// Gets or sets the rolling file count direction. + /// + /// + /// The rolling file count direction. + /// + /// + /// + /// Indicates if the current file is the lowest numbered file or the + /// highest numbered file. + /// + /// + /// By default newer files have lower numbers ( < 0), + /// i.e. log.1 is most recent, log.5 is the 5th backup, etc... + /// + /// + /// >= 0 does the opposite i.e. + /// log.1 is the first backup made, log.5 is the 5th backup made, etc. + /// For infinite backups use >= 0 to reduce + /// rollover costs. + /// + /// The default file count direction is -1. + /// + public int CountDirection + { + get { return this.m_countDirection; } + set { this.m_countDirection = value; } } + + /// + /// Gets or sets the rolling style. + /// + /// The rolling style. + /// + /// + /// The default rolling style is . + /// + /// + /// When set to this appender's + /// property is set to false, otherwise + /// the appender would append to a single file rather than rolling + /// the file each time it is opened. + /// + /// + public RollingMode RollingStyle + { + get { return this.m_rollingStyle; } + set + { + this.m_rollingStyle = value; + switch (this.m_rollingStyle) + { + case RollingMode.Once: + this.m_rollDate = false; + this.m_rollSize = false; + + this.AppendToFile = false; + break; - /// - /// Initializes a new instance of the class. - /// - /// - /// - /// Default constructor. - /// - /// - public RollingFileAppender() - { + case RollingMode.Size: + this.m_rollDate = false; + this.m_rollSize = true; + break; + + case RollingMode.Date: + this.m_rollDate = true; + this.m_rollSize = false; + break; + + case RollingMode.Composite: + this.m_rollDate = true; + this.m_rollSize = true; + break; + } + } } /// - /// Finalizes an instance of the class. - /// Cleans up all resources used by this appender. - /// - ~RollingFileAppender() - { -#if !NETCF - if (this.m_mutexForRolling != null) - { -#if NET_4_0 || MONO_4_0 || NETSTANDARD1_3 - this.m_mutexForRolling.Dispose(); -#else - m_mutexForRolling.Close(); -#endif - this.m_mutexForRolling = null; - } -#endif + /// Gets or sets a value indicating whether to preserve the file name extension when rolling. + /// + /// + /// true if the file name extension should be preserved. + /// + /// + /// + /// By default file.log is rolled to file.log.yyyy-MM-dd or file.log.curSizeRollBackup. + /// However, under Windows the new file name will loose any program associations as the + /// extension is changed. Optionally file.log can be renamed to file.yyyy-MM-dd.log or + /// file.curSizeRollBackup.log to maintain any program associations. + /// + /// + public bool PreserveLogFileNameExtension + { + get { return this.m_preserveLogFileNameExtension; } + set { this.m_preserveLogFileNameExtension = value; } } -#if !NET_1_0 && !CLI_1_0 && !NETCF - /// - /// Gets or sets the strategy for determining the current date and time. The default - /// implementation is to use LocalDateTime which internally calls through to DateTime.Now. - /// DateTime.UtcNow may be used on frameworks newer than .NET 1.0 by specifying - /// . - /// - /// - /// An implementation of the interface which returns the current date and time. - /// - /// - /// - /// Gets or sets the used to return the current date and time. - /// - /// - /// There are two built strategies for determining the current date and time, - /// - /// and . - /// - /// - /// The default strategy is . - /// - /// -#else - /// - /// Gets or sets the strategy for determining the current date and time. The default - /// implementation is to use LocalDateTime which internally calls through to DateTime.Now. - /// - /// - /// An implementation of the interface which returns the current date and time. - /// - /// - /// - /// Gets or sets the used to return the current date and time. - /// - /// - /// The default strategy is . - /// - /// -#endif - public IDateTime DateTimeStrategy - { - get { return this.m_dateTime; } - set { this.m_dateTime = value; } - } - - /// - /// Gets or sets the date pattern to be used for generating file names - /// when rolling over on date. - /// - /// - /// The date pattern to be used for generating file names when rolling - /// over on date. - /// - /// - /// - /// Takes a string in the same format as expected by - /// . - /// - /// - /// This property determines the rollover schedule when rolling over - /// on date. - /// - /// - public string DatePattern - { - get { return this.m_datePattern; } - set { this.m_datePattern = value; } - } - - /// - /// Gets or sets the maximum number of backup files that are kept before - /// the oldest is erased. - /// - /// - /// The maximum number of backup files that are kept before the oldest is - /// erased. - /// - /// - /// - /// If set to zero, then there will be no backup files and the log file - /// will be truncated when it reaches . - /// - /// - /// If a negative number is supplied then no deletions will be made. Note - /// that this could result in very slow performance as a large number of - /// files are rolled over unless is used. - /// - /// - /// The maximum applies to each time based group of files and - /// not the total. - /// - /// - public int MaxSizeRollBackups - { - get { return this.m_maxSizeRollBackups; } - set { this.m_maxSizeRollBackups = value; } - } - - /// - /// Gets or sets the maximum size that the output file is allowed to reach - /// before being rolled over to backup files. - /// - /// - /// The maximum size in bytes that the output file is allowed to reach before being - /// rolled over to backup files. - /// - /// - /// - /// This property is equivalent to except - /// that it is required for differentiating the setter taking a - /// argument from the setter taking a - /// argument. - /// - /// - /// The default maximum file size is 10MB (10*1024*1024). - /// - /// - public long MaxFileSize - { - get { return this.m_maxFileSize; } - set { this.m_maxFileSize = value; } - } - - /// - /// Gets or sets the maximum size that the output file is allowed to reach - /// before being rolled over to backup files. - /// - /// - /// The maximum size that the output file is allowed to reach before being - /// rolled over to backup files. - /// - /// - /// - /// This property allows you to specify the maximum size with the - /// suffixes "KB", "MB" or "GB" so that the size is interpreted being - /// expressed respectively in kilobytes, megabytes or gigabytes. - /// - /// - /// For example, the value "10KB" will be interpreted as 10240 bytes. - /// - /// - /// The default maximum file size is 10MB. - /// - /// - /// If you have the option to set the maximum file size programmatically - /// consider using the property instead as this - /// allows you to set the size in bytes as a . - /// - /// - public string MaximumFileSize - { - get { return this.m_maxFileSize.ToString(NumberFormatInfo.InvariantInfo); } - set { this.m_maxFileSize = OptionConverter.ToFileSize(value, this.m_maxFileSize + 1); } - } - - /// - /// Gets or sets the rolling file count direction. - /// - /// - /// The rolling file count direction. - /// - /// - /// - /// Indicates if the current file is the lowest numbered file or the - /// highest numbered file. - /// - /// - /// By default newer files have lower numbers ( < 0), - /// i.e. log.1 is most recent, log.5 is the 5th backup, etc... - /// - /// - /// >= 0 does the opposite i.e. - /// log.1 is the first backup made, log.5 is the 5th backup made, etc. - /// For infinite backups use >= 0 to reduce - /// rollover costs. - /// - /// The default file count direction is -1. - /// - public int CountDirection - { - get { return this.m_countDirection; } - set { this.m_countDirection = value; } - } - - /// - /// Gets or sets the rolling style. - /// - /// The rolling style. - /// - /// - /// The default rolling style is . - /// - /// - /// When set to this appender's - /// property is set to false, otherwise - /// the appender would append to a single file rather than rolling - /// the file each time it is opened. - /// - /// - public RollingMode RollingStyle - { - get { return this.m_rollingStyle; } - - set - { - this.m_rollingStyle = value; - switch (this.m_rollingStyle) - { - case RollingMode.Once: - this.m_rollDate = false; - this.m_rollSize = false; - - this.AppendToFile = false; - break; - - case RollingMode.Size: - this.m_rollDate = false; - this.m_rollSize = true; - break; - - case RollingMode.Date: - this.m_rollDate = true; - this.m_rollSize = false; - break; - - case RollingMode.Composite: - this.m_rollDate = true; - this.m_rollSize = true; - break; - } - } - } - - /// - /// Gets or sets a value indicating whether to preserve the file name extension when rolling. - /// - /// - /// true if the file name extension should be preserved. - /// - /// - /// - /// By default file.log is rolled to file.log.yyyy-MM-dd or file.log.curSizeRollBackup. - /// However, under Windows the new file name will loose any program associations as the - /// extension is changed. Optionally file.log can be renamed to file.yyyy-MM-dd.log or - /// file.curSizeRollBackup.log to maintain any program associations. - /// - /// - public bool PreserveLogFileNameExtension - { - get { return this.m_preserveLogFileNameExtension; } - set { this.m_preserveLogFileNameExtension = value; } - } - - /// - /// Gets or sets a value indicating whether to always log to - /// the same file. - /// - /// - /// true if always should be logged to the same file, otherwise false. - /// - /// - /// - /// By default file.log is always the current file. Optionally - /// file.log.yyyy-mm-dd for current formatted datePattern can by the currently - /// logging file (or file.log.curSizeRollBackup or even - /// file.log.yyyy-mm-dd.curSizeRollBackup). - /// - /// - /// This will make time based rollovers with a large number of backups - /// much faster as the appender it won't have to rename all the backups!. - /// - /// - public bool StaticLogFileName - { - get { return this.m_staticLogFileName; } - set { this.m_staticLogFileName = value; } + /// + /// Gets or sets a value indicating whether to always log to + /// the same file. + /// + /// + /// true if always should be logged to the same file, otherwise false. + /// + /// + /// + /// By default file.log is always the current file. Optionally + /// file.log.yyyy-mm-dd for current formatted datePattern can by the currently + /// logging file (or file.log.curSizeRollBackup or even + /// file.log.yyyy-mm-dd.curSizeRollBackup). + /// + /// + /// This will make time based rollovers with a large number of backups + /// much faster as the appender it won't have to rename all the backups! + /// + /// + public bool StaticLogFileName + { + get { return this.m_staticLogFileName; } + set { this.m_staticLogFileName = value; } } - /// - /// The fully qualified type of the RollingFileAppender class. - /// - /// - /// Used by the internal logger to record the Type of the - /// log message. - /// + /// + /// The fully qualified type of the RollingFileAppender class. + /// + /// + /// Used by the internal logger to record the Type of the + /// log message. + /// private static readonly Type declaringType = typeof(RollingFileAppender); - /// - /// Sets the quiet writer being used. - /// - /// - /// This method can be overridden by sub classes. - /// - /// the writer to set. - protected override void SetQWForFiles(TextWriter writer) - { - this.QuietWriter = new CountingQuietTextWriter(writer, this.ErrorHandler); - } - - /// - /// Write out a logging event. - /// - /// the event to write to file. - /// - /// - /// Handles append time behavior for RollingFileAppender. This checks - /// if a roll over either by date (checked first) or time (checked second) - /// is need and then appends to the file last. - /// - /// - protected override void Append(LoggingEvent loggingEvent) - { - this.AdjustFileBeforeAppend(); - base.Append(loggingEvent); - } - - /// - /// Write out an array of logging events. - /// - /// the events to write to file. - /// - /// - /// Handles append time behavior for RollingFileAppender. This checks - /// if a roll over either by date (checked first) or time (checked second) - /// is need and then appends to the file last. - /// - /// - protected override void Append(LoggingEvent[] loggingEvents) - { - this.AdjustFileBeforeAppend(); - base.Append(loggingEvents); - } - - /// - /// Performs any required rolling before outputting the next event. - /// - /// - /// - /// Handles append time behavior for RollingFileAppender. This checks - /// if a roll over either by date (checked first) or time (checked second) - /// is need and then appends to the file last. - /// - /// - protected virtual void AdjustFileBeforeAppend() - { - // reuse the file appenders locking model to lock the rolling -#if !NETCF - try - { - // if rolling should be locked, acquire the lock - if (this.m_mutexForRolling != null) - { - this.m_mutexForRolling.WaitOne(); - } -#endif - if (this.m_rollDate) - { - DateTime n = this.m_dateTime.Now; - if (n >= this.m_nextCheck) - { - this.m_now = n; - this.m_nextCheck = this.NextCheckDate(this.m_now, this.m_rollPoint); - - this.RollOverTime(true); - } - } - - if (this.m_rollSize) - { - if ((this.File != null) && ((CountingQuietTextWriter)this.QuietWriter).Count >= this.m_maxFileSize) - { - this.RollOverSize(); - } - } -#if !NETCF - } - finally - { - // if rolling should be locked, release the lock - if (this.m_mutexForRolling != null) - { - this.m_mutexForRolling.ReleaseMutex(); - } - } -#endif - } - - /// - /// Creates and opens the file for logging. If - /// is false then the fully qualified name is determined and used. - /// - /// the name of the file to open. - /// true to append to existing file. - /// - /// This method will ensure that the directory structure - /// for the specified exists. - /// - protected override void OpenFile(string fileName, bool append) - { - lock (this) - { - fileName = this.GetNextOutputFileName(fileName); - - // Calculate the current size of the file - long currentCount = 0; - if (append) - { - using (this.SecurityContext.Impersonate(this)) - { - if (System.IO.File.Exists(fileName)) - { - currentCount = new FileInfo(fileName).Length; - } - } - } - else - { - if (LogLog.IsErrorEnabled) - { - // Internal check that the file is not being overwritten - // If not Appending to an existing file we should have rolled the file out of the - // way. Therefore we should not be over-writing an existing file. - // The only exception is if we are not allowed to roll the existing file away. - if (this.m_maxSizeRollBackups != 0 && this.FileExists(fileName)) - { - LogLog.Error(declaringType, "RollingFileAppender: INTERNAL ERROR. Append is False but OutputFile [" + fileName + "] already exists."); - } - } - } - - if (!this.m_staticLogFileName) - { - this.m_scheduledFilename = fileName; - } - - // Open the file (call the base class to do it) - base.OpenFile(fileName, append); - - // Set the file size onto the counting writer - ((CountingQuietTextWriter)this.QuietWriter).Count = currentCount; - } - } - - /// - /// Get the current output file name. - /// - /// the base file name. - /// the output file name. - /// - /// The output file name is based on the base fileName specified. - /// If is set then the output - /// file name is the same as the base file passed in. Otherwise - /// the output file depends on the date pattern, on the count - /// direction or both. - /// - protected string GetNextOutputFileName(string fileName) - { - if (!this.m_staticLogFileName) - { - fileName = fileName.Trim(); - - if (this.m_rollDate) - { - fileName = this.CombinePath(fileName, this.m_now.ToString(this.m_datePattern, System.Globalization.DateTimeFormatInfo.InvariantInfo)); - } - - if (this.m_countDirection >= 0) - { - fileName = this.CombinePath(fileName, "." + this.m_curSizeRollBackups); - } - } - - return fileName; + /// + /// Sets the quiet writer being used. + /// + /// + /// This method can be overridden by sub classes. + /// + /// the writer to set + protected override void SetQWForFiles(TextWriter writer) + { + this.QuietWriter = new CountingQuietTextWriter(writer, this.ErrorHandler); + } + + /// + /// Write out a logging event. + /// + /// the event to write to file. + /// + /// + /// Handles append time behavior for RollingFileAppender. This checks + /// if a roll over either by date (checked first) or time (checked second) + /// is need and then appends to the file last. + /// + /// + protected override void Append(LoggingEvent loggingEvent) + { + this.AdjustFileBeforeAppend(); + base.Append(loggingEvent); + } + + /// + /// Write out an array of logging events. + /// + /// the events to write to file. + /// + /// + /// Handles append time behavior for RollingFileAppender. This checks + /// if a roll over either by date (checked first) or time (checked second) + /// is need and then appends to the file last. + /// + /// + protected override void Append(LoggingEvent[] loggingEvents) + { + this.AdjustFileBeforeAppend(); + base.Append(loggingEvents); + } + + /// + /// Performs any required rolling before outputting the next event + /// + /// + /// + /// Handles append time behavior for RollingFileAppender. This checks + /// if a roll over either by date (checked first) or time (checked second) + /// is need and then appends to the file last. + /// + /// + protected virtual void AdjustFileBeforeAppend() + { + // reuse the file appenders locking model to lock the rolling +#if !NETCF + try + { + // if rolling should be locked, acquire the lock + if (this.m_mutexForRolling != null) + { + this.m_mutexForRolling.WaitOne(); + } +#endif + if (this.m_rollDate) + { + DateTime n = this.m_dateTime.Now; + if (n >= this.m_nextCheck) + { + this.m_now = n; + this.m_nextCheck = this.NextCheckDate(this.m_now, this.m_rollPoint); + + this.RollOverTime(true); + } + } + + if (this.m_rollSize) + { + if ((this.File != null) && ((CountingQuietTextWriter)this.QuietWriter).Count >= this.m_maxFileSize) + { + this.RollOverSize(); + } + } +#if !NETCF + } + finally + { + // if rolling should be locked, release the lock + if (this.m_mutexForRolling != null) + { + this.m_mutexForRolling.ReleaseMutex(); + } + } +#endif + } + + /// + /// Creates and opens the file for logging. If + /// is false then the fully qualified name is determined and used. + /// + /// the name of the file to open + /// true to append to existing file + /// + /// This method will ensure that the directory structure + /// for the specified exists. + /// + protected override void OpenFile(string fileName, bool append) + { + lock(this) + { + fileName = this.GetNextOutputFileName(fileName); + + // Calculate the current size of the file + long currentCount = 0; + if (append) + { + using(this.SecurityContext.Impersonate(this)) + { + if (System.IO.File.Exists(fileName)) + { + currentCount = (new FileInfo(fileName)).Length; + } + } + } + else + { + if (LogLog.IsErrorEnabled) + { + // Internal check that the file is not being overwritten + // If not Appending to an existing file we should have rolled the file out of the + // way. Therefore we should not be over-writing an existing file. + // The only exception is if we are not allowed to roll the existing file away. + if (this.m_maxSizeRollBackups != 0 && this.FileExists(fileName)) + { + LogLog.Error(declaringType, "RollingFileAppender: INTERNAL ERROR. Append is False but OutputFile ["+fileName+"] already exists."); + } + } + } + + if (!this.m_staticLogFileName) + { + this.m_scheduledFilename = fileName; + } + + // Open the file (call the base class to do it) + base.OpenFile(fileName, append); + + // Set the file size onto the counting writer + ((CountingQuietTextWriter)this.QuietWriter).Count = currentCount; + } + } + + /// + /// Get the current output file name + /// + /// the base file name + /// the output file name + /// + /// The output file name is based on the base fileName specified. + /// If is set then the output + /// file name is the same as the base file passed in. Otherwise + /// the output file depends on the date pattern, on the count + /// direction or both. + /// + protected string GetNextOutputFileName(string fileName) + { + if (!this.m_staticLogFileName) + { + fileName = fileName.Trim(); + + if (this.m_rollDate) + { + fileName = this.CombinePath(fileName, this.m_now.ToString(this.m_datePattern, DateTimeFormatInfo.InvariantInfo)); + } + + if (this.m_countDirection >= 0) + { + fileName = this.CombinePath(fileName, "." + this.m_curSizeRollBackups); + } + } + + return fileName; + } + + /// + /// Determines curSizeRollBackups (only within the current roll point) + /// + private void DetermineCurSizeRollBackups() + { + this.m_curSizeRollBackups = 0; + + string fullPath = null; + string fileName = null; + + using(this.SecurityContext.Impersonate(this)) + { + fullPath = Path.GetFullPath(this.m_baseFileName); + fileName = Path.GetFileName(fullPath); + } + + ArrayList arrayFiles = this.GetExistingFiles(fullPath); + this.InitializeRollBackups(fileName, arrayFiles); + + LogLog.Debug(declaringType, "curSizeRollBackups starts at ["+ this.m_curSizeRollBackups+"]"); + } + + /// + /// Generates a wildcard pattern that can be used to find all files + /// that are similar to the base file name. + /// + /// + /// + private string GetWildcardPatternForFile(string baseFileName) + { + if (this.m_preserveLogFileNameExtension) + { + return Path.GetFileNameWithoutExtension(baseFileName) + "*" + Path.GetExtension(baseFileName); + } + else + { + return baseFileName + '*'; + } + } + + /// + /// Builds a list of filenames for all files matching the base filename plus a file + /// pattern. + /// + /// + /// + private ArrayList GetExistingFiles(string baseFilePath) + { + ArrayList alFiles = new ArrayList(); + + string directory = null; + + using(this.SecurityContext.Impersonate(this)) + { + string fullPath = Path.GetFullPath(baseFilePath); + + directory = Path.GetDirectoryName(fullPath); + if (Directory.Exists(directory)) + { + string baseFileName = Path.GetFileName(fullPath); + + string[] files = Directory.GetFiles(directory, this.GetWildcardPatternForFile(baseFileName)); + + if (files != null) + { + for (int i = 0; i < files.Length; i++) + { + string curFileName = Path.GetFileName(files[i]); + if (curFileName.StartsWith(Path.GetFileNameWithoutExtension(baseFileName))) + { + alFiles.Add(curFileName); + } + } + } + } + } + LogLog.Debug(declaringType, "Searched for existing files in [" + directory + "]"); + return alFiles; + } + + /// + /// Initiates a roll over if needed for crossing a date boundary since the last run. + /// + private void RollOverIfDateBoundaryCrossing() + { + if (this.m_staticLogFileName && this.m_rollDate) + { + if (this.FileExists(this.m_baseFileName)) + { + DateTime last; + using(this.SecurityContext.Impersonate(this)) { +#if !NET_1_0 && !CLI_1_0 && !NETCF + if (this.DateTimeStrategy is UniversalDateTime) + { + last = System.IO.File.GetLastWriteTimeUtc(this.m_baseFileName); + } + else + { +#endif + last = System.IO.File.GetLastWriteTime(this.m_baseFileName); +#if !NET_1_0 && !CLI_1_0 && !NETCF + } +#endif + } + LogLog.Debug(declaringType, "[" + last.ToString(this.m_datePattern,DateTimeFormatInfo.InvariantInfo) + "] vs. [" + this.m_now.ToString(this.m_datePattern,DateTimeFormatInfo.InvariantInfo) + "]"); + + if (!(last.ToString(this.m_datePattern,DateTimeFormatInfo.InvariantInfo).Equals(this.m_now.ToString(this.m_datePattern, DateTimeFormatInfo.InvariantInfo)))) + { + this.m_scheduledFilename = this.CombinePath(this.m_baseFileName, last.ToString(this.m_datePattern, DateTimeFormatInfo.InvariantInfo)); + LogLog.Debug(declaringType, "Initial roll over to ["+ this.m_scheduledFilename+"]"); + this.RollOverTime(false); + LogLog.Debug(declaringType, "curSizeRollBackups after rollOver at ["+ this.m_curSizeRollBackups+"]"); + } + } + } + } + + /// + /// Initializes based on existing conditions at time of . + /// + /// + /// + /// Initializes based on existing conditions at time of . + /// The following is done + /// + /// determine curSizeRollBackups (only within the current roll point) + /// initiates a roll over if needed for crossing a date boundary since the last run. + /// + /// + /// + protected void ExistingInit() + { + this.DetermineCurSizeRollBackups(); + this.RollOverIfDateBoundaryCrossing(); + + // If file exists and we are not appending then roll it out of the way + if (this.AppendToFile == false) + { + bool fileExists = false; + string fileName = this.GetNextOutputFileName(this.m_baseFileName); + + using(this.SecurityContext.Impersonate(this)) + { + fileExists = System.IO.File.Exists(fileName); + } + + if (fileExists) + { + if (this.m_maxSizeRollBackups == 0) + { + LogLog.Debug(declaringType, "Output file [" + fileName + "] already exists. MaxSizeRollBackups is 0; cannot roll. Overwriting existing file."); + } + else + { + LogLog.Debug(declaringType, "Output file [" + fileName + "] already exists. Not appending to file. Rolling existing file out of the way."); + + this.RollOverRenameFiles(fileName); + } + } + } + } + + /// + /// Does the work of bumping the 'current' file counter higher + /// to the highest count when an incremental file name is seen. + /// The highest count is either the first file (when count direction + /// is greater than 0) or the last file (when count direction less than 0). + /// In either case, we want to know the highest count that is present. + /// + /// + /// + private void InitializeFromOneFile(string baseFile, string curFileName) + { + if (curFileName.StartsWith(Path.GetFileNameWithoutExtension(baseFile)) == false) + { + // This is not a log file, so ignore + return; + } + if (curFileName.Equals(baseFile)) + { + // Base log file is not an incremented logfile (.1 or .2, etc) + return; + } + + /* + if (m_staticLogFileName) + { + int endLength = curFileName.Length - index; + if (baseFile.Length + endLength != curFileName.Length) + { + // file is probably scheduledFilename + .x so I don't care + return; + } + } + */ + + // Only look for files in the current roll point + if (this.m_rollDate && !this.m_staticLogFileName) + { + string date = this.m_dateTime.Now.ToString(this.m_datePattern, DateTimeFormatInfo.InvariantInfo); + string prefix = this.m_preserveLogFileNameExtension ? Path.GetFileNameWithoutExtension(baseFile) + date : baseFile + date; + string suffix = this.m_preserveLogFileNameExtension ? Path.GetExtension(baseFile) : string.Empty; + if (!curFileName.StartsWith(prefix) || !curFileName.EndsWith(suffix)) + { + LogLog.Debug(declaringType, "Ignoring file ["+curFileName+"] because it is from a different date period"); + return; + } + } + + try + { + // Bump the counter up to the highest count seen so far + int backup = this.GetBackUpIndex(curFileName); + + // caution: we might get a false positive when certain + // date patterns such as yyyyMMdd are used...those are + // valid number but aren't the kind of back up index + // we're looking for + if (backup > this.m_curSizeRollBackups) + { + if (0 == this.m_maxSizeRollBackups) + { + // Stay at zero when zero backups are desired + } + else if (-1 == this.m_maxSizeRollBackups) + { + // Infinite backups, so go as high as the highest value + this.m_curSizeRollBackups = backup; + } + else + { + // Backups limited to a finite number + if (this.m_countDirection >= 0) + { + // Go with the highest file when counting up + this.m_curSizeRollBackups = backup; + } + else + { + // Clip to the limit when counting down + if (backup <= this.m_maxSizeRollBackups) + { + this.m_curSizeRollBackups = backup; + } + } + } + LogLog.Debug(declaringType, "File name [" + curFileName + "] moves current count to [" + this.m_curSizeRollBackups + "]"); + } + } + catch(FormatException) + { + // this happens when file.log -> file.log.yyyy-MM-dd which is normal + // when staticLogFileName == false + LogLog.Debug(declaringType, "Encountered a backup file not ending in .x [" + curFileName + "]"); + } + } + + /// + /// Attempts to extract a number from the end of the file name that indicates + /// the number of the times the file has been rolled over. + /// + /// + /// Certain date pattern extensions like yyyyMMdd will be parsed as valid backup indexes. + /// + /// + /// + private int GetBackUpIndex(string curFileName) + { + int backUpIndex = -1; + string fileName = curFileName; + + if (this.m_preserveLogFileNameExtension) + { + fileName = Path.GetFileNameWithoutExtension(fileName); + } + + int index = fileName.LastIndexOf("."); + if (index > 0) + { + // if the "yyyy-MM-dd" component of file.log.yyyy-MM-dd is passed to TryParse + // it will gracefully fail and return backUpIndex will be 0 + SystemInfo.TryParse(fileName.Substring(index + 1), out backUpIndex); + } + + return backUpIndex; + } + + /// + /// Takes a list of files and a base file name, and looks for + /// 'incremented' versions of the base file. Bumps the max + /// count up to the highest count seen. + /// + /// + /// + private void InitializeRollBackups(string baseFile, ArrayList arrayFiles) + { + if (null != arrayFiles) + { + string baseFileLower = baseFile.ToLowerInvariant(); + + foreach(string curFileName in arrayFiles) + { + this.InitializeFromOneFile(baseFileLower, curFileName.ToLowerInvariant()); + } + } + } + + /// + /// Calculates the RollPoint for the datePattern supplied. + /// + /// the date pattern to calculate the check period for + /// The RollPoint that is most accurate for the date pattern supplied + /// + /// Essentially the date pattern is examined to determine what the + /// most suitable roll point is. The roll point chosen is the roll point + /// with the smallest period that can be detected using the date pattern + /// supplied. i.e. if the date pattern only outputs the year, month, day + /// and hour then the smallest roll point that can be detected would be + /// and hourly roll point as minutes could not be detected. + /// + private RollPoint ComputeCheckPeriod(string datePattern) + { + // s_date1970 is 1970-01-01 00:00:00 this is UniversalSortableDateTimePattern + // (based on ISO 8601) using universal time. This date is used for reference + // purposes to calculate the resolution of the date pattern. + + // Get string representation of base line date + string r0 = s_date1970.ToString(datePattern, DateTimeFormatInfo.InvariantInfo); + + // Check each type of rolling mode starting with the smallest increment. + for(int i = (int)RollPoint.TopOfMinute; i <= (int)RollPoint.TopOfMonth; i++) + { + // Get string representation of next pattern + string r1 = this.NextCheckDate(s_date1970, (RollPoint)i).ToString(datePattern, DateTimeFormatInfo.InvariantInfo); + + LogLog.Debug(declaringType, "Type = [" + i + "], r0 = [" + r0 + "], r1 = [" + r1 + "]"); + + // Check if the string representations are different + if (r0 != null && r1 != null && !r0.Equals(r1)) + { + // Found highest precision roll point + return (RollPoint)i; + } + } + + return RollPoint.InvalidRollPoint; // Deliberately head for trouble... + } + + /// + /// Initialize the appender based on the options set + /// + /// + /// + /// This is part of the delayed object + /// activation scheme. The method must + /// be called on this object after the configuration properties have + /// been set. Until is called this + /// object is in an undefined state and must not be used. + /// + /// + /// If any of the configuration properties are modified then + /// must be called again. + /// + /// + /// Sets initial conditions including date/time roll over information, first check, + /// scheduledFilename, and calls to initialize + /// the current number of backups. + /// + /// + public override void ActivateOptions() + { + if (this.m_dateTime == null) + { + this.m_dateTime = new LocalDateTime(); + } + + if (this.m_rollDate && this.m_datePattern != null) + { + this.m_now = this.m_dateTime.Now; + this.m_rollPoint = this.ComputeCheckPeriod(this.m_datePattern); + + if (this.m_rollPoint == RollPoint.InvalidRollPoint) + { + throw new ArgumentException("Invalid RollPoint, unable to parse [" + this.m_datePattern + "]"); + } + + // next line added as this removes the name check in rollOver + this.m_nextCheck = this.NextCheckDate(this.m_now, this.m_rollPoint); + } + else + { + if (this.m_rollDate) + { + this.ErrorHandler.Error("Either DatePattern or rollingStyle options are not set for [" + this.Name + "]."); + } + } + + if (this.SecurityContext == null) + { + this.SecurityContext = SecurityContextProvider.DefaultProvider.CreateSecurityContext(this); + } + + using(this.SecurityContext.Impersonate(this)) + { + // Must convert the FileAppender's m_filePath to an absolute path before we + // call ExistingInit(). This will be done by the base.ActivateOptions() but + // we need to duplicate that functionality here first. + base.File = ConvertToFullPath(base.File.Trim()); + + // Store fully qualified base file name + this.m_baseFileName = base.File; + } + +#if !NETCF + // initialize the mutex that is used to lock rolling + this.m_mutexForRolling = new Mutex(false, this.m_baseFileName + .Replace("\\", "_") + .Replace(":", "_") + .Replace("/", "_") + "_rolling" + ); +#endif + + if (this.m_rollDate && this.File != null && this.m_scheduledFilename == null) + { + this.m_scheduledFilename = this.CombinePath(this.File, this.m_now.ToString(this.m_datePattern, DateTimeFormatInfo.InvariantInfo)); + } + + this.ExistingInit(); + + base.ActivateOptions(); + } + + /// + /// + /// + /// + /// .1, .2, .3, etc. + /// + private string CombinePath(string path1, string path2) + { + string extension = Path.GetExtension(path1); + if (this.m_preserveLogFileNameExtension && extension.Length > 0) + { + return Path.Combine(Path.GetDirectoryName(path1), Path.GetFileNameWithoutExtension(path1) + path2 + extension); + } + else + { + return path1 + path2; + } + } + + /// + /// Rollover the file(s) to date/time tagged file(s). + /// + /// set to true if the file to be rolled is currently open + /// + /// + /// Rollover the file(s) to date/time tagged file(s). + /// Resets curSizeRollBackups. + /// If fileIsOpen is set then the new file is opened (through SafeOpenFile). + /// + /// + protected void RollOverTime(bool fileIsOpen) + { + if (this.m_staticLogFileName) + { + // Compute filename, but only if datePattern is specified + if (this.m_datePattern == null) + { + this.ErrorHandler.Error("Missing DatePattern option in rollOver()."); + return; + } + + // is the new file name equivalent to the 'current' one + // something has gone wrong if we hit this -- we should only + // roll over if the new file will be different from the old + string dateFormat = this.m_now.ToString(this.m_datePattern, DateTimeFormatInfo.InvariantInfo); + if (this.m_scheduledFilename.Equals(this.CombinePath(this.File, dateFormat))) + { + this.ErrorHandler.Error("Compare " + this.m_scheduledFilename + " : " + this.CombinePath(this.File, dateFormat)); + return; + } + + if (fileIsOpen) + { + // close current file, and rename it to datedFilename + this.CloseFile(); + } + + // we may have to roll over a large number of backups here + for (int i = 1; i <= this.m_curSizeRollBackups; i++) + { + string from = this.CombinePath(this.File, "." + i); + string to = this.CombinePath(this.m_scheduledFilename, "." + i); + this.RollFile(from, to); + } + + this.RollFile(this.File, this.m_scheduledFilename); + } + + // We've cleared out the old date and are ready for the new + this.m_curSizeRollBackups = 0; + + // new scheduled name + this.m_scheduledFilename = this.CombinePath(this.File, this.m_now.ToString(this.m_datePattern, DateTimeFormatInfo.InvariantInfo)); + + if (fileIsOpen) + { + // This will also close the file. This is OK since multiple close operations are safe. + this.SafeOpenFile(this.m_baseFileName, false); + } + } + + /// + /// Renames file to file . + /// + /// Name of existing file to roll. + /// New name for file. + /// + /// + /// Renames file to file . It + /// also checks for existence of target file and deletes if it does. + /// + /// + protected void RollFile(string fromFile, string toFile) + { + if (this.FileExists(fromFile)) + { + // Delete the toFile if it exists + this.DeleteFile(toFile); + + // We may not have permission to move the file, or the file may be locked + try + { + LogLog.Debug(declaringType, "Moving [" + fromFile + "] -> [" + toFile + "]"); + using(this.SecurityContext.Impersonate(this)) + { + System.IO.File.Move(fromFile, toFile); + } + } + catch(Exception moveEx) + { + this.ErrorHandler.Error("Exception while rolling file [" + fromFile + "] -> [" + toFile + "]", moveEx, ErrorCode.GenericFailure); + } + } + else + { + LogLog.Warn(declaringType, "Cannot RollFile [" + fromFile + "] -> [" + toFile + "]. Source does not exist"); + } } - /// - /// Determines curSizeRollBackups (only within the current roll point). - /// - private void DetermineCurSizeRollBackups() - { - this.m_curSizeRollBackups = 0; - - string fullPath = null; - string fileName = null; - - using (this.SecurityContext.Impersonate(this)) - { - fullPath = System.IO.Path.GetFullPath(this.m_baseFileName); - fileName = System.IO.Path.GetFileName(fullPath); - } - - ArrayList arrayFiles = this.GetExistingFiles(fullPath); - this.InitializeRollBackups(fileName, arrayFiles); - - LogLog.Debug(declaringType, "curSizeRollBackups starts at [" + this.m_curSizeRollBackups + "]"); - } - - /// - /// Generates a wildcard pattern that can be used to find all files - /// that are similar to the base file name. - /// - /// - /// - private string GetWildcardPatternForFile(string baseFileName) - { - if (this.m_preserveLogFileNameExtension) - { - return Path.GetFileNameWithoutExtension(baseFileName) + "*" + Path.GetExtension(baseFileName); - } - else - { - return baseFileName + '*'; - } - } - - /// - /// Builds a list of filenames for all files matching the base filename plus a file - /// pattern. - /// - /// - /// - private ArrayList GetExistingFiles(string baseFilePath) - { - ArrayList alFiles = new ArrayList(); - - string directory = null; - - using (this.SecurityContext.Impersonate(this)) - { - string fullPath = Path.GetFullPath(baseFilePath); - - directory = Path.GetDirectoryName(fullPath); - if (Directory.Exists(directory)) - { - string baseFileName = Path.GetFileName(fullPath); - - string[] files = Directory.GetFiles(directory, this.GetWildcardPatternForFile(baseFileName)); - - if (files != null) - { - for (int i = 0; i < files.Length; i++) - { - string curFileName = Path.GetFileName(files[i]); - if (curFileName.StartsWith(Path.GetFileNameWithoutExtension(baseFileName))) - { - alFiles.Add(curFileName); - } - } - } - } - } - - LogLog.Debug(declaringType, "Searched for existing files in [" + directory + "]"); - return alFiles; - } - - /// - /// Initiates a roll over if needed for crossing a date boundary since the last run. - /// - private void RollOverIfDateBoundaryCrossing() - { - if (this.m_staticLogFileName && this.m_rollDate) - { - if (this.FileExists(this.m_baseFileName)) - { - DateTime last; - using (this.SecurityContext.Impersonate(this)) - { -#if !NET_1_0 && !CLI_1_0 && !NETCF - if (this.DateTimeStrategy is UniversalDateTime) - { - last = System.IO.File.GetLastWriteTimeUtc(this.m_baseFileName); - } - else - { -#endif - last = System.IO.File.GetLastWriteTime(this.m_baseFileName); -#if !NET_1_0 && !CLI_1_0 && !NETCF - } -#endif - } - - LogLog.Debug(declaringType, "[" + last.ToString(this.m_datePattern, System.Globalization.DateTimeFormatInfo.InvariantInfo) + "] vs. [" + this.m_now.ToString(this.m_datePattern, System.Globalization.DateTimeFormatInfo.InvariantInfo) + "]"); - - if (!last.ToString(this.m_datePattern, System.Globalization.DateTimeFormatInfo.InvariantInfo).Equals(this.m_now.ToString(this.m_datePattern, System.Globalization.DateTimeFormatInfo.InvariantInfo))) - { - this.m_scheduledFilename = this.CombinePath(this.m_baseFileName, last.ToString(this.m_datePattern, System.Globalization.DateTimeFormatInfo.InvariantInfo)); - LogLog.Debug(declaringType, "Initial roll over to [" + this.m_scheduledFilename + "]"); - this.RollOverTime(false); - LogLog.Debug(declaringType, "curSizeRollBackups after rollOver at [" + this.m_curSizeRollBackups + "]"); - } - } - } - } - - /// - /// Initializes based on existing conditions at time of . - /// - /// - /// - /// Initializes based on existing conditions at time of . - /// The following is done. - /// - /// determine curSizeRollBackups (only within the current roll point) - /// initiates a roll over if needed for crossing a date boundary since the last run. - /// - /// - /// - protected void ExistingInit() - { - this.DetermineCurSizeRollBackups(); - this.RollOverIfDateBoundaryCrossing(); - - // If file exists and we are not appending then roll it out of the way - if (this.AppendToFile == false) - { - bool fileExists = false; - string fileName = this.GetNextOutputFileName(this.m_baseFileName); - - using (this.SecurityContext.Impersonate(this)) - { - fileExists = System.IO.File.Exists(fileName); - } - - if (fileExists) - { - if (this.m_maxSizeRollBackups == 0) - { - LogLog.Debug(declaringType, "Output file [" + fileName + "] already exists. MaxSizeRollBackups is 0; cannot roll. Overwriting existing file."); - } - else - { - LogLog.Debug(declaringType, "Output file [" + fileName + "] already exists. Not appending to file. Rolling existing file out of the way."); - - this.RollOverRenameFiles(fileName); - } - } - } - } - - /// - /// Does the work of bumping the 'current' file counter higher - /// to the highest count when an incremental file name is seen. - /// The highest count is either the first file (when count direction - /// is greater than 0) or the last file (when count direction less than 0). - /// In either case, we want to know the highest count that is present. - /// - /// - /// - private void InitializeFromOneFile(string baseFile, string curFileName) - { - if (curFileName.StartsWith(Path.GetFileNameWithoutExtension(baseFile)) == false) - { - // This is not a log file, so ignore - return; - } - - if (curFileName.Equals(baseFile)) - { - // Base log file is not an incremented logfile (.1 or .2, etc) - return; - } - - /* - if (m_staticLogFileName) - { - int endLength = curFileName.Length - index; - if (baseFile.Length + endLength != curFileName.Length) - { - // file is probably scheduledFilename + .x so I don't care - return; - } - } - */ - - // Only look for files in the current roll point - if (this.m_rollDate && !this.m_staticLogFileName) - { - string date = this.m_dateTime.Now.ToString(this.m_datePattern, System.Globalization.DateTimeFormatInfo.InvariantInfo); - string prefix = this.m_preserveLogFileNameExtension ? Path.GetFileNameWithoutExtension(baseFile) + date : baseFile + date; - string suffix = this.m_preserveLogFileNameExtension ? Path.GetExtension(baseFile) : string.Empty; - if (!curFileName.StartsWith(prefix) || !curFileName.EndsWith(suffix)) - { - LogLog.Debug(declaringType, "Ignoring file [" + curFileName + "] because it is from a different date period"); - return; - } - } - - try - { - // Bump the counter up to the highest count seen so far - int backup = this.GetBackUpIndex(curFileName); - - // caution: we might get a false positive when certain - // date patterns such as yyyyMMdd are used...those are - // valid number but aren't the kind of back up index - // we're looking for - if (backup > this.m_curSizeRollBackups) - { - if (this.m_maxSizeRollBackups == 0) - { - // Stay at zero when zero backups are desired - } - else if (this.m_maxSizeRollBackups == -1) - { - // Infinite backups, so go as high as the highest value - this.m_curSizeRollBackups = backup; - } - else - { - // Backups limited to a finite number - if (this.m_countDirection >= 0) - { - // Go with the highest file when counting up - this.m_curSizeRollBackups = backup; - } - else - { - // Clip to the limit when counting down - if (backup <= this.m_maxSizeRollBackups) - { - this.m_curSizeRollBackups = backup; - } - } - } - - LogLog.Debug(declaringType, "File name [" + curFileName + "] moves current count to [" + this.m_curSizeRollBackups + "]"); - } - } - catch (FormatException) - { - // this happens when file.log -> file.log.yyyy-MM-dd which is normal - // when staticLogFileName == false - LogLog.Debug(declaringType, "Encountered a backup file not ending in .x [" + curFileName + "]"); - } - } - - /// - /// Attempts to extract a number from the end of the file name that indicates - /// the number of the times the file has been rolled over. - /// - /// - /// Certain date pattern extensions like yyyyMMdd will be parsed as valid backup indexes. - /// - /// - /// - private int GetBackUpIndex(string curFileName) - { - int backUpIndex = -1; - string fileName = curFileName; - - if (this.m_preserveLogFileNameExtension) - { - fileName = Path.GetFileNameWithoutExtension(fileName); - } - - int index = fileName.LastIndexOf("."); - if (index > 0) - { - // if the "yyyy-MM-dd" component of file.log.yyyy-MM-dd is passed to TryParse - // it will gracefully fail and return backUpIndex will be 0 - SystemInfo.TryParse(fileName.Substring(index + 1), out backUpIndex); - } - - return backUpIndex; - } - - /// - /// Takes a list of files and a base file name, and looks for - /// 'incremented' versions of the base file. Bumps the max - /// count up to the highest count seen. - /// - /// - /// - private void InitializeRollBackups(string baseFile, ArrayList arrayFiles) - { - if (arrayFiles != null) - { - string baseFileLower = baseFile.ToLower(System.Globalization.CultureInfo.InvariantCulture); - - foreach (string curFileName in arrayFiles) - { - this.InitializeFromOneFile(baseFileLower, curFileName.ToLower(System.Globalization.CultureInfo.InvariantCulture)); - } - } - } - - /// - /// Calculates the RollPoint for the datePattern supplied. - /// - /// the date pattern to calculate the check period for. - /// The RollPoint that is most accurate for the date pattern supplied. - /// - /// Essentially the date pattern is examined to determine what the - /// most suitable roll point is. The roll point chosen is the roll point - /// with the smallest period that can be detected using the date pattern - /// supplied. i.e. if the date pattern only outputs the year, month, day - /// and hour then the smallest roll point that can be detected would be - /// and hourly roll point as minutes could not be detected. - /// - private RollPoint ComputeCheckPeriod(string datePattern) - { - // s_date1970 is 1970-01-01 00:00:00 this is UniversalSortableDateTimePattern - // (based on ISO 8601) using universal time. This date is used for reference - // purposes to calculate the resolution of the date pattern. - - // Get string representation of base line date - string r0 = s_date1970.ToString(datePattern, System.Globalization.DateTimeFormatInfo.InvariantInfo); - - // Check each type of rolling mode starting with the smallest increment. - for (int i = (int)RollPoint.TopOfMinute; i <= (int)RollPoint.TopOfMonth; i++) - { - // Get string representation of next pattern - string r1 = this.NextCheckDate(s_date1970, (RollPoint)i).ToString(datePattern, System.Globalization.DateTimeFormatInfo.InvariantInfo); - - LogLog.Debug(declaringType, "Type = [" + i + "], r0 = [" + r0 + "], r1 = [" + r1 + "]"); - - // Check if the string representations are different - if (r0 != null && r1 != null && !r0.Equals(r1)) - { - // Found highest precision roll point - return (RollPoint)i; - } - } - - return RollPoint.InvalidRollPoint; // Deliberately head for trouble... - } - - /// - /// Initialize the appender based on the options set. - /// - /// - /// - /// This is part of the delayed object - /// activation scheme. The method must - /// be called on this object after the configuration properties have - /// been set. Until is called this - /// object is in an undefined state and must not be used. - /// - /// - /// If any of the configuration properties are modified then - /// must be called again. - /// - /// - /// Sets initial conditions including date/time roll over information, first check, - /// scheduledFilename, and calls to initialize - /// the current number of backups. - /// - /// - public override void ActivateOptions() - { - if (this.m_dateTime == null) - { - this.m_dateTime = new LocalDateTime(); - } - - if (this.m_rollDate && this.m_datePattern != null) - { - this.m_now = this.m_dateTime.Now; - this.m_rollPoint = this.ComputeCheckPeriod(this.m_datePattern); - - if (this.m_rollPoint == RollPoint.InvalidRollPoint) - { - throw new ArgumentException("Invalid RollPoint, unable to parse [" + this.m_datePattern + "]"); - } - - // next line added as this removes the name check in rollOver - this.m_nextCheck = this.NextCheckDate(this.m_now, this.m_rollPoint); - } - else - { - if (this.m_rollDate) - { - this.ErrorHandler.Error("Either DatePattern or rollingStyle options are not set for [" + this.Name + "]."); - } - } - - if (this.SecurityContext == null) - { - this.SecurityContext = SecurityContextProvider.DefaultProvider.CreateSecurityContext(this); - } - - using (this.SecurityContext.Impersonate(this)) - { - // Must convert the FileAppender's m_filePath to an absolute path before we - // call ExistingInit(). This will be done by the base.ActivateOptions() but - // we need to duplicate that functionality here first. - this.File = ConvertToFullPath(this.File.Trim()); - - // Store fully qualified base file name - this.m_baseFileName = this.File; - } - -#if !NETCF - // initialize the mutex that is used to lock rolling - this.m_mutexForRolling = new Mutex(false, this.m_baseFileName.Replace("\\", "_").Replace(":", "_").Replace("/", "_")); -#endif - - if (this.m_rollDate && this.File != null && this.m_scheduledFilename == null) - { - this.m_scheduledFilename = this.CombinePath(this.File, this.m_now.ToString(this.m_datePattern, System.Globalization.DateTimeFormatInfo.InvariantInfo)); - } - - this.ExistingInit(); - - base.ActivateOptions(); + /// + /// Test if a file exists at a specified path + /// + /// the path to the file + /// true if the file exists + /// + /// + /// Test if a file exists at a specified path + /// + /// + protected bool FileExists(string path) + { + using(this.SecurityContext.Impersonate(this)) + { + return System.IO.File.Exists(path); + } } + + /// + /// Deletes the specified file if it exists. + /// + /// The file to delete. + /// + /// + /// Delete a file if is exists. + /// The file is first moved to a new filename then deleted. + /// This allows the file to be removed even when it cannot + /// be deleted, but it still can be moved. + /// + /// + protected void DeleteFile(string fileName) + { + if (this.FileExists(fileName)) + { + // We may not have permission to delete the file, or the file may be locked + + string fileToDelete = fileName; + + // Try to move the file to temp name. + // If the file is locked we may still be able to move it + string tempFileName = fileName + "." + Environment.TickCount + ".DeletePending"; + try + { + using(this.SecurityContext.Impersonate(this)) + { + System.IO.File.Move(fileName, tempFileName); + } + fileToDelete = tempFileName; + } + catch(Exception moveEx) + { + LogLog.Debug(declaringType, "Exception while moving file to be deleted [" + fileName + "] -> [" + tempFileName + "]", moveEx); + } - /// - /// - /// - /// - /// .1, .2, .3, etc. - /// - private string CombinePath(string path1, string path2) - { - string extension = Path.GetExtension(path1); - if (this.m_preserveLogFileNameExtension && extension.Length > 0) - { - return Path.Combine(Path.GetDirectoryName(path1), Path.GetFileNameWithoutExtension(path1) + path2 + extension); - } - else - { - return path1 + path2; - } - } - - /// - /// Rollover the file(s) to date/time tagged file(s). - /// - /// set to true if the file to be rolled is currently open. - /// - /// - /// Rollover the file(s) to date/time tagged file(s). - /// Resets curSizeRollBackups. - /// If fileIsOpen is set then the new file is opened (through SafeOpenFile). - /// - /// - protected void RollOverTime(bool fileIsOpen) - { - if (this.m_staticLogFileName) - { - // Compute filename, but only if datePattern is specified - if (this.m_datePattern == null) - { - this.ErrorHandler.Error("Missing DatePattern option in rollOver()."); - return; - } - - // is the new file name equivalent to the 'current' one - // something has gone wrong if we hit this -- we should only - // roll over if the new file will be different from the old - string dateFormat = this.m_now.ToString(this.m_datePattern, System.Globalization.DateTimeFormatInfo.InvariantInfo); - if (this.m_scheduledFilename.Equals(this.CombinePath(this.File, dateFormat))) - { - this.ErrorHandler.Error("Compare " + this.m_scheduledFilename + " : " + this.CombinePath(this.File, dateFormat)); - return; - } - - if (fileIsOpen) - { - // close current file, and rename it to datedFilename - this.CloseFile(); - } - - // we may have to roll over a large number of backups here - for (int i = 1; i <= this.m_curSizeRollBackups; i++) - { - string from = this.CombinePath(this.File, "." + i); - string to = this.CombinePath(this.m_scheduledFilename, "." + i); - this.RollFile(from, to); - } - - this.RollFile(this.File, this.m_scheduledFilename); - } - - // We've cleared out the old date and are ready for the new - this.m_curSizeRollBackups = 0; - - // new scheduled name - this.m_scheduledFilename = this.CombinePath(this.File, this.m_now.ToString(this.m_datePattern, System.Globalization.DateTimeFormatInfo.InvariantInfo)); - - if (fileIsOpen) - { - // This will also close the file. This is OK since multiple close operations are safe. - this.SafeOpenFile(this.m_baseFileName, false); - } - } - - /// - /// Renames file to file . - /// - /// Name of existing file to roll. - /// New name for file. - /// - /// - /// Renames file to file . It - /// also checks for existence of target file and deletes if it does. - /// - /// - protected void RollFile(string fromFile, string toFile) - { - if (this.FileExists(fromFile)) - { - // Delete the toFile if it exists - this.DeleteFile(toFile); - - // We may not have permission to move the file, or the file may be locked - try - { - LogLog.Debug(declaringType, "Moving [" + fromFile + "] -> [" + toFile + "]"); - using (this.SecurityContext.Impersonate(this)) - { - System.IO.File.Move(fromFile, toFile); - } - } - catch (Exception moveEx) - { - this.ErrorHandler.Error("Exception while rolling file [" + fromFile + "] -> [" + toFile + "]", moveEx, ErrorCode.GenericFailure); - } - } - else - { - LogLog.Warn(declaringType, "Cannot RollFile [" + fromFile + "] -> [" + toFile + "]. Source does not exist"); - } - } - - /// - /// Test if a file exists at a specified path. - /// - /// the path to the file. - /// true if the file exists. - /// - /// - /// Test if a file exists at a specified path. - /// - /// - protected bool FileExists(string path) - { - using (this.SecurityContext.Impersonate(this)) - { - return System.IO.File.Exists(path); - } - } - - /// - /// Deletes the specified file if it exists. - /// - /// The file to delete. - /// - /// - /// Delete a file if is exists. - /// The file is first moved to a new filename then deleted. - /// This allows the file to be removed even when it cannot - /// be deleted, but it still can be moved. - /// - /// - protected void DeleteFile(string fileName) - { - if (this.FileExists(fileName)) - { - // We may not have permission to delete the file, or the file may be locked - string fileToDelete = fileName; - - // Try to move the file to temp name. - // If the file is locked we may still be able to move it - string tempFileName = fileName + "." + Environment.TickCount + ".DeletePending"; - try - { - using (this.SecurityContext.Impersonate(this)) - { - System.IO.File.Move(fileName, tempFileName); - } - - fileToDelete = tempFileName; - } - catch (Exception moveEx) - { - LogLog.Debug(declaringType, "Exception while moving file to be deleted [" + fileName + "] -> [" + tempFileName + "]", moveEx); - } - - // Try to delete the file (either the original or the moved file) - try - { - using (this.SecurityContext.Impersonate(this)) - { - System.IO.File.Delete(fileToDelete); - } - - LogLog.Debug(declaringType, "Deleted file [" + fileName + "]"); - } - catch (Exception deleteEx) - { - if (fileToDelete == fileName) - { - // Unable to move or delete the file - this.ErrorHandler.Error("Exception while deleting file [" + fileToDelete + "]", deleteEx, ErrorCode.GenericFailure); - } - else - { - // Moved the file, but the delete failed. File is probably locked. - // The file should automatically be deleted when the lock is released. - LogLog.Debug(declaringType, "Exception while deleting temp file [" + fileToDelete + "]", deleteEx); - } - } - } - } - - /// - /// Implements file roll base on file size. - /// - /// - /// - /// If the maximum number of size based backups is reached - /// (curSizeRollBackups == maxSizeRollBackups) then the oldest - /// file is deleted -- its index determined by the sign of countDirection. - /// If countDirection < 0, then files - /// {File.1, ..., File.curSizeRollBackups -1} - /// are renamed to {File.2, ..., - /// File.curSizeRollBackups}. Moreover, File is - /// renamed File.1 and closed. - /// - /// - /// A new file is created to receive further log output. - /// - /// - /// If maxSizeRollBackups is equal to zero, then the - /// File is truncated with no backup files created. - /// - /// - /// If maxSizeRollBackups < 0, then File is - /// renamed if needed and no files are deleted. - /// - /// - protected void RollOverSize() - { - this.CloseFile(); // keep windows happy. - - LogLog.Debug(declaringType, "rolling over count [" + ((CountingQuietTextWriter)this.QuietWriter).Count + "]"); - LogLog.Debug(declaringType, "maxSizeRollBackups [" + this.m_maxSizeRollBackups + "]"); - LogLog.Debug(declaringType, "curSizeRollBackups [" + this.m_curSizeRollBackups + "]"); - LogLog.Debug(declaringType, "countDirection [" + this.m_countDirection + "]"); - - this.RollOverRenameFiles(this.File); - - if (!this.m_staticLogFileName && this.m_countDirection >= 0) - { - this.m_curSizeRollBackups++; - } - - // This will also close the file. This is OK since multiple close operations are safe. - this.SafeOpenFile(this.m_baseFileName, false); - } - - /// - /// Implements file roll. - /// - /// the base name to rename. - /// - /// - /// If the maximum number of size based backups is reached - /// (curSizeRollBackups == maxSizeRollBackups) then the oldest - /// file is deleted -- its index determined by the sign of countDirection. - /// If countDirection < 0, then files - /// {File.1, ..., File.curSizeRollBackups -1} - /// are renamed to {File.2, ..., - /// File.curSizeRollBackups}. - /// - /// - /// If maxSizeRollBackups is equal to zero, then the - /// File is truncated with no backup files created. - /// - /// - /// If maxSizeRollBackups < 0, then File is - /// renamed if needed and no files are deleted. - /// - /// - /// This is called by to rename the files. - /// - /// - protected void RollOverRenameFiles(string baseFileName) - { - // If maxBackups <= 0, then there is no file renaming to be done. - if (this.m_maxSizeRollBackups != 0) - { - if (this.m_countDirection < 0) - { - // Delete the oldest file, to keep Windows happy. - if (this.m_curSizeRollBackups == this.m_maxSizeRollBackups) - { - this.DeleteFile(this.CombinePath(baseFileName, "." + this.m_maxSizeRollBackups)); - this.m_curSizeRollBackups--; - } - - // Map {(maxBackupIndex - 1), ..., 2, 1} to {maxBackupIndex, ..., 3, 2} - for (int i = this.m_curSizeRollBackups; i >= 1; i--) - { - this.RollFile(this.CombinePath(baseFileName, "." + i), this.CombinePath(baseFileName, "." + (i + 1))); - } - - this.m_curSizeRollBackups++; - - // Rename fileName to fileName.1 - this.RollFile(baseFileName, this.CombinePath(baseFileName, ".1")); - } - else - { - // countDirection >= 0 - if (this.m_curSizeRollBackups >= this.m_maxSizeRollBackups && this.m_maxSizeRollBackups > 0) - { - // delete the first and keep counting up. - int oldestFileIndex = this.m_curSizeRollBackups - this.m_maxSizeRollBackups; - - // If static then there is 1 file without a number, therefore 1 less archive - if (this.m_staticLogFileName) - { - oldestFileIndex++; - } - - // If using a static log file then the base for the numbered sequence is the baseFileName passed in - // If not using a static log file then the baseFileName will already have a numbered postfix which - // we must remove, however it may have a date postfix which we must keep! - string archiveFileBaseName = baseFileName; - if (!this.m_staticLogFileName) - { - int lastDotIndex = archiveFileBaseName.LastIndexOf("."); - if (lastDotIndex >= 0) - { - archiveFileBaseName = archiveFileBaseName.Substring(0, lastDotIndex); - } - } - - // Delete the archive file - this.DeleteFile(this.CombinePath(archiveFileBaseName, "." + oldestFileIndex)); - } - - if (this.m_staticLogFileName) - { - this.m_curSizeRollBackups++; - this.RollFile(baseFileName, this.CombinePath(baseFileName, "." + this.m_curSizeRollBackups)); - } - } - } + // Try to delete the file (either the original or the moved file) + try + { + using(this.SecurityContext.Impersonate(this)) + { + System.IO.File.Delete(fileToDelete); + } + LogLog.Debug(declaringType, "Deleted file [" + fileName + "]"); + } + catch(Exception deleteEx) + { + if (fileToDelete == fileName) + { + // Unable to move or delete the file + this.ErrorHandler.Error("Exception while deleting file [" + fileToDelete + "]", deleteEx, ErrorCode.GenericFailure); + } + else + { + // Moved the file, but the delete failed. File is probably locked. + // The file should automatically be deleted when the lock is released. + LogLog.Debug(declaringType, "Exception while deleting temp file [" + fileToDelete + "]", deleteEx); + } + } + } } + + /// + /// Implements file roll base on file size. + /// + /// + /// + /// If the maximum number of size based backups is reached + /// (curSizeRollBackups == maxSizeRollBackups) then the oldest + /// file is deleted -- its index determined by the sign of countDirection. + /// If countDirection < 0, then files + /// {File.1, ..., File.curSizeRollBackups -1} + /// are renamed to {File.2, ..., + /// File.curSizeRollBackups}. Moreover, File is + /// renamed File.1 and closed. + /// + /// + /// A new file is created to receive further log output. + /// + /// + /// If maxSizeRollBackups is equal to zero, then the + /// File is truncated with no backup files created. + /// + /// + /// If maxSizeRollBackups < 0, then File is + /// renamed if needed and no files are deleted. + /// + /// + protected void RollOverSize() + { + this.CloseFile(); // keep windows happy. + + LogLog.Debug(declaringType, "rolling over count [" + ((CountingQuietTextWriter)this.QuietWriter).Count + "]"); + LogLog.Debug(declaringType, "maxSizeRollBackups [" + this.m_maxSizeRollBackups + "]"); + LogLog.Debug(declaringType, "curSizeRollBackups [" + this.m_curSizeRollBackups + "]"); + LogLog.Debug(declaringType, "countDirection [" + this.m_countDirection + "]"); + + this.RollOverRenameFiles(this.File); + + if (!this.m_staticLogFileName && this.m_countDirection >= 0) + { + this.m_curSizeRollBackups++; + } - /// - /// Get the start time of the next window for the current rollpoint. - /// - /// the current date. - /// the type of roll point we are working with. - /// the start time for the next roll point an interval after the currentDateTime date. - /// - /// - /// Returns the date of the next roll point after the currentDateTime date passed to the method. - /// - /// - /// The basic strategy is to subtract the time parts that are less significant - /// than the rollpoint from the current time. This should roll the time back to - /// the start of the time window for the current rollpoint. Then we add 1 window - /// worth of time and get the start time of the next window for the rollpoint. - /// - /// - protected DateTime NextCheckDate(DateTime currentDateTime, RollPoint rollPoint) - { - // Local variable to work on (this does not look very efficient) - DateTime current = currentDateTime; - - // Do slightly different things depending on what the type of roll point we want. - switch (rollPoint) - { - case RollPoint.TopOfMinute: - current = current.AddMilliseconds(-current.Millisecond); - current = current.AddSeconds(-current.Second); - current = current.AddMinutes(1); - break; - - case RollPoint.TopOfHour: - current = current.AddMilliseconds(-current.Millisecond); - current = current.AddSeconds(-current.Second); - current = current.AddMinutes(-current.Minute); - current = current.AddHours(1); - break; - - case RollPoint.HalfDay: - current = current.AddMilliseconds(-current.Millisecond); - current = current.AddSeconds(-current.Second); - current = current.AddMinutes(-current.Minute); - - if (current.Hour < 12) - { - current = current.AddHours(12 - current.Hour); - } - else - { - current = current.AddHours(-current.Hour); - current = current.AddDays(1); - } - - break; - - case RollPoint.TopOfDay: - current = current.AddMilliseconds(-current.Millisecond); - current = current.AddSeconds(-current.Second); - current = current.AddMinutes(-current.Minute); - current = current.AddHours(-current.Hour); - current = current.AddDays(1); - break; - - case RollPoint.TopOfWeek: - current = current.AddMilliseconds(-current.Millisecond); - current = current.AddSeconds(-current.Second); - current = current.AddMinutes(-current.Minute); - current = current.AddHours(-current.Hour); - current = current.AddDays(7 - (int)current.DayOfWeek); - break; - - case RollPoint.TopOfMonth: - current = current.AddMilliseconds(-current.Millisecond); - current = current.AddSeconds(-current.Second); - current = current.AddMinutes(-current.Minute); - current = current.AddHours(-current.Hour); - current = current.AddDays(1 - current.Day); /* first day of month is 1 not 0 */ - current = current.AddMonths(1); - break; - } - - return current; + // This will also close the file. This is OK since multiple close operations are safe. + this.SafeOpenFile(this.m_baseFileName, false); } - /// - /// This object supplies the current date/time. Allows test code to plug in - /// a method to control this class when testing date/time based rolling. The default - /// implementation uses the underlying value of DateTime.Now. - /// - private IDateTime m_dateTime = null; - - /// - /// The date pattern. By default, the pattern is set to ".yyyy-MM-dd" - /// meaning daily rollover. - /// - private string m_datePattern = ".yyyy-MM-dd"; - - /// - /// The actual formatted filename that is currently being written to - /// or will be the file transferred to on roll over - /// (based on staticLogFileName). - /// - private string m_scheduledFilename = null; - - /// - /// The timestamp when we shall next recompute the filename. - /// - private DateTime m_nextCheck = DateTime.MaxValue; - - /// - /// Holds date of last roll over. - /// - private DateTime m_now; - - /// - /// The type of rolling done. - /// - private RollPoint m_rollPoint; - - /// - /// The default maximum file size is 10MB. - /// - private long m_maxFileSize = 10 * 1024 * 1024; - - /// - /// There is zero backup files by default. - /// - private int m_maxSizeRollBackups = 0; - - /// - /// How many sized based backups have been made so far. - /// - private int m_curSizeRollBackups = 0; - - /// - /// The rolling file count direction. - /// - private int m_countDirection = -1; - - /// - /// The rolling mode used in this appender. - /// - private RollingMode m_rollingStyle = RollingMode.Composite; - - /// - /// Cache flag set if we are rolling by date. - /// - private bool m_rollDate = true; - - /// - /// Cache flag set if we are rolling by size. - /// - private bool m_rollSize = true; - - /// - /// Value indicating whether to always log to the same file. - /// - private bool m_staticLogFileName = true; - - /// - /// Value indicating whether to preserve the file name extension when rolling. - /// - private bool m_preserveLogFileNameExtension = false; - - /// - /// FileName provided in configuration. Used for rolling properly. - /// - private string m_baseFileName; - -#if !NETCF - /// - /// A mutex that is used to lock rolling of files. - /// + /// + /// Implements file roll. + /// + /// the base name to rename + /// + /// + /// If the maximum number of size based backups is reached + /// (curSizeRollBackups == maxSizeRollBackups) then the oldest + /// file is deleted -- its index determined by the sign of countDirection. + /// If countDirection < 0, then files + /// {File.1, ..., File.curSizeRollBackups -1} + /// are renamed to {File.2, ..., + /// File.curSizeRollBackups}. + /// + /// + /// If maxSizeRollBackups is equal to zero, then the + /// File is truncated with no backup files created. + /// + /// + /// If maxSizeRollBackups < 0, then File is + /// renamed if needed and no files are deleted. + /// + /// + /// This is called by to rename the files. + /// + /// + protected void RollOverRenameFiles(string baseFileName) + { + // If maxBackups <= 0, then there is no file renaming to be done. + if (this.m_maxSizeRollBackups != 0) + { + if (this.m_countDirection < 0) + { + // Delete the oldest file, to keep Windows happy. + if (this.m_curSizeRollBackups == this.m_maxSizeRollBackups) + { + this.DeleteFile(this.CombinePath(baseFileName, "." + this.m_maxSizeRollBackups)); + this.m_curSizeRollBackups--; + } + + // Map {(maxBackupIndex - 1), ..., 2, 1} to {maxBackupIndex, ..., 3, 2} + for (int i = this.m_curSizeRollBackups; i >= 1; i--) + { + this.RollFile((this.CombinePath(baseFileName, "." + i)), (this.CombinePath(baseFileName, "." + (i + 1)))); + } + + this.m_curSizeRollBackups++; + + // Rename fileName to fileName.1 + this.RollFile(baseFileName, this.CombinePath(baseFileName, ".1")); + } + else + { + // countDirection >= 0 + if (this.m_curSizeRollBackups >= this.m_maxSizeRollBackups && this.m_maxSizeRollBackups > 0) + { + // delete the first and keep counting up. + int oldestFileIndex = this.m_curSizeRollBackups - this.m_maxSizeRollBackups; + + // If static then there is 1 file without a number, therefore 1 less archive + if (this.m_staticLogFileName) + { + oldestFileIndex++; + } + + // If using a static log file then the base for the numbered sequence is the baseFileName passed in + // If not using a static log file then the baseFileName will already have a numbered postfix which + // we must remove, however it may have a date postfix which we must keep! + string archiveFileBaseName = baseFileName; + if (!this.m_staticLogFileName) + { + if (this.m_preserveLogFileNameExtension) + { + string extension = Path.GetExtension(archiveFileBaseName); + string baseName = Path.GetFileNameWithoutExtension(archiveFileBaseName); + int lastDotIndex = baseName.LastIndexOf("."); + if (lastDotIndex >= 0) + { + archiveFileBaseName = baseName.Substring(0, lastDotIndex) + extension; + } + } + else + { + int lastDotIndex = archiveFileBaseName.LastIndexOf("."); + if (lastDotIndex >= 0) + { + archiveFileBaseName = archiveFileBaseName.Substring(0, lastDotIndex); + } + } + } + + // Delete the archive file + this.DeleteFile(this.CombinePath(archiveFileBaseName, "." + oldestFileIndex)); + } + + if (this.m_staticLogFileName) + { + this.m_curSizeRollBackups++; + this.RollFile(baseFileName, this.CombinePath(baseFileName, "." + this.m_curSizeRollBackups)); + } + } + } + } + + /// + /// Get the start time of the next window for the current rollpoint + /// + /// the current date + /// the type of roll point we are working with + /// the start time for the next roll point an interval after the currentDateTime date + /// + /// + /// Returns the date of the next roll point after the currentDateTime date passed to the method. + /// + /// + /// The basic strategy is to subtract the time parts that are less significant + /// than the rollpoint from the current time. This should roll the time back to + /// the start of the time window for the current rollpoint. Then we add 1 window + /// worth of time and get the start time of the next window for the rollpoint. + /// + /// + protected DateTime NextCheckDate(DateTime currentDateTime, RollPoint rollPoint) + { + // Local variable to work on (this does not look very efficient) + DateTime current = currentDateTime; + + // Do slightly different things depending on what the type of roll point we want. + switch(rollPoint) + { + case RollPoint.TopOfMinute: + current = current.AddMilliseconds(-current.Millisecond); + current = current.AddSeconds(-current.Second); + current = current.AddMinutes(1); + break; + + case RollPoint.TopOfHour: + current = current.AddMilliseconds(-current.Millisecond); + current = current.AddSeconds(-current.Second); + current = current.AddMinutes(-current.Minute); + current = current.AddHours(1); + break; + + case RollPoint.HalfDay: + current = current.AddMilliseconds(-current.Millisecond); + current = current.AddSeconds(-current.Second); + current = current.AddMinutes(-current.Minute); + + if (current.Hour < 12) + { + current = current.AddHours(12 - current.Hour); + } + else + { + current = current.AddHours(-current.Hour); + current = current.AddDays(1); + } + break; + + case RollPoint.TopOfDay: + current = current.AddMilliseconds(-current.Millisecond); + current = current.AddSeconds(-current.Second); + current = current.AddMinutes(-current.Minute); + current = current.AddHours(-current.Hour); + current = current.AddDays(1); + break; + + case RollPoint.TopOfWeek: + current = current.AddMilliseconds(-current.Millisecond); + current = current.AddSeconds(-current.Second); + current = current.AddMinutes(-current.Minute); + current = current.AddHours(-current.Hour); + current = current.AddDays(7 - (int)current.DayOfWeek); + break; + + case RollPoint.TopOfMonth: + current = current.AddMilliseconds(-current.Millisecond); + current = current.AddSeconds(-current.Second); + current = current.AddMinutes(-current.Minute); + current = current.AddHours(-current.Hour); + current = current.AddDays(1 - current.Day); /* first day of month is 1 not 0 */ + current = current.AddMonths(1); + break; + } + return current; + } + + /// + /// This object supplies the current date/time. Allows test code to plug in + /// a method to control this class when testing date/time based rolling. The default + /// implementation uses the underlying value of DateTime.Now. + /// + private IDateTime m_dateTime = null; + + /// + /// The date pattern. By default, the pattern is set to ".yyyy-MM-dd" + /// meaning daily rollover. + /// + private string m_datePattern = ".yyyy-MM-dd"; + + /// + /// The actual formatted filename that is currently being written to + /// or will be the file transferred to on roll over + /// (based on staticLogFileName). + /// + private string m_scheduledFilename = null; + + /// + /// The timestamp when we shall next recompute the filename. + /// + private DateTime m_nextCheck = DateTime.MaxValue; + + /// + /// Holds date of last roll over + /// + private DateTime m_now; + + /// + /// The type of rolling done + /// + private RollPoint m_rollPoint; + + /// + /// The default maximum file size is 10MB + /// + private long m_maxFileSize = 10*1024*1024; + + /// + /// There is zero backup files by default + /// + private int m_maxSizeRollBackups = 0; + + /// + /// How many sized based backups have been made so far + /// + private int m_curSizeRollBackups = 0; + + /// + /// The rolling file count direction. + /// + private int m_countDirection = -1; + + /// + /// The rolling mode used in this appender. + /// + private RollingMode m_rollingStyle = RollingMode.Composite; + + /// + /// Cache flag set if we are rolling by date. + /// + private bool m_rollDate = true; + + /// + /// Cache flag set if we are rolling by size. + /// + private bool m_rollSize = true; + + /// + /// Value indicating whether to always log to the same file. + /// + private bool m_staticLogFileName = true; + + /// + /// Value indicating whether to preserve the file name extension when rolling. + /// + private bool m_preserveLogFileNameExtension = false; + + + /// + /// FileName provided in configuration. Used for rolling properly + /// + private string m_baseFileName; + +#if !NETCF + /// + /// A mutex that is used to lock rolling of files. + /// private Mutex m_mutexForRolling; -#endif +#endif - /// - /// The 1st of January 1970 in UTC. - /// + /// + /// The 1st of January 1970 in UTC + /// private static readonly DateTime s_date1970 = new DateTime(1970, 1, 1); - /// - /// This interface is used to supply Date/Time information to the . - /// - /// - /// This interface is used to supply Date/Time information to the . - /// Used primarily to allow test classes to plug themselves in so they can - /// supply test date/times. - /// - public interface IDateTime - { - /// - /// Gets the current time. - /// - /// The current time. - /// - /// - /// Gets the current time. - /// - /// - DateTime Now { get; } - } - - /// - /// Default implementation of that returns the current time. - /// - private class LocalDateTime : IDateTime - { - /// - /// Gets the current time. - /// - /// The current time. - /// - /// - /// Gets the current time. - /// - /// - public DateTime Now - { - get { return DateTime.Now; } - } - } - -#if !NET_1_0 && !CLI_1_0 && !NETCF - /// - /// Implementation of that returns the current time as the coordinated universal time (UTC). - /// - private class UniversalDateTime : IDateTime - { - /// - /// Gets the current time. - /// - /// The current time. - /// - /// - /// Gets the current time. - /// - /// - public DateTime Now - { - get { return DateTime.UtcNow; } - } + /// + /// This interface is used to supply Date/Time information to the . + /// + /// + /// This interface is used to supply Date/Time information to the . + /// Used primarily to allow test classes to plug themselves in so they can + /// supply test date/times. + /// + public interface IDateTime + { + /// + /// Gets the current time. + /// + /// The current time. + /// + /// + /// Gets the current time. + /// + /// + DateTime Now { get; } } -#endif - } -} + /// + /// Default implementation of that returns the current time. + /// + private class LocalDateTime : IDateTime + { + /// + /// Gets the current time. + /// + /// The current time. + /// + /// + /// Gets the current time. + /// + /// + public DateTime Now + { + get { return DateTime.Now; } + } + } + +#if !NET_1_0 && !CLI_1_0 && !NETCF + /// + /// Implementation of that returns the current time as the coordinated universal time (UTC). + /// + private class UniversalDateTime : IDateTime + { + /// + /// Gets the current time. + /// + /// The current time. + /// + /// + /// Gets the current time. + /// + /// + public DateTime Now + { + get { return DateTime.UtcNow; } + } + } +#endif + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/SmtpAppender.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/SmtpAppender.cs index 724d7d4c3c5..71be1573233 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/SmtpAppender.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/SmtpAppender.cs @@ -1,646 +1,650 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -// .NET Compact Framework 1.0 has no support for System.Web.Mail -// SSCLI 1.0 has no support for System.Web.Mail -#if !NETCF && !SSCLI - -using System; -using System.IO; -using System.Text; - -#if NET_2_0 || MONO_2_0 -using System.Net.Mail; - -#else -using System.Web.Mail; -#endif - -using log4net.Core; -using log4net.Layout; -using log4net.Util; - -namespace log4net.Appender -{ - /// - /// Send an e-mail when a specific logging event occurs, typically on errors - /// or fatal errors. - /// - /// - /// - /// The number of logging events delivered in this e-mail depend on - /// the value of option. The - /// keeps only the last - /// logging events in its - /// cyclic buffer. This keeps memory requirements at a reasonable level while - /// still delivering useful application context. - /// - /// - /// Authentication and setting the server Port are only available on the MS .NET 1.1 runtime. - /// For these features to be enabled you need to ensure that you are using a version of - /// the log4net assembly that is built against the MS .NET 1.1 framework and that you are - /// running the your application on the MS .NET 1.1 runtime. On all other platforms only sending - /// unauthenticated messages to a server listening on port 25 (the default) is supported. - /// - /// - /// Authentication is supported by setting the property to - /// either or . - /// If using authentication then the - /// and properties must also be set. - /// - /// - /// To set the SMTP server port use the property. The default port is 25. - /// - /// - /// Nicko Cadell. - /// Gert Driesen. - public class SmtpAppender : BufferingAppenderSkeleton +#if NET_2_0 || NETSTANDARD2_0 +// SSCLI 1.0 has no support for System.Web.Mail +#if !NETCF && !SSCLI + +using System; +using System.IO; +using System.Text; + +#if NET_2_0 || MONO_2_0 || NETSTANDARD2_0 +using System.Net.Mail; +#else +using System.Web.Mail; +#endif + +using log4net.Core; + +namespace log4net.Appender +{ + /// + /// Send an e-mail when a specific logging event occurs, typically on errors + /// or fatal errors. + /// + /// + /// + /// The number of logging events delivered in this e-mail depend on + /// the value of option. The + /// keeps only the last + /// logging events in its + /// cyclic buffer. This keeps memory requirements at a reasonable level while + /// still delivering useful application context. + /// + /// + /// Authentication and setting the server Port are only available on the MS .NET 1.1 runtime. + /// For these features to be enabled you need to ensure that you are using a version of + /// the log4net assembly that is built against the MS .NET 1.1 framework and that you are + /// running the your application on the MS .NET 1.1 runtime. On all other platforms only sending + /// unauthenticated messages to a server listening on port 25 (the default) is supported. + /// + /// + /// Authentication is supported by setting the property to + /// either or . + /// If using authentication then the + /// and properties must also be set. + /// + /// + /// To set the SMTP server port use the property. The default port is 25. + /// + /// + /// Nicko Cadell + /// Gert Driesen + public class SmtpAppender : BufferingAppenderSkeleton { /// - /// Initializes a new instance of the class. - /// Default constructor. - /// - /// - /// - /// Default constructor. - /// - /// - public SmtpAppender() - { + /// Default constructor + /// + /// + /// + /// Default constructor + /// + /// + public SmtpAppender() + { } - /// - /// Gets or sets a comma- or semicolon-delimited list of recipient e-mail addresses (use semicolon on .NET 1.1 and comma for later versions). - /// - /// - /// - /// For .NET 1.1 (System.Web.Mail): A semicolon-delimited list of e-mail addresses. - /// - /// - /// For .NET 2.0 (System.Net.Mail): A comma-delimited list of e-mail addresses. - /// - /// - /// - /// - /// For .NET 1.1 (System.Web.Mail): A semicolon-delimited list of e-mail addresses. - /// - /// - /// For .NET 2.0 (System.Net.Mail): A comma-delimited list of e-mail addresses. - /// - /// - public string To - { - get { return this.m_to; } - set { this.m_to = MaybeTrimSeparators(value); } - } - - /// - /// Gets or sets a comma- or semicolon-delimited list of recipient e-mail addresses - /// that will be carbon copied (use semicolon on .NET 1.1 and comma for later versions). - /// - /// - /// - /// For .NET 1.1 (System.Web.Mail): A semicolon-delimited list of e-mail addresses. - /// - /// - /// For .NET 2.0 (System.Net.Mail): A comma-delimited list of e-mail addresses. - /// - /// - /// - /// - /// For .NET 1.1 (System.Web.Mail): A semicolon-delimited list of e-mail addresses. - /// - /// - /// For .NET 2.0 (System.Net.Mail): A comma-delimited list of e-mail addresses. - /// - /// - public string Cc - { - get { return this.m_cc; } - set { this.m_cc = MaybeTrimSeparators(value); } - } - - /// - /// Gets or sets a semicolon-delimited list of recipient e-mail addresses - /// that will be blind carbon copied. - /// - /// - /// A semicolon-delimited list of e-mail addresses. - /// - /// - /// - /// A semicolon-delimited list of recipient e-mail addresses. - /// - /// - public string Bcc - { - get { return this.m_bcc; } - set { this.m_bcc = MaybeTrimSeparators(value); } - } - - /// - /// Gets or sets the e-mail address of the sender. - /// - /// - /// The e-mail address of the sender. - /// - /// - /// - /// The e-mail address of the sender. - /// - /// - public string From - { - get { return this.m_from; } - set { this.m_from = value; } - } - - /// - /// Gets or sets the subject line of the e-mail message. - /// - /// - /// The subject line of the e-mail message. - /// - /// - /// - /// The subject line of the e-mail message. - /// - /// - public string Subject - { - get { return this.m_subject; } - set { this.m_subject = value; } - } - - /// - /// Gets or sets the name of the SMTP relay mail server to use to send - /// the e-mail messages. - /// - /// - /// The name of the e-mail relay server. If SmtpServer is not set, the - /// name of the local SMTP server is used. - /// - /// - /// - /// The name of the e-mail relay server. If SmtpServer is not set, the - /// name of the local SMTP server is used. - /// - /// - public string SmtpHost - { - get { return this.m_smtpHost; } - set { this.m_smtpHost = value; } - } - - /// - /// Gets or sets a value indicating whether obsolete. - /// - /// - /// Use the BufferingAppenderSkeleton Fix methods instead. - /// - /// - /// - /// Obsolete property. - /// - /// - [Obsolete("Use the BufferingAppenderSkeleton Fix methods. Scheduled removal in v10.0.0.")] - public bool LocationInfo - { - get { return false; } - set { } - } - - /// - /// Gets or sets the mode to use to authentication with the SMTP server. - /// - /// - /// Authentication is only available on the MS .NET 1.1 runtime. - /// - /// Valid Authentication mode values are: , - /// , and . - /// The default value is . When using - /// you must specify the - /// and to use to authenticate. - /// When using the Windows credentials for the current - /// thread, if impersonating, or the process will be used to authenticate. - /// - /// - public SmtpAuthentication Authentication - { - get { return this.m_authentication; } - set { this.m_authentication = value; } - } - - /// - /// Gets or sets the username to use to authenticate with the SMTP server. - /// - /// - /// Authentication is only available on the MS .NET 1.1 runtime. - /// - /// A and must be specified when - /// is set to , - /// otherwise the username will be ignored. - /// - /// - public string Username - { - get { return this.m_username; } - set { this.m_username = value; } - } - - /// - /// Gets or sets the password to use to authenticate with the SMTP server. - /// - /// - /// Authentication is only available on the MS .NET 1.1 runtime. - /// - /// A and must be specified when - /// is set to , - /// otherwise the password will be ignored. - /// - /// - public string Password - { - get { return this.m_password; } - set { this.m_password = value; } - } - - /// - /// Gets or sets the port on which the SMTP server is listening. - /// - /// - /// Server Port is only available on the MS .NET 1.1 runtime. - /// - /// The port on which the SMTP server is listening. The default - /// port is 25. The Port can only be changed when running on - /// the MS .NET 1.1 runtime. - /// - /// - public int Port - { - get { return this.m_port; } - set { this.m_port = value; } - } - - /// - /// Gets or sets the priority of the e-mail message. - /// - /// - /// One of the values. - /// - /// - /// - /// Sets the priority of the e-mails generated by this - /// appender. The default priority is . - /// - /// - /// If you are using this appender to report errors then - /// you may want to set the priority to . - /// - /// - public MailPriority Priority - { - get { return this.m_mailPriority; } - set { this.m_mailPriority = value; } - } - -#if NET_2_0 || MONO_2_0 - /// - /// Gets or sets a value indicating whether enable or disable use of SSL when sending e-mail message. - /// - /// - /// This is available on MS .NET 2.0 runtime and higher. - /// - public bool EnableSsl - { - get { return this.m_enableSsl; } - set { this.m_enableSsl = value; } - } - - /// - /// Gets or sets the reply-to e-mail address. - /// - /// - /// This is available on MS .NET 2.0 runtime and higher. - /// - public string ReplyTo - { - get { return this.m_replyTo; } - set { this.m_replyTo = value; } - } -#endif - - /// - /// Gets or sets the subject encoding to be used. - /// - /// - /// The default encoding is the operating system's current ANSI codepage. - /// - public Encoding SubjectEncoding - { - get { return this.m_subjectEncoding; } - set { this.m_subjectEncoding = value; } - } - - /// - /// Gets or sets the body encoding to be used. - /// - /// - /// The default encoding is the operating system's current ANSI codepage. - /// - public Encoding BodyEncoding - { - get { return this.m_bodyEncoding; } - set { this.m_bodyEncoding = value; } + /// + /// Gets or sets a comma- or semicolon-delimited list of recipient e-mail addresses (use semicolon on .NET 1.1 and comma for later versions). + /// + /// + /// + /// For .NET 1.1 (System.Web.Mail): A semicolon-delimited list of e-mail addresses. + /// + /// + /// For .NET 2.0 (System.Net.Mail): A comma-delimited list of e-mail addresses. + /// + /// + /// + /// + /// For .NET 1.1 (System.Web.Mail): A semicolon-delimited list of e-mail addresses. + /// + /// + /// For .NET 2.0 (System.Net.Mail): A comma-delimited list of e-mail addresses. + /// + /// + public string To + { + get { return this.m_to; } + set { this.m_to = MaybeTrimSeparators(value); } } - /// - /// Sends the contents of the cyclic buffer as an e-mail message. - /// - /// The logging events to send. - protected override void SendBuffer(LoggingEvent[] events) - { - // Note: this code already owns the monitor for this - // appender. This frees us from needing to synchronize again. - try - { - StringWriter writer = new StringWriter(System.Globalization.CultureInfo.InvariantCulture); - - string t = this.Layout.Header; - if (t != null) - { - writer.Write(t); - } - - for (int i = 0; i < events.Length; i++) - { - // Render the event and append the text to the buffer - this.RenderLoggingEvent(writer, events[i]); - } - - t = this.Layout.Footer; - if (t != null) - { - writer.Write(t); - } - - this.SendEmail(writer.ToString()); - } - catch (Exception e) - { - this.ErrorHandler.Error("Error occurred while sending e-mail notification.", e); - } + /// + /// Gets or sets a comma- or semicolon-delimited list of recipient e-mail addresses + /// that will be carbon copied (use semicolon on .NET 1.1 and comma for later versions). + /// + /// + /// + /// For .NET 1.1 (System.Web.Mail): A semicolon-delimited list of e-mail addresses. + /// + /// + /// For .NET 2.0 (System.Net.Mail): A comma-delimited list of e-mail addresses. + /// + /// + /// + /// + /// For .NET 1.1 (System.Web.Mail): A semicolon-delimited list of e-mail addresses. + /// + /// + /// For .NET 2.0 (System.Net.Mail): A comma-delimited list of e-mail addresses. + /// + /// + public string Cc + { + get { return this.m_cc; } + set { this.m_cc = MaybeTrimSeparators(value); } } - /// - /// Gets a value indicating whether this appender requires a to be set. - /// - /// true. - /// - /// - /// This appender requires a to be set. - /// - /// - protected override bool RequiresLayout - { - get { return true; } + /// + /// Gets or sets a semicolon-delimited list of recipient e-mail addresses + /// that will be blind carbon copied. + /// + /// + /// A semicolon-delimited list of e-mail addresses. + /// + /// + /// + /// A semicolon-delimited list of recipient e-mail addresses. + /// + /// + public string Bcc + { + get { return this.m_bcc; } + set { this.m_bcc = MaybeTrimSeparators(value); } } - /// - /// Send the email message. - /// - /// the body text to include in the mail. - protected virtual void SendEmail(string messageBody) - { -#if NET_2_0 || MONO_2_0 - // .NET 2.0 has a new API for SMTP email System.Net.Mail - // This API supports credentials and multiple hosts correctly. - // The old API is deprecated. - - // Create and configure the smtp client - SmtpClient smtpClient = new SmtpClient(); - if (!string.IsNullOrEmpty(this.m_smtpHost)) - { - smtpClient.Host = this.m_smtpHost; - } - - smtpClient.Port = this.m_port; - smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network; - smtpClient.EnableSsl = this.m_enableSsl; - - if (this.m_authentication == SmtpAuthentication.Basic) - { - // Perform basic authentication - smtpClient.Credentials = new System.Net.NetworkCredential(this.m_username, this.m_password); - } - else if (this.m_authentication == SmtpAuthentication.Ntlm) - { - // Perform integrated authentication (NTLM) - smtpClient.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials; - } - - using (MailMessage mailMessage = new MailMessage()) - { - mailMessage.Body = messageBody; - mailMessage.BodyEncoding = this.m_bodyEncoding; - mailMessage.From = new MailAddress(this.m_from); - mailMessage.To.Add(this.m_to); - if (!string.IsNullOrEmpty(this.m_cc)) - { - mailMessage.CC.Add(this.m_cc); - } - - if (!string.IsNullOrEmpty(this.m_bcc)) - { - mailMessage.Bcc.Add(this.m_bcc); - } - - if (!string.IsNullOrEmpty(this.m_replyTo)) - { - // .NET 4.0 warning CS0618: 'System.Net.Mail.MailMessage.ReplyTo' is obsolete: - // 'ReplyTo is obsoleted for this type. Please use ReplyToList instead which can accept multiple addresses. http://go.microsoft.com/fwlink/?linkid=14202' -#if !NET_4_0 && !MONO_4_0 - mailMessage.ReplyTo = new MailAddress(m_replyTo); -#else - mailMessage.ReplyToList.Add(new MailAddress(this.m_replyTo)); -#endif - } - - mailMessage.Subject = this.m_subject; - mailMessage.SubjectEncoding = this.m_subjectEncoding; - mailMessage.Priority = this.m_mailPriority; - - // TODO: Consider using SendAsync to send the message without blocking. This would be a change in - // behaviour compared to .NET 1.x. We would need a SendCompletedCallback to log errors. - smtpClient.Send(mailMessage); - } -#else - // .NET 1.x uses the System.Web.Mail API for sending Mail - - MailMessage mailMessage = new MailMessage(); - mailMessage.Body = messageBody; - mailMessage.BodyEncoding = m_bodyEncoding; - mailMessage.From = m_from; - mailMessage.To = m_to; - if (m_cc != null && m_cc.Length > 0) - { - mailMessage.Cc = m_cc; - } - if (m_bcc != null && m_bcc.Length > 0) - { - mailMessage.Bcc = m_bcc; - } - mailMessage.Subject = m_subject; -#if !MONO && !NET_1_0 && !NET_1_1 && !CLI_1_0 - mailMessage.SubjectEncoding = m_subjectEncoding; -#endif - mailMessage.Priority = m_mailPriority; - -#if NET_1_1 - // The Fields property on the MailMessage allows the CDO properties to be set directly. - // This property is only available on .NET Framework 1.1 and the implementation must understand - // the CDO properties. For details of the fields available in CDO see: - // - // http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cdosys/html/_cdosys_configuration_coclass.asp - // - - try - { - if (m_authentication == SmtpAuthentication.Basic) - { - // Perform basic authentication - mailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", 1); - mailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername", m_username); - mailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword", m_password); - } - else if (m_authentication == SmtpAuthentication.Ntlm) - { - // Perform integrated authentication (NTLM) - mailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", 2); - } - - // Set the port if not the default value - if (m_port != 25) - { - mailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpserverport", m_port); - } - } - catch(MissingMethodException missingMethodException) - { - // If we were compiled against .NET 1.1 but are running against .NET 1.0 then - // we will get a MissingMethodException when accessing the MailMessage.Fields property. - - ErrorHandler.Error("SmtpAppender: Authentication and server Port are only supported when running on the MS .NET 1.1 framework", missingMethodException); - } -#else - if (m_authentication != SmtpAuthentication.None) - { - ErrorHandler.Error("SmtpAppender: Authentication is only supported on the MS .NET 1.1 or MS .NET 2.0 builds of log4net"); - } - - if (m_port != 25) - { - ErrorHandler.Error("SmtpAppender: Server Port is only supported on the MS .NET 1.1 or MS .NET 2.0 builds of log4net"); - } -#endif // if NET_1_1 - - if (m_smtpHost != null && m_smtpHost.Length > 0) - { - SmtpMail.SmtpServer = m_smtpHost; - } - - SmtpMail.Send(mailMessage); -#endif // if NET_2_0 + /// + /// Gets or sets the e-mail address of the sender. + /// + /// + /// The e-mail address of the sender. + /// + /// + /// + /// The e-mail address of the sender. + /// + /// + public string From + { + get { return this.m_from; } + set { this.m_from = value; } } - private string m_to; - private string m_cc; - private string m_bcc; - private string m_from; - private string m_subject; - private string m_smtpHost; - private Encoding m_subjectEncoding = Encoding.UTF8; - private Encoding m_bodyEncoding = Encoding.UTF8; - - // authentication fields - private SmtpAuthentication m_authentication = SmtpAuthentication.None; - private string m_username; - private string m_password; - - // server port, default port 25 - private int m_port = 25; - - private MailPriority m_mailPriority = MailPriority.Normal; - -#if NET_2_0 || MONO_2_0 - private bool m_enableSsl = false; - private string m_replyTo; -#endif - - /// - /// Values for the property. - /// - /// - /// - /// SMTP authentication modes. - /// - /// - public enum SmtpAuthentication - { - /// - /// No authentication - /// - None, - - /// - /// Basic authentication. - /// - /// - /// Requires a username and password to be supplied - /// - Basic, - - /// - /// Integrated authentication - /// - /// - /// Uses the Windows credentials from the current thread or process to authenticate. - /// - Ntlm, + /// + /// Gets or sets the subject line of the e-mail message. + /// + /// + /// The subject line of the e-mail message. + /// + /// + /// + /// The subject line of the e-mail message. + /// + /// + public string Subject + { + get { return this.m_subject; } + set { this.m_subject = value; } + } + + /// + /// Gets or sets the name of the SMTP relay mail server to use to send + /// the e-mail messages. + /// + /// + /// The name of the e-mail relay server. If SmtpServer is not set, the + /// name of the local SMTP server is used. + /// + /// + /// + /// The name of the e-mail relay server. If SmtpServer is not set, the + /// name of the local SMTP server is used. + /// + /// + public string SmtpHost + { + get { return this.m_smtpHost; } + set { this.m_smtpHost = value; } } - private static readonly char[] ADDRESS_DELIMITERS = new char[] { ',', ';' }; + /// + /// Obsolete + /// + /// + /// Use the BufferingAppenderSkeleton Fix methods instead + /// + /// + /// + /// Obsolete property. + /// + /// + [Obsolete("Use the BufferingAppenderSkeleton Fix methods")] + public bool LocationInfo + { + get { return false; } + set { ; } + } + + /// + /// The mode to use to authentication with the SMTP server + /// + /// + /// Authentication is only available on the MS .NET 1.1 runtime. + /// + /// Valid Authentication mode values are: , + /// , and . + /// The default value is . When using + /// you must specify the + /// and to use to authenticate. + /// When using the Windows credentials for the current + /// thread, if impersonating, or the process will be used to authenticate. + /// + /// + public SmtpAuthentication Authentication + { + get { return this.m_authentication; } + set { this.m_authentication = value; } + } + + /// + /// The username to use to authenticate with the SMTP server + /// + /// + /// Authentication is only available on the MS .NET 1.1 runtime. + /// + /// A and must be specified when + /// is set to , + /// otherwise the username will be ignored. + /// + /// + public string Username + { + get { return this.m_username; } + set { this.m_username = value; } + } + + /// + /// The password to use to authenticate with the SMTP server + /// + /// + /// Authentication is only available on the MS .NET 1.1 runtime. + /// + /// A and must be specified when + /// is set to , + /// otherwise the password will be ignored. + /// + /// + public string Password + { + get { return this.m_password; } + set { this.m_password = value; } + } + + /// + /// The port on which the SMTP server is listening + /// + /// + /// Server Port is only available on the MS .NET 1.1 runtime. + /// + /// The port on which the SMTP server is listening. The default + /// port is 25. The Port can only be changed when running on + /// the MS .NET 1.1 runtime. + /// + /// + public int Port + { + get { return this.m_port; } + set { this.m_port = value; } + } + + /// + /// Gets or sets the priority of the e-mail message + /// + /// + /// One of the values. + /// + /// + /// + /// Sets the priority of the e-mails generated by this + /// appender. The default priority is . + /// + /// + /// If you are using this appender to report errors then + /// you may want to set the priority to . + /// + /// + public MailPriority Priority + { + get { return this.m_mailPriority; } + set { this.m_mailPriority = value; } + } + +#if NET_2_0 || MONO_2_0 || NETSTANDARD2_0 + /// + /// Enable or disable use of SSL when sending e-mail message + /// + /// + /// This is available on MS .NET 2.0 runtime and higher + /// + public bool EnableSsl + { + get { return this.m_enableSsl; } + set { this.m_enableSsl = value; } + } + + /// + /// Gets or sets the reply-to e-mail address. + /// + /// + /// This is available on MS .NET 2.0 runtime and higher + /// + public string ReplyTo + { + get { return this.m_replyTo; } + set { this.m_replyTo = value; } + } +#endif + + /// + /// Gets or sets the subject encoding to be used. + /// + /// + /// The default encoding is the operating system's current ANSI codepage. + /// + public Encoding SubjectEncoding + { + get { return this.m_subjectEncoding; } + set { this.m_subjectEncoding = value; } + } + + /// + /// Gets or sets the body encoding to be used. + /// + /// + /// The default encoding is the operating system's current ANSI codepage. + /// + public Encoding BodyEncoding + { + get { return this.m_bodyEncoding; } + set { this.m_bodyEncoding = value; } + } + + /// + /// Sends the contents of the cyclic buffer as an e-mail message. + /// + /// The logging events to send. + protected override void SendBuffer(LoggingEvent[] events) + { + // Note: this code already owns the monitor for this + // appender. This frees us from needing to synchronize again. + try + { + using (var writer = new StringWriter(System.Globalization.CultureInfo.InvariantCulture)) + { + string t = this.Layout.Header; + if (t != null) + { + writer.Write(t); + } + + for (int i = 0; i < events.Length; i++) + { + // Render the event and append the text to the buffer + this.RenderLoggingEvent(writer, events[i]); + } + + t = this.Layout.Footer; + if (t != null) + { + writer.Write(t); + } + + this.SendEmail(writer.ToString()); + } + } + catch(Exception e) + { + this.ErrorHandler.Error("Error occurred while sending e-mail notification.", e); + } + } - /// - /// trims leading and trailing commas or semicolons. - /// - private static string MaybeTrimSeparators(string s) + /// + /// This appender requires a to be set. + /// + /// true + /// + /// + /// This appender requires a to be set. + /// + /// + protected override bool RequiresLayout { -#if NET_2_0 || MONO_2_0 - return string.IsNullOrEmpty(s) ? s : s.Trim(ADDRESS_DELIMITERS); -#else - return s != null && s.Length > 0 ? s : s.Trim(ADDRESS_DELIMITERS); -#endif + get { return true; } } - } -} - -#endif // !NETCF && !SSCLI + + /// + /// Send the email message + /// + /// the body text to include in the mail + protected virtual void SendEmail(string messageBody) + { +#if NET_2_0 || MONO_2_0 || NETSTANDARD2_0 + // .NET 2.0 has a new API for SMTP email System.Net.Mail + // This API supports credentials and multiple hosts correctly. + // The old API is deprecated. + + // Create and configure the smtp client +#if NET_4_0 || MONO_4_0 || NETSTANDARD2_0 + using (var smtpClient = new SmtpClient()) + { +#else + SmtpClient smtpClient = new SmtpClient(); +#endif + if (!String.IsNullOrEmpty(this.m_smtpHost)) + { + smtpClient.Host = this.m_smtpHost; + } + + smtpClient.Port = this.m_port; + smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network; + smtpClient.EnableSsl = this.m_enableSsl; + + if (this.m_authentication == SmtpAuthentication.Basic) + { + // Perform basic authentication + smtpClient.Credentials = new System.Net.NetworkCredential(this.m_username, this.m_password); + } + else if (this.m_authentication == SmtpAuthentication.Ntlm) + { + // Perform integrated authentication (NTLM) + smtpClient.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials; + } + + using (MailMessage mailMessage = new MailMessage()) + { + mailMessage.Body = messageBody; + mailMessage.BodyEncoding = this.m_bodyEncoding; + mailMessage.From = new MailAddress(this.m_from); + mailMessage.To.Add(this.m_to); + if (!String.IsNullOrEmpty(this.m_cc)) + { + mailMessage.CC.Add(this.m_cc); + } + + if (!String.IsNullOrEmpty(this.m_bcc)) + { + mailMessage.Bcc.Add(this.m_bcc); + } + + if (!String.IsNullOrEmpty(this.m_replyTo)) + { + // .NET 4.0 warning CS0618: 'System.Net.Mail.MailMessage.ReplyTo' is obsolete: + // 'ReplyTo is obsoleted for this type. Please use ReplyToList instead which can accept multiple addresses. http://go.microsoft.com/fwlink/?linkid=14202' +#if !NET_4_0 && !MONO_4_0 && !NETSTANDARD2_0 + mailMessage.ReplyTo = new MailAddress(m_replyTo); +#else + mailMessage.ReplyToList.Add(new MailAddress(this.m_replyTo)); +#endif + } + + mailMessage.Subject = this.m_subject; + mailMessage.SubjectEncoding = this.m_subjectEncoding; + mailMessage.Priority = this.m_mailPriority; + + // TODO: Consider using SendAsync to send the message without blocking. This would be a change in + // behaviour compared to .NET 1.x. We would need a SendCompletedCallback to log errors. + smtpClient.Send(mailMessage); + } +#else + // .NET 1.x uses the System.Web.Mail API for sending Mail + + MailMessage mailMessage = new MailMessage(); + mailMessage.Body = messageBody; + mailMessage.BodyEncoding = m_bodyEncoding; + mailMessage.From = m_from; + mailMessage.To = m_to; + if (m_cc != null && m_cc.Length > 0) + { + mailMessage.Cc = m_cc; + } + if (m_bcc != null && m_bcc.Length > 0) + { + mailMessage.Bcc = m_bcc; + } + mailMessage.Subject = m_subject; +#if !MONO && !NET_1_0 && !NET_1_1 && !CLI_1_0 + mailMessage.SubjectEncoding = m_subjectEncoding; +#endif + mailMessage.Priority = m_mailPriority; + +#if NET_1_1 + // The Fields property on the MailMessage allows the CDO properties to be set directly. + // This property is only available on .NET Framework 1.1 and the implementation must understand + // the CDO properties. For details of the fields available in CDO see: + // + // http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cdosys/html/_cdosys_configuration_coclass.asp + // + + try + { + if (m_authentication == SmtpAuthentication.Basic) + { + // Perform basic authentication + mailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", 1); + mailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername", m_username); + mailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword", m_password); + } + else if (m_authentication == SmtpAuthentication.Ntlm) + { + // Perform integrated authentication (NTLM) + mailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", 2); + } + + // Set the port if not the default value + if (m_port != 25) + { + mailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpserverport", m_port); + } + } + catch(MissingMethodException missingMethodException) + { + // If we were compiled against .NET 1.1 but are running against .NET 1.0 then + // we will get a MissingMethodException when accessing the MailMessage.Fields property. + + ErrorHandler.Error("SmtpAppender: Authentication and server Port are only supported when running on the MS .NET 1.1 framework", missingMethodException); + } +#else + if (m_authentication != SmtpAuthentication.None) + { + ErrorHandler.Error("SmtpAppender: Authentication is only supported on the MS .NET 1.1 or MS .NET 2.0 builds of log4net"); + } + + if (m_port != 25) + { + ErrorHandler.Error("SmtpAppender: Server Port is only supported on the MS .NET 1.1 or MS .NET 2.0 builds of log4net"); + } +#endif // if NET_1_1 + + if (m_smtpHost != null && m_smtpHost.Length > 0) + { + SmtpMail.SmtpServer = m_smtpHost; + } + + SmtpMail.Send(mailMessage); +#endif // if NET_2_0 +#if NET_4_0 || MONO_4_0 || NETSTANDARD2_0 + } +#endif + } + + private string m_to; + private string m_cc; + private string m_bcc; + private string m_from; + private string m_subject; + private string m_smtpHost; + private Encoding m_subjectEncoding = Encoding.UTF8; + private Encoding m_bodyEncoding = Encoding.UTF8; + + // authentication fields + private SmtpAuthentication m_authentication = SmtpAuthentication.None; + private string m_username; + private string m_password; + + // server port, default port 25 + private int m_port = 25; + + private MailPriority m_mailPriority = MailPriority.Normal; + +#if NET_2_0 || MONO_2_0 || NETSTANDARD2_0 + private bool m_enableSsl = false; + private string m_replyTo; +#endif + + /// + /// Values for the property. + /// + /// + /// + /// SMTP authentication modes. + /// + /// + public enum SmtpAuthentication + { + /// + /// No authentication + /// + None, + + /// + /// Basic authentication. + /// + /// + /// Requires a username and password to be supplied + /// + Basic, + + /// + /// Integrated authentication + /// + /// + /// Uses the Windows credentials from the current thread or process to authenticate. + /// + Ntlm + } + + private static readonly char[] ADDRESS_DELIMITERS = new char[] { ',', ';' }; + + /// + /// trims leading and trailing commas or semicolons + /// + private static string MaybeTrimSeparators(string s) { +#if NET_2_0 || MONO_2_0 || NETSTANDARD2_0 + return string.IsNullOrEmpty(s) ? s : s.Trim(ADDRESS_DELIMITERS); +#else + return s != null && s.Length > 0 ? s : s.Trim(ADDRESS_DELIMITERS); +#endif + } + } +} + +#endif // !NETCF && !SSCLI +#endif // NET_2_0 diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/SmtpPickupDirAppender.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/SmtpPickupDirAppender.cs index f6e385141ac..67fe4c3aae8 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/SmtpPickupDirAppender.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/SmtpPickupDirAppender.cs @@ -1,333 +1,328 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.Appender -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; - using System.IO; - using System.Text; +using System; +using System.IO; - using log4net.Core; - using log4net.Layout; - using log4net.Util; +using log4net.Core; +using log4net.Util; - /// - /// Send an email when a specific logging event occurs, typically on errors - /// or fatal errors. Rather than sending via smtp it writes a file into the - /// directory specified by . This allows services such - /// as the IIS SMTP agent to manage sending the messages. - /// - /// - /// - /// The configuration for this appender is identical to that of the SMTPAppender, - /// except that instead of specifying the SMTPAppender.SMTPHost you specify - /// . - /// - /// - /// The number of logging events delivered in this e-mail depend on - /// the value of option. The - /// keeps only the last - /// logging events in its - /// cyclic buffer. This keeps memory requirements at a reasonable level while - /// still delivering useful application context. - /// - /// - /// Niall Daley. - /// Nicko Cadell. - public class SmtpPickupDirAppender : BufferingAppenderSkeleton +namespace log4net.Appender +{ + /// + /// Send an email when a specific logging event occurs, typically on errors + /// or fatal errors. Rather than sending via smtp it writes a file into the + /// directory specified by . This allows services such + /// as the IIS SMTP agent to manage sending the messages. + /// + /// + /// + /// The configuration for this appender is identical to that of the SMTPAppender, + /// except that instead of specifying the SMTPAppender.SMTPHost you specify + /// . + /// + /// + /// The number of logging events delivered in this e-mail depend on + /// the value of option. The + /// keeps only the last + /// logging events in its + /// cyclic buffer. This keeps memory requirements at a reasonable level while + /// still delivering useful application context. + /// + /// + /// Niall Daley + /// Nicko Cadell + public class SmtpPickupDirAppender : BufferingAppenderSkeleton { /// - /// Initializes a new instance of the class. - /// Default constructor. - /// - /// - /// - /// Default constructor. - /// - /// - public SmtpPickupDirAppender() - { - this.m_fileExtension = string.Empty; // Default to empty string, not null + /// Default constructor + /// + /// + /// + /// Default constructor + /// + /// + public SmtpPickupDirAppender() + { + this.m_fileExtension = string.Empty; // Default to empty string, not null } - /// - /// Gets or sets a semicolon-delimited list of recipient e-mail addresses. - /// - /// - /// A semicolon-delimited list of e-mail addresses. - /// - /// - /// - /// A semicolon-delimited list of e-mail addresses. - /// - /// - public string To - { - get { return this.m_to; } - set { this.m_to = value; } - } - - /// - /// Gets or sets the e-mail address of the sender. - /// - /// - /// The e-mail address of the sender. - /// - /// - /// - /// The e-mail address of the sender. - /// - /// - public string From - { - get { return this.m_from; } - set { this.m_from = value; } - } - - /// - /// Gets or sets the subject line of the e-mail message. - /// - /// - /// The subject line of the e-mail message. - /// - /// - /// - /// The subject line of the e-mail message. - /// - /// - public string Subject - { - get { return this.m_subject; } - set { this.m_subject = value; } - } - - /// - /// Gets or sets the path to write the messages to. - /// - /// - /// - /// Gets or sets the path to write the messages to. This should be the same - /// as that used by the agent sending the messages. - /// - /// - public string PickupDir - { - get { return this.m_pickupDir; } - set { this.m_pickupDir = value; } - } - - /// - /// Gets or sets the file extension for the generated files. - /// - /// - /// The file extension for the generated files. - /// - /// - /// - /// The file extension for the generated files. - /// - /// - public string FileExtension - { - get { return this.m_fileExtension; } + /// + /// Gets or sets a semicolon-delimited list of recipient e-mail addresses. + /// + /// + /// A semicolon-delimited list of e-mail addresses. + /// + /// + /// + /// A semicolon-delimited list of e-mail addresses. + /// + /// + public string To + { + get { return this.m_to; } + set { this.m_to = value; } + } + + /// + /// Gets or sets the e-mail address of the sender. + /// + /// + /// The e-mail address of the sender. + /// + /// + /// + /// The e-mail address of the sender. + /// + /// + public string From + { + get { return this.m_from; } + set { this.m_from = value; } + } + + /// + /// Gets or sets the subject line of the e-mail message. + /// + /// + /// The subject line of the e-mail message. + /// + /// + /// + /// The subject line of the e-mail message. + /// + /// + public string Subject + { + get { return this.m_subject; } + set { this.m_subject = value; } + } + + /// + /// Gets or sets the path to write the messages to. + /// + /// + /// + /// Gets or sets the path to write the messages to. This should be the same + /// as that used by the agent sending the messages. + /// + /// + public string PickupDir + { + get { return this.m_pickupDir; } + set { this.m_pickupDir = value; } + } + + /// + /// Gets or sets the file extension for the generated files + /// + /// + /// The file extension for the generated files + /// + /// + /// + /// The file extension for the generated files + /// + /// + public string FileExtension + { + get { return this.m_fileExtension; } + set + { + this.m_fileExtension = value; + if (this.m_fileExtension == null) + { + this.m_fileExtension = string.Empty; + } + // Make sure any non empty extension starts with a dot +#if NET_2_0 || MONO_2_0 || NETSTANDARD + if (!string.IsNullOrEmpty(this.m_fileExtension) && !this.m_fileExtension.StartsWith(".")) +#else + if (m_fileExtension != null && m_fileExtension.Length > 0 && !m_fileExtension.StartsWith(".")) +#endif + { + this.m_fileExtension = "." + this.m_fileExtension; + } + } + } + + /// + /// Gets or sets the used to write to the pickup directory. + /// + /// + /// The used to write to the pickup directory. + /// + /// + /// + /// Unless a specified here for this appender + /// the is queried for the + /// security context to use. The default behavior is to use the security context + /// of the current thread. + /// + /// + public SecurityContext SecurityContext + { + get { return this.m_securityContext; } + set { this.m_securityContext = value; } + } + + /// + /// Sends the contents of the cyclic buffer as an e-mail message. + /// + /// The logging events to send. + /// + /// + /// Sends the contents of the cyclic buffer as an e-mail message. + /// + /// + protected override void SendBuffer(LoggingEvent[] events) + { + // Note: this code already owns the monitor for this + // appender. This frees us from needing to synchronize again. + try + { + string filePath = null; + StreamWriter writer = null; + + // Impersonate to open the file + using(this.SecurityContext.Impersonate(this)) + { + filePath = Path.Combine(this.m_pickupDir, SystemInfo.NewGuid().ToString("N") + this.m_fileExtension); + writer = File.CreateText(filePath); + } + + if (writer == null) + { + this.ErrorHandler.Error("Failed to create output file for writing ["+filePath+"]", null, ErrorCode.FileOpenFailure); + } + else + { + using(writer) + { + writer.WriteLine("To: " + this.m_to); + writer.WriteLine("From: " + this.m_from); + writer.WriteLine("Subject: " + this.m_subject); + writer.WriteLine("Date: " + DateTime.UtcNow.ToString("r")); + writer.WriteLine(string.Empty); + + string t = this.Layout.Header; + if (t != null) + { + writer.Write(t); + } + + for(int i = 0; i < events.Length; i++) + { + // Render the event and append the text to the buffer + this.RenderLoggingEvent(writer, events[i]); + } - set - { - this.m_fileExtension = value; - if (this.m_fileExtension == null) - { - this.m_fileExtension = string.Empty; - } + t = this.Layout.Footer; + if (t != null) + { + writer.Write(t); + } - // Make sure any non empty extension starts with a dot -#if NET_2_0 || MONO_2_0 - if (!string.IsNullOrEmpty(this.m_fileExtension) && !this.m_fileExtension.StartsWith(".")) -#else - if (m_fileExtension != null && m_fileExtension.Length > 0 && !m_fileExtension.StartsWith(".")) -#endif - { - this.m_fileExtension = "." + this.m_fileExtension; - } - } - } - - /// - /// Gets or sets the used to write to the pickup directory. - /// - /// - /// The used to write to the pickup directory. - /// - /// - /// - /// Unless a specified here for this appender - /// the is queried for the - /// security context to use. The default behavior is to use the security context - /// of the current thread. - /// - /// - public SecurityContext SecurityContext - { - get { return this.m_securityContext; } - set { this.m_securityContext = value; } + writer.WriteLine(string.Empty); + writer.WriteLine("."); + } + } + } + catch(Exception e) + { + this.ErrorHandler.Error("Error occurred while sending e-mail notification.", e); + } } - /// - /// Sends the contents of the cyclic buffer as an e-mail message. - /// - /// The logging events to send. - /// - /// - /// Sends the contents of the cyclic buffer as an e-mail message. - /// - /// - protected override void SendBuffer(LoggingEvent[] events) - { - // Note: this code already owns the monitor for this - // appender. This frees us from needing to synchronize again. - try - { - string filePath = null; - StreamWriter writer = null; - - // Impersonate to open the file - using (this.SecurityContext.Impersonate(this)) - { - filePath = Path.Combine(this.m_pickupDir, SystemInfo.NewGuid().ToString("N") + this.m_fileExtension); - writer = File.CreateText(filePath); - } - - if (writer == null) - { - this.ErrorHandler.Error("Failed to create output file for writing [" + filePath + "]", null, ErrorCode.FileOpenFailure); - } - else - { - using (writer) - { - writer.WriteLine("To: " + this.m_to); - writer.WriteLine("From: " + this.m_from); - writer.WriteLine("Subject: " + this.m_subject); - writer.WriteLine("Date: " + DateTime.UtcNow.ToString("r")); - writer.WriteLine(string.Empty); - - string t = this.Layout.Header; - if (t != null) - { - writer.Write(t); - } - - for (int i = 0; i < events.Length; i++) - { - // Render the event and append the text to the buffer - this.RenderLoggingEvent(writer, events[i]); - } - - t = this.Layout.Footer; - if (t != null) - { - writer.Write(t); - } - - writer.WriteLine(string.Empty); - writer.WriteLine("."); - } - } - } - catch (Exception e) - { - this.ErrorHandler.Error("Error occurred while sending e-mail notification.", e); - } + /// + /// Activate the options on this appender. + /// + /// + /// + /// This is part of the delayed object + /// activation scheme. The method must + /// be called on this object after the configuration properties have + /// been set. Until is called this + /// object is in an undefined state and must not be used. + /// + /// + /// If any of the configuration properties are modified then + /// must be called again. + /// + /// + public override void ActivateOptions() + { + base.ActivateOptions(); + + if (this.m_securityContext == null) + { + this.m_securityContext = SecurityContextProvider.DefaultProvider.CreateSecurityContext(this); + } + + using(this.SecurityContext.Impersonate(this)) + { + this.m_pickupDir = ConvertToFullPath(this.m_pickupDir.Trim()); + } } - /// - /// Activate the options on this appender. - /// - /// - /// - /// This is part of the delayed object - /// activation scheme. The method must - /// be called on this object after the configuration properties have - /// been set. Until is called this - /// object is in an undefined state and must not be used. - /// - /// - /// If any of the configuration properties are modified then - /// must be called again. - /// - /// - public override void ActivateOptions() - { - base.ActivateOptions(); - - if (this.m_securityContext == null) - { - this.m_securityContext = SecurityContextProvider.DefaultProvider.CreateSecurityContext(this); - } - - using (this.SecurityContext.Impersonate(this)) - { - this.m_pickupDir = ConvertToFullPath(this.m_pickupDir.Trim()); - } - } - - /// - /// Gets a value indicating whether this appender requires a to be set. - /// - /// true. - /// - /// - /// This appender requires a to be set. - /// - /// - protected override bool RequiresLayout - { - get { return true; } + /// + /// This appender requires a to be set. + /// + /// true + /// + /// + /// This appender requires a to be set. + /// + /// + protected override bool RequiresLayout + { + get { return true; } } - /// - /// Convert a path into a fully qualified path. - /// - /// The path to convert. - /// The fully qualified path. - /// - /// - /// Converts the path specified to a fully - /// qualified path. If the path is relative it is - /// taken as relative from the application base - /// directory. - /// - /// - protected static string ConvertToFullPath(string path) - { - return SystemInfo.ConvertToFullPath(path); + /// + /// Convert a path into a fully qualified path. + /// + /// The path to convert. + /// The fully qualified path. + /// + /// + /// Converts the path specified to a fully + /// qualified path. If the path is relative it is + /// taken as relative from the application base + /// directory. + /// + /// + protected static string ConvertToFullPath(string path) + { + return SystemInfo.ConvertToFullPath(path); } - private string m_to; - private string m_from; - private string m_subject; - private string m_pickupDir; - private string m_fileExtension; - - /// - /// The security context to use for privileged calls. - /// + private string m_to; + private string m_from; + private string m_subject; + private string m_pickupDir; + private string m_fileExtension; + + /// + /// The security context to use for privileged calls + /// private SecurityContext m_securityContext; - } -} + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/TelnetAppender.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/TelnetAppender.cs index 5a857227e88..1aeb9e38301 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/TelnetAppender.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/TelnetAppender.cs @@ -1,525 +1,520 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +using System; +using System.Collections; +using System.Globalization; +using System.Net; +using System.Net.Sockets; +using System.IO; +#if NETSTANDARD +using System.Threading.Tasks; +#endif -#if NETSTANDARD1_3 -using System.Threading.Tasks; -#endif -using log4net.Core; -using log4net.Layout; -using log4net.Util; - -namespace log4net.Appender -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; - using System.Collections; - using System.Globalization; - using System.IO; - using System.Net; - using System.Net.Sockets; - using System.Text; - using System.Threading; - - /// - /// Appender that allows clients to connect via Telnet to receive log messages. - /// - /// - /// - /// The TelnetAppender accepts socket connections and streams logging messages - /// back to the client. - /// The output is provided in a telnet-friendly way so that a log can be monitored - /// over a TCP/IP socket. - /// This allows simple remote monitoring of application logging. - /// - /// - /// The default is 23 (the telnet port). - /// - /// - /// Keith Long. - /// Nicko Cadell. - public class TelnetAppender : AppenderSkeleton - { - private SocketHandler m_handler; +using log4net.Core; +using log4net.Util; + +namespace log4net.Appender +{ + /// + /// Appender that allows clients to connect via Telnet to receive log messages + /// + /// + /// + /// The TelnetAppender accepts socket connections and streams logging messages + /// back to the client. + /// The output is provided in a telnet-friendly way so that a log can be monitored + /// over a TCP/IP socket. + /// This allows simple remote monitoring of application logging. + /// + /// + /// The default is 23 (the telnet port). + /// + /// + /// Keith Long + /// Nicko Cadell + public class TelnetAppender : AppenderSkeleton + { + private SocketHandler m_handler; private int m_listeningPort = 23; /// - /// Initializes a new instance of the class. - /// Default constructor. - /// - /// - /// - /// Default constructor. - /// - /// - public TelnetAppender() - { + /// Default constructor + /// + /// + /// + /// Default constructor + /// + /// + public TelnetAppender() + { } - /// - /// The fully qualified type of the TelnetAppender class. - /// - /// - /// Used by the internal logger to record the Type of the - /// log message. - /// + /// + /// The fully qualified type of the TelnetAppender class. + /// + /// + /// Used by the internal logger to record the Type of the + /// log message. + /// private static readonly Type declaringType = typeof(TelnetAppender); - /// - /// Gets or sets the TCP port number on which this will listen for connections. - /// - /// - /// An integer value in the range to - /// indicating the TCP port number on which this will listen for connections. - /// - /// - /// - /// The default value is 23 (the telnet port). - /// - /// - /// The value specified is less than - /// or greater than . - public int Port - { - get - { - return this.m_listeningPort; - } - - set - { - if (value < IPEndPoint.MinPort || value > IPEndPoint.MaxPort) - { - throw log4net.Util.SystemInfo.CreateArgumentOutOfRangeException("value", (object)value, - "The value specified for Port is less than " + - IPEndPoint.MinPort.ToString(NumberFormatInfo.InvariantInfo) + - " or greater than " + - IPEndPoint.MaxPort.ToString(NumberFormatInfo.InvariantInfo) + "."); - } - else - { - this.m_listeningPort = value; - } - } + /// + /// Gets or sets the TCP port number on which this will listen for connections. + /// + /// + /// An integer value in the range to + /// indicating the TCP port number on which this will listen for connections. + /// + /// + /// + /// The default value is 23 (the telnet port). + /// + /// + /// The value specified is less than + /// or greater than . + public int Port + { + get + { + return this.m_listeningPort; + } + set + { + if (value < IPEndPoint.MinPort || value > IPEndPoint.MaxPort) + { + throw SystemInfo.CreateArgumentOutOfRangeException("value", (object)value, + "The value specified for Port is less than " + + IPEndPoint.MinPort.ToString(NumberFormatInfo.InvariantInfo) + + " or greater than " + + IPEndPoint.MaxPort.ToString(NumberFormatInfo.InvariantInfo) + "."); + } + else + { + this.m_listeningPort = value; + } + } + } + + /// + /// Overrides the parent method to close the socket handler + /// + /// + /// + /// Closes all the outstanding connections. + /// + /// + protected override void OnClose() + { + base.OnClose(); + + if (this.m_handler != null) + { + this.m_handler.Dispose(); + this.m_handler = null; + } + } + + /// + /// This appender requires a to be set. + /// + /// true + /// + /// + /// This appender requires a to be set. + /// + /// + protected override bool RequiresLayout + { + get { return true; } + } + + /// + /// Initialize the appender based on the options set. + /// + /// + /// + /// This is part of the delayed object + /// activation scheme. The method must + /// be called on this object after the configuration properties have + /// been set. Until is called this + /// object is in an undefined state and must not be used. + /// + /// + /// If any of the configuration properties are modified then + /// must be called again. + /// + /// + /// Create the socket handler and wait for connections + /// + /// + public override void ActivateOptions() + { + base.ActivateOptions(); + try + { + LogLog.Debug(declaringType, "Creating SocketHandler to listen on port ["+ this.m_listeningPort+"]"); + this.m_handler = new SocketHandler(this.m_listeningPort); + } + catch(Exception ex) + { + LogLog.Error(declaringType, "Failed to create SocketHandler", ex); + throw; + } } - /// - /// Overrides the parent method to close the socket handler. - /// - /// - /// - /// Closes all the outstanding connections. - /// - /// - protected override void OnClose() - { - base.OnClose(); - - if (this.m_handler != null) - { - this.m_handler.Dispose(); - this.m_handler = null; - } - } - - /// - /// Gets a value indicating whether this appender requires a to be set. - /// - /// true. - /// - /// - /// This appender requires a to be set. - /// - /// - protected override bool RequiresLayout - { - get { return true; } - } - - /// - /// Initialize the appender based on the options set. - /// - /// - /// - /// This is part of the delayed object - /// activation scheme. The method must - /// be called on this object after the configuration properties have - /// been set. Until is called this - /// object is in an undefined state and must not be used. - /// - /// - /// If any of the configuration properties are modified then - /// must be called again. - /// - /// - /// Create the socket handler and wait for connections. - /// - /// - public override void ActivateOptions() - { - base.ActivateOptions(); - try - { - LogLog.Debug(declaringType, "Creating SocketHandler to listen on port [" + this.m_listeningPort + "]"); - this.m_handler = new SocketHandler(this.m_listeningPort); - } - catch (Exception ex) - { - LogLog.Error(declaringType, "Failed to create SocketHandler", ex); - throw; - } - } - - /// - /// Writes the logging event to each connected client. - /// - /// The event to log. - /// - /// - /// Writes the logging event to each connected client. - /// - /// - protected override void Append(LoggingEvent loggingEvent) - { - if (this.m_handler != null && this.m_handler.HasConnections) - { - this.m_handler.Send(this.RenderLoggingEvent(loggingEvent)); - } + /// + /// Writes the logging event to each connected client. + /// + /// The event to log. + /// + /// + /// Writes the logging event to each connected client. + /// + /// + protected override void Append(LoggingEvent loggingEvent) + { + if (this.m_handler != null && this.m_handler.HasConnections) + { + this.m_handler.Send(this.RenderLoggingEvent(loggingEvent)); + } } - /// - /// Helper class to manage connected clients. - /// - /// - /// - /// The SocketHandler class is used to accept connections from - /// clients. It is threaded so that clients can connect/disconnect - /// asynchronously. - /// - /// - protected class SocketHandler : IDisposable - { - private const int MAX_CONNECTIONS = 20; - - private Socket m_serverSocket; - private ArrayList m_clients = new ArrayList(); - - /// - /// Class that represents a client connected to this handler. - /// - /// - /// - /// Class that represents a client connected to this handler. - /// - /// - protected class SocketClient : IDisposable - { - private Socket m_socket; + /// + /// Helper class to manage connected clients + /// + /// + /// + /// The SocketHandler class is used to accept connections from + /// clients. It is threaded so that clients can connect/disconnect + /// asynchronously. + /// + /// + protected class SocketHandler : IDisposable + { + private const int MAX_CONNECTIONS = 20; + + private Socket m_serverSocket; + private ArrayList m_clients = new ArrayList(); + + /// + /// Class that represents a client connected to this handler + /// + /// + /// + /// Class that represents a client connected to this handler + /// + /// + protected class SocketClient : IDisposable + { + private Socket m_socket; private StreamWriter m_writer; /// - /// Initializes a new instance of the class. - /// Create this for the specified . - /// - /// the client's socket. - /// - /// - /// Opens a stream writer on the socket. - /// - /// - public SocketClient(Socket socket) - { - this.m_socket = socket; - - try - { - this.m_writer = new StreamWriter(new NetworkStream(socket)); - } - catch - { - this.Dispose(); - throw; - } - } - - /// - /// Write a string to the client. - /// - /// string to send. - /// - /// - /// Write a string to the client. - /// - /// - public void Send(string message) - { - this.m_writer.Write(message); - this.m_writer.Flush(); - } + /// Create this for the specified + /// + /// the client's socket + /// + /// + /// Opens a stream writer on the socket. + /// + /// + public SocketClient(Socket socket) + { + this.m_socket = socket; - /// - /// Cleanup the clients connection. - /// - /// - /// - /// Close the socket connection. - /// - /// - public void Dispose() - { - try - { - if (this.m_writer != null) - { - this.m_writer.Close(); - this.m_writer = null; - } - } + try + { + this.m_writer = new StreamWriter(new NetworkStream(socket)); + } catch { + this.Dispose(); + throw; } - - if (this.m_socket != null) - { - try - { - this.m_socket.Shutdown(SocketShutdown.Both); - } - catch + } + + /// + /// Write a string to the client + /// + /// string to send + /// + /// + /// Write a string to the client + /// + /// + public void Send(String message) + { + this.m_writer.Write(message); + this.m_writer.Flush(); + } + + /// + /// Cleanup the clients connection + /// + /// + /// + /// Close the socket connection. + /// + /// + public void Dispose() + { + try + { + if (this.m_writer != null) { + this.m_writer.Dispose(); + this.m_writer = null; } - - try - { - this.m_socket.Close(); - } - catch + } + catch { } + + if (this.m_socket != null) + { + try + { + this.m_socket.Shutdown(SocketShutdown.Both); + } + catch { } + + try { +#if NET_4_0 || NETSTANDARD + this.m_socket.Dispose(); +#else + m_socket.Close(); +#endif } - - this.m_socket = null; - } + catch { } + + this.m_socket = null; + } + } + } + + /// + /// Opens a new server port on + /// + /// the local port to listen on for connections + /// + /// + /// Creates a socket handler on the specified local server port. + /// + /// + public SocketHandler(int port) + { + this.m_serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); + + this.m_serverSocket.Bind(new IPEndPoint(IPAddress.Any, port)); + this.m_serverSocket.Listen(5); + this.AcceptConnection(); + } + + private void AcceptConnection() + { +#if NETSTANDARD + m_serverSocket.AcceptAsync().ContinueWith(OnConnect, TaskScheduler.Default); +#else + this.m_serverSocket.BeginAccept(new AsyncCallback(this.OnConnect), null); +#endif + } + + /// + /// Sends a string message to each of the connected clients + /// + /// the text to send + /// + /// + /// Sends a string message to each of the connected clients + /// + /// + public void Send(String message) + { + ArrayList localClients = this.m_clients; + + foreach (SocketClient client in localClients) + { + try + { + client.Send(message); + } + catch (Exception) + { + // The client has closed the connection, remove it from our list + client.Dispose(); + this.RemoveClient(client); + } + } + } + + /// + /// Add a client to the internal clients list + /// + /// client to add + private void AddClient(SocketClient client) + { + lock(this) + { + ArrayList clientsCopy = (ArrayList)this.m_clients.Clone(); + clientsCopy.Add(client); + this.m_clients = clientsCopy; + } + } + + /// + /// Remove a client from the internal clients list + /// + /// client to remove + private void RemoveClient(SocketClient client) + { + lock(this) + { + ArrayList clientsCopy = (ArrayList)this.m_clients.Clone(); + clientsCopy.Remove(client); + this.m_clients = clientsCopy; + } + } + + /// + /// Test if this handler has active connections + /// + /// + /// true if this handler has active connections + /// + /// + /// + /// This property will be true while this handler has + /// active connections, that is at least one connection that + /// the handler will attempt to send a message to. + /// + /// + public bool HasConnections + { + get + { + ArrayList localClients = this.m_clients; + + return (localClients != null && localClients.Count > 0); } } + +#if NETSTANDARD + private void OnConnect(Task acceptTask) +#else /// - /// Initializes a new instance of the class. - /// Opens a new server port on . - /// - /// the local port to listen on for connections. - /// - /// - /// Creates a socket handler on the specified local server port. - /// - /// - public SocketHandler(int port) - { - this.m_serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); - - this.m_serverSocket.Bind(new IPEndPoint(IPAddress.Any, port)); - this.m_serverSocket.Listen(5); - this.AcceptConnection(); - } - - private void AcceptConnection() - { -#if NETSTANDARD1_3 - m_serverSocket.AcceptAsync().ContinueWith(OnConnect, TaskScheduler.Default); -#else - this.m_serverSocket.BeginAccept(new AsyncCallback(this.OnConnect), null); -#endif - } - - /// - /// Sends a string message to each of the connected clients. - /// - /// the text to send. - /// - /// - /// Sends a string message to each of the connected clients. - /// - /// - public void Send(string message) - { - ArrayList localClients = this.m_clients; - - foreach (SocketClient client in localClients) - { - try - { - client.Send(message); - } - catch (Exception) - { - // The client has closed the connection, remove it from our list - client.Dispose(); - this.RemoveClient(client); - } - } - } - - /// - /// Add a client to the internal clients list. - /// - /// client to add. - private void AddClient(SocketClient client) - { - lock (this) - { - ArrayList clientsCopy = (ArrayList)this.m_clients.Clone(); - clientsCopy.Add(client); - this.m_clients = clientsCopy; - } - } - - /// - /// Remove a client from the internal clients list. - /// - /// client to remove. - private void RemoveClient(SocketClient client) - { - lock (this) - { - ArrayList clientsCopy = (ArrayList)this.m_clients.Clone(); - clientsCopy.Remove(client); - this.m_clients = clientsCopy; - } - } - - /// - /// Gets a value indicating whether test if this handler has active connections. - /// - /// - /// true if this handler has active connections. - /// - /// - /// - /// This property will be true while this handler has - /// active connections, that is at least one connection that - /// the handler will attempt to send a message to. - /// - /// - public bool HasConnections - { - get - { - ArrayList localClients = this.m_clients; - - return localClients != null && localClients.Count > 0; - } - } - -#if NETSTANDARD1_3 - private void OnConnect(Task acceptTask) -#else - /// - /// Callback used to accept a connection on the server socket. - /// - /// The result of the asynchronous operation. - /// - /// - /// On connection adds to the list of connections - /// if there are two many open connections you will be disconnected. - /// - /// - private void OnConnect(IAsyncResult asyncResult) -#endif - { - try - { -#if NETSTANDARD1_3 - Socket socket = acceptTask.GetAwaiter().GetResult(); -#else - // Block until a client connects - Socket socket = this.m_serverSocket.EndAccept(asyncResult); -#endif - LogLog.Debug(declaringType, "Accepting connection from [" + socket.RemoteEndPoint.ToString() + "]"); - SocketClient client = new SocketClient(socket); - - int currentActiveConnectionsCount = this.m_clients.Count; - if (currentActiveConnectionsCount < MAX_CONNECTIONS) - { - try - { - client.Send("TelnetAppender v1.0 (" + (currentActiveConnectionsCount + 1) + " active connections)\r\n\r\n"); - this.AddClient(client); - } - catch - { - client.Dispose(); - } - } - else - { - client.Send("Sorry - Too many connections.\r\n"); - client.Dispose(); - } - } - catch - { - } - finally - { - if (this.m_serverSocket != null) - { - this.AcceptConnection(); - } - } + /// Callback used to accept a connection on the server socket + /// + /// The result of the asynchronous operation + /// + /// + /// On connection adds to the list of connections + /// if there are two many open connections you will be disconnected + /// + /// + private void OnConnect(IAsyncResult asyncResult) +#endif + { + try + { +#if NETSTANDARD + Socket socket = acceptTask.GetAwaiter().GetResult(); +#else + // Block until a client connects + Socket socket = this.m_serverSocket.EndAccept(asyncResult); +#endif + LogLog.Debug(declaringType, "Accepting connection from ["+socket.RemoteEndPoint.ToString()+"]"); + SocketClient client = new SocketClient(socket); + + int currentActiveConnectionsCount = this.m_clients.Count; + if (currentActiveConnectionsCount < MAX_CONNECTIONS) + { + try + { + client.Send("TelnetAppender v1.0 (" + (currentActiveConnectionsCount + 1) + " active connections)\r\n\r\n"); + this.AddClient(client); + } + catch + { + client.Dispose(); + } + } + else + { + client.Send("Sorry - Too many connections.\r\n"); + client.Dispose(); + } + } + catch + { + } + finally + { + if (this.m_serverSocket != null) + { + this.AcceptConnection(); + } + } } - /// - /// Close all network connections. - /// - /// - /// - /// Make sure we close all network connections. - /// - /// - public void Dispose() - { - ArrayList localClients = this.m_clients; - - foreach (SocketClient client in localClients) - { - client.Dispose(); - } - - this.m_clients.Clear(); - - Socket localSocket = this.m_serverSocket; - this.m_serverSocket = null; - try - { - localSocket.Shutdown(SocketShutdown.Both); - } - catch - { - } - - try - { - localSocket.Close(); - } - catch - { - } + /// + /// Close all network connections + /// + /// + /// + /// Make sure we close all network connections + /// + /// + public void Dispose() + { + ArrayList localClients = this.m_clients; + + foreach (SocketClient client in localClients) + { + client.Dispose(); + } + + this.m_clients.Clear(); + + Socket localSocket = this.m_serverSocket; + this.m_serverSocket = null; + try + { + localSocket.Shutdown(SocketShutdown.Both); + } + catch + { + } + + try + { +#if NET_2_0 + localSocket.Close(); +#else + localSocket.Dispose(); +#endif + } + catch + { + } } } - } -} + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/TextWriterAppender.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/TextWriterAppender.cs index d3618911844..b5ad2b1d673 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/TextWriterAppender.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/TextWriterAppender.cs @@ -1,489 +1,484 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.Appender -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; - using System.IO; +using System; +using System.IO; - using log4net.Core; - using log4net.Layout; - using log4net.Util; +using log4net.Util; +using log4net.Layout; +using log4net.Core; - /// - /// Sends logging events to a . - /// - /// - /// - /// An Appender that writes to a . - /// - /// - /// This appender may be used stand alone if initialized with an appropriate - /// writer, however it is typically used as a base class for an appender that - /// can open a to write to. - /// - /// - /// Nicko Cadell. - /// Gert Driesen. - /// Douglas de la Torre. - public class TextWriterAppender : AppenderSkeleton +namespace log4net.Appender +{ + /// + /// Sends logging events to a . + /// + /// + /// + /// An Appender that writes to a . + /// + /// + /// This appender may be used stand alone if initialized with an appropriate + /// writer, however it is typically used as a base class for an appender that + /// can open a to write to. + /// + /// + /// Nicko Cadell + /// Gert Driesen + /// Douglas de la Torre + public class TextWriterAppender : AppenderSkeleton { - /// - /// Initializes a new instance of the class. - /// - /// - /// - /// Default constructor. - /// - /// - public TextWriterAppender() - { - } - - /// - /// Initializes a new instance of the class and - /// sets the output destination to a new initialized - /// with the specified . - /// - /// The layout to use with this appender. - /// The to output to. - /// - /// - /// Obsolete constructor. - /// - /// - [Obsolete("Instead use the default constructor and set the Layout & Writer properties. Scheduled removal in v10.0.0.")] - public TextWriterAppender(ILayout layout, Stream os) - : this(layout, new StreamWriter(os)) - { - } - - /// - /// Initializes a new instance of the class and sets - /// the output destination to the specified . - /// - /// The layout to use with this appender. - /// The to output to. - /// - /// The must have been previously opened. - /// - /// - /// - /// Obsolete constructor. - /// - /// - [Obsolete("Instead use the default constructor and set the Layout & Writer properties. Scheduled removal in v10.0.0.")] - public TextWriterAppender(ILayout layout, TextWriter writer) - { - this.Layout = layout; - this.Writer = writer; + /// + /// Initializes a new instance of the class. + /// + /// + /// + /// Default constructor. + /// + /// + public TextWriterAppender() + { } - /// - /// Gets or sets a value indicating whether gets or set whether the appender will flush at the end - /// of each append operation. - /// - /// - /// - /// The default behavior is to flush at the end of each - /// append operation. - /// - /// - /// If this option is set to false, then the underlying - /// stream can defer persisting the logging event to a later - /// time. - /// - /// - /// - /// Avoiding the flush operation at the end of each append results in - /// a performance gain of 10 to 20 percent. However, there is safety - /// trade-off involved in skipping flushing. Indeed, when flushing is - /// skipped, then it is likely that the last few log events will not - /// be recorded on disk when the application exits. This is a high - /// price to pay even for a 20% performance gain. - /// - public bool ImmediateFlush - { - get { return this.m_immediateFlush; } - set { this.m_immediateFlush = value; } - } - - /// - /// Gets or sets the where the log output will go. - /// - /// - /// - /// The specified must be open and writable. - /// - /// - /// The will be closed when the appender - /// instance is closed. - /// - /// - /// Note: Logging to an unopened will fail. - /// - /// - public virtual TextWriter Writer - { - get { return this.m_qtw; } - - set - { - lock (this) - { - this.Reset(); - if (value != null) - { - this.m_qtw = new QuietTextWriter(value, this.ErrorHandler); - this.WriteHeader(); - } - } - } + /// + /// Initializes a new instance of the class and + /// sets the output destination to a new initialized + /// with the specified . + /// + /// The layout to use with this appender. + /// The to output to. + /// + /// + /// Obsolete constructor. + /// + /// + [Obsolete("Instead use the default constructor and set the Layout & Writer properties")] + public TextWriterAppender(ILayout layout, Stream os) : this(layout, new StreamWriter(os)) + { } - /// - /// This method determines if there is a sense in attempting to append. - /// - /// - /// - /// This method checks if an output target has been set and if a - /// layout has been set. - /// - /// - /// false if any of the preconditions fail. - protected override bool PreAppendCheck() - { - if (!base.PreAppendCheck()) - { - return false; - } - - if (this.m_qtw == null) - { - // Allow subclass to lazily create the writer - this.PrepareWriter(); - - if (this.m_qtw == null) - { - this.ErrorHandler.Error("No output stream or file set for the appender named [" + this.Name + "]."); - return false; - } - } + /// + /// Initializes a new instance of the class and sets + /// the output destination to the specified . + /// + /// The layout to use with this appender + /// The to output to + /// + /// The must have been previously opened. + /// + /// + /// + /// Obsolete constructor. + /// + /// + [Obsolete("Instead use the default constructor and set the Layout & Writer properties")] + public TextWriterAppender(ILayout layout, TextWriter writer) + { + this.Layout = layout; + this.Writer = writer; + } - if (this.m_qtw.Closed) - { - this.ErrorHandler.Error("Output stream for appender named [" + this.Name + "] has been closed."); - return false; - } - - return true; - } - - /// - /// This method is called by the - /// method. - /// - /// The event to log. - /// - /// - /// Writes a log statement to the output stream if the output stream exists - /// and is writable. - /// - /// - /// The format of the output will depend on the appender's layout. - /// - /// - protected override void Append(LoggingEvent loggingEvent) - { - this.RenderLoggingEvent(this.m_qtw, loggingEvent); - - if (this.m_immediateFlush) - { - this.m_qtw.Flush(); - } - } - - /// - /// This method is called by the - /// method. - /// - /// The array of events to log. - /// - /// - /// This method writes all the bulk logged events to the output writer - /// before flushing the stream. - /// - /// - protected override void Append(LoggingEvent[] loggingEvents) - { - foreach (LoggingEvent loggingEvent in loggingEvents) - { - this.RenderLoggingEvent(this.m_qtw, loggingEvent); - } - - if (this.m_immediateFlush) - { - this.m_qtw.Flush(); - } - } - - /// - /// Close this appender instance. The underlying stream or writer is also closed. - /// - /// - /// Closed appenders cannot be reused. - /// - protected override void OnClose() - { - lock (this) - { - this.Reset(); - } - } - - /// - /// Gets or sets or set the and the underlying - /// , if any, for this appender. - /// - /// - /// The for this appender. - /// - public override IErrorHandler ErrorHandler - { - get { return base.ErrorHandler; } + /// + /// Gets or set whether the appender will flush at the end + /// of each append operation. + /// + /// + /// + /// The default behavior is to flush at the end of each + /// append operation. + /// + /// + /// If this option is set to false, then the underlying + /// stream can defer persisting the logging event to a later + /// time. + /// + /// + /// + /// Avoiding the flush operation at the end of each append results in + /// a performance gain of 10 to 20 percent. However, there is safety + /// trade-off involved in skipping flushing. Indeed, when flushing is + /// skipped, then it is likely that the last few log events will not + /// be recorded on disk when the application exits. This is a high + /// price to pay even for a 20% performance gain. + /// + public bool ImmediateFlush + { + get { return this.m_immediateFlush; } + set { this.m_immediateFlush = value; } + } - set - { - lock (this) - { - if (value == null) - { - LogLog.Warn(declaringType, "TextWriterAppender: You have tried to set a null error-handler."); - } - else - { - base.ErrorHandler = value; - if (this.m_qtw != null) - { - this.m_qtw.ErrorHandler = value; - } - } - } - } - } - - /// - /// Gets a value indicating whether this appender requires a to be set. - /// - /// true. - /// - /// - /// This appender requires a to be set. - /// - /// - protected override bool RequiresLayout - { - get { return true; } + /// + /// Sets the where the log output will go. + /// + /// + /// + /// The specified must be open and writable. + /// + /// + /// The will be closed when the appender + /// instance is closed. + /// + /// + /// Note: Logging to an unopened will fail. + /// + /// + public virtual TextWriter Writer + { + get { return this.m_qtw; } + set + { + lock(this) + { + this.Reset(); + if (value != null) + { + this.m_qtw = new QuietTextWriter(value, this.ErrorHandler); + this.WriteHeader(); + } + } + } } - /// - /// Writes the footer and closes the underlying . - /// - /// - /// - /// Writes the footer and closes the underlying . - /// - /// - protected virtual void WriteFooterAndCloseWriter() - { - this.WriteFooter(); - this.CloseWriter(); - } - - /// - /// Closes the underlying . - /// - /// - /// - /// Closes the underlying . - /// - /// - protected virtual void CloseWriter() - { - if (this.m_qtw != null) - { - try - { - this.m_qtw.Close(); - } - catch (Exception e) - { - this.ErrorHandler.Error("Could not close writer [" + this.m_qtw + "]", e); + /// + /// This method determines if there is a sense in attempting to append. + /// + /// + /// + /// This method checks if an output target has been set and if a + /// layout has been set. + /// + /// + /// false if any of the preconditions fail. + protected override bool PreAppendCheck() + { + if (!base.PreAppendCheck()) + { + return false; + } + + if (this.m_qtw == null) + { + // Allow subclass to lazily create the writer + this.PrepareWriter(); - // do need to invoke an error handler - // at this late stage - } - } - } - - /// - /// Clears internal references to the underlying - /// and other variables. - /// - /// - /// - /// Subclasses can override this method for an alternate closing behavior. - /// - /// - protected virtual void Reset() - { - this.WriteFooterAndCloseWriter(); - this.m_qtw = null; - } - - /// - /// Writes a footer as produced by the embedded layout's property. - /// - /// - /// - /// Writes a footer as produced by the embedded layout's property. - /// - /// - protected virtual void WriteFooter() - { - if (this.Layout != null && this.m_qtw != null && !this.m_qtw.Closed) - { - string f = this.Layout.Footer; - if (f != null) - { - this.m_qtw.Write(f); - } - } - } - - /// - /// Writes a header produced by the embedded layout's property. - /// - /// - /// - /// Writes a header produced by the embedded layout's property. - /// - /// - protected virtual void WriteHeader() - { - if (this.Layout != null && this.m_qtw != null && !this.m_qtw.Closed) - { - string h = this.Layout.Header; - if (h != null) - { - this.m_qtw.Write(h); - } - } - } - - /// - /// Called to allow a subclass to lazily initialize the writer. - /// - /// - /// - /// This method is called when an event is logged and the or - /// have not been set. This allows a subclass to - /// attempt to initialize the writer multiple times. - /// - /// - protected virtual void PrepareWriter() - { - } - - /// - /// Gets or sets the where logging events - /// will be written to. - /// - /// - /// The where logging events are written. - /// - /// - /// - /// This is the where logging events - /// will be written to. - /// - /// - protected QuietTextWriter QuietWriter - { - get { return this.m_qtw; } - set { this.m_qtw = value; } + if (this.m_qtw == null) + { + this.ErrorHandler.Error("No output stream or file set for the appender named [" + this.Name + "]."); + return false; + } + } + if (this.m_qtw.Closed) + { + this.ErrorHandler.Error("Output stream for appender named [" + this.Name + "] has been closed."); + return false; + } + + return true; } - /// - /// This is the where logging events - /// will be written to. - /// - private QuietTextWriter m_qtw; - - /// - /// Immediate flush means that the underlying - /// or output stream will be flushed at the end of each append operation. - /// - /// - /// - /// Immediate flush is slower but ensures that each append request is - /// actually written. If is set to - /// false, then there is a good chance that the last few - /// logging events are not actually persisted if and when the application - /// crashes. - /// - /// - /// The default value is true. - /// - /// - private bool m_immediateFlush = true; + /// + /// This method is called by the + /// method. + /// + /// The event to log. + /// + /// + /// Writes a log statement to the output stream if the output stream exists + /// and is writable. + /// + /// + /// The format of the output will depend on the appender's layout. + /// + /// + protected override void Append(LoggingEvent loggingEvent) + { + this.RenderLoggingEvent(this.m_qtw, loggingEvent); - /// - /// The fully qualified type of the TextWriterAppender class. - /// - /// - /// Used by the internal logger to record the Type of the - /// log message. - /// - private static readonly Type declaringType = typeof(TextWriterAppender); + if (this.m_immediateFlush) + { + this.m_qtw.Flush(); + } + } - /// - /// Flushes any buffered log data. - /// - /// The maximum time to wait for logging events to be flushed. - /// True if all logging events were flushed successfully, else false. - public override bool Flush(int millisecondsTimeout) + /// + /// This method is called by the + /// method. + /// + /// The array of events to log. + /// + /// + /// This method writes all the bulk logged events to the output writer + /// before flushing the stream. + /// + /// + protected override void Append(LoggingEvent[] loggingEvents) { - // Nothing to do if ImmediateFlush is true - if (this.m_immediateFlush) + foreach(LoggingEvent loggingEvent in loggingEvents) { - return true; + this.RenderLoggingEvent(this.m_qtw, loggingEvent); } - // lock(this) will block any Appends while the buffer is flushed. - lock (this) + if (this.m_immediateFlush) { this.m_qtw.Flush(); + } + } + + /// + /// Close this appender instance. The underlying stream or writer is also closed. + /// + /// + /// Closed appenders cannot be reused. + /// + protected override void OnClose() + { + lock(this) + { + this.Reset(); } + } - return true; - } - } -} + /// + /// Gets or set the and the underlying + /// , if any, for this appender. + /// + /// + /// The for this appender. + /// + public override IErrorHandler ErrorHandler + { + get { return base.ErrorHandler; } + set + { + lock(this) + { + if (value == null) + { + LogLog.Warn(declaringType, "TextWriterAppender: You have tried to set a null error-handler."); + } + else + { + base.ErrorHandler = value; + if (this.m_qtw != null) + { + this.m_qtw.ErrorHandler = value; + } + } + } + } + } + + /// + /// This appender requires a to be set. + /// + /// true + /// + /// + /// This appender requires a to be set. + /// + /// + protected override bool RequiresLayout + { + get { return true; } + } + + /// + /// Writes the footer and closes the underlying . + /// + /// + /// + /// Writes the footer and closes the underlying . + /// + /// + protected virtual void WriteFooterAndCloseWriter() + { + this.WriteFooter(); + this.CloseWriter(); + } + + /// + /// Closes the underlying . + /// + /// + /// + /// Closes the underlying . + /// + /// + protected virtual void CloseWriter() + { + if (this.m_qtw != null) + { + try + { + this.m_qtw.Close(); + } + catch(Exception e) + { + this.ErrorHandler.Error("Could not close writer [" + this.m_qtw + "]", e); + // do need to invoke an error handler + // at this late stage + } + } + } + + /// + /// Clears internal references to the underlying + /// and other variables. + /// + /// + /// + /// Subclasses can override this method for an alternate closing behavior. + /// + /// + protected virtual void Reset() + { + this.WriteFooterAndCloseWriter(); + this.m_qtw = null; + } + + /// + /// Writes a footer as produced by the embedded layout's property. + /// + /// + /// + /// Writes a footer as produced by the embedded layout's property. + /// + /// + protected virtual void WriteFooter() + { + if (this.Layout != null && this.m_qtw != null && !this.m_qtw.Closed) + { + string f = this.Layout.Footer; + if (f != null) + { + this.m_qtw.Write(f); + } + } + } + + /// + /// Writes a header produced by the embedded layout's property. + /// + /// + /// + /// Writes a header produced by the embedded layout's property. + /// + /// + protected virtual void WriteHeader() + { + if (this.Layout != null && this.m_qtw != null && !this.m_qtw.Closed) + { + string h = this.Layout.Header; + if (h != null) + { + this.m_qtw.Write(h); + } + } + } + + /// + /// Called to allow a subclass to lazily initialize the writer + /// + /// + /// + /// This method is called when an event is logged and the or + /// have not been set. This allows a subclass to + /// attempt to initialize the writer multiple times. + /// + /// + protected virtual void PrepareWriter() + { + } + + /// + /// Gets or sets the where logging events + /// will be written to. + /// + /// + /// The where logging events are written. + /// + /// + /// + /// This is the where logging events + /// will be written to. + /// + /// + protected QuietTextWriter QuietWriter + { + get { return this.m_qtw; } + set { this.m_qtw = value; } + } + + /// + /// This is the where logging events + /// will be written to. + /// + private QuietTextWriter m_qtw; + + /// + /// Immediate flush means that the underlying + /// or output stream will be flushed at the end of each append operation. + /// + /// + /// + /// Immediate flush is slower but ensures that each append request is + /// actually written. If is set to + /// false, then there is a good chance that the last few + /// logging events are not actually persisted if and when the application + /// crashes. + /// + /// + /// The default value is true. + /// + /// + private bool m_immediateFlush = true; + + /// + /// The fully qualified type of the TextWriterAppender class. + /// + /// + /// Used by the internal logger to record the Type of the + /// log message. + /// + private static readonly Type declaringType = typeof(TextWriterAppender); + + /// + /// Flushes any buffered log data. + /// + /// The maximum time to wait for logging events to be flushed. + /// True if all logging events were flushed successfully, else false. + public override bool Flush(int millisecondsTimeout) + { + // Nothing to do if ImmediateFlush is true + if (this.m_immediateFlush) + { + return true; + } + + // lock(this) will block any Appends while the buffer is flushed. + lock (this) + { + this.m_qtw.Flush(); + } + + return true; + } + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/TraceAppender.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/TraceAppender.cs index 501dd1bb088..3be25c930f0 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/TraceAppender.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/TraceAppender.cs @@ -1,217 +1,217 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#define TRACE - -namespace log4net.Appender -{ - using log4net.Core; - using log4net.Layout; +#define TRACE - /// - /// Appends log events to the system. - /// - /// - /// - /// The application configuration file can be used to control what listeners - /// are actually used. See the MSDN documentation for the - /// class for details on configuring the - /// trace system. - /// - /// - /// Events are written using the System.Diagnostics.Trace.Write(string,string) - /// method. The event's logger name is the default value for the category parameter - /// of the Write method. - /// - /// - /// Compact Framework
- /// The Compact Framework does not support the - /// class for any operation except Assert. When using the Compact Framework this - /// appender will write to the system rather than - /// the Trace system. This appender will therefore behave like the . - ///
- ///
- /// Douglas de la Torre. - /// Nicko Cadell. - /// Gert Driesen. - /// Ron Grabowski. - public class TraceAppender : AppenderSkeleton +using log4net.Layout; +using log4net.Core; + +namespace log4net.Appender +{ + /// + /// Appends log events to the system. + /// + /// + /// + /// The application configuration file can be used to control what listeners + /// are actually used. See the MSDN documentation for the + /// class for details on configuring the + /// trace system. + /// + /// + /// Events are written using the System.Diagnostics.Trace.Write(string,string) + /// method. The event's logger name is the default value for the category parameter + /// of the Write method. + /// + /// + /// Compact Framework
+ /// The Compact Framework does not support the + /// class for any operation except Assert. When using the Compact Framework this + /// appender will write to the system rather than + /// the Trace system. This appender will therefore behave like the . + ///
+ ///
+ /// Douglas de la Torre + /// Nicko Cadell + /// Gert Driesen + /// Ron Grabowski + public class TraceAppender : AppenderSkeleton { /// - /// Initializes a new instance of the class. - /// Initializes a new instance of the . - /// - /// - /// - /// Default constructor. - /// - /// - public TraceAppender() - { + /// Initializes a new instance of the . + /// + /// + /// + /// Default constructor. + /// + /// + public TraceAppender() + { + } + + /// + /// Initializes a new instance of the + /// with a specified layout. + /// + /// The layout to use with this appender. + /// + /// + /// Obsolete constructor. + /// + /// + [System.Obsolete("Instead use the default constructor and set the Layout property")] + public TraceAppender(ILayout layout) + { + this.Layout = layout; } /// - /// Initializes a new instance of the class. - /// Initializes a new instance of the - /// with a specified layout. - /// - /// The layout to use with this appender. - /// - /// - /// Obsolete constructor. - /// - /// - [System.Obsolete("Instead use the default constructor and set the Layout property")] - public TraceAppender(ILayout layout) - { - this.Layout = layout; + /// Gets or sets a value that indicates whether the appender will + /// flush at the end of each write. + /// + /// + /// The default behavior is to flush at the end of each + /// write. If the option is set tofalse, then the underlying + /// stream can defer writing to physical medium to a later time. + /// + /// + /// Avoiding the flush operation at the end of each append results + /// in a performance gain of 10 to 20 percent. However, there is safety + /// trade-off involved in skipping flushing. Indeed, when flushing is + /// skipped, then it is likely that the last few log events will not + /// be recorded on disk when the application exits. This is a high + /// price to pay even for a 20% performance gain. + /// + /// + public bool ImmediateFlush + { + get { return this.m_immediateFlush; } + set { this.m_immediateFlush = value; } } - /// - /// Gets or sets a value indicating whether gets or sets a value that indicates whether the appender will - /// flush at the end of each write. - /// - /// - /// The default behavior is to flush at the end of each - /// write. If the option is set tofalse, then the underlying - /// stream can defer writing to physical medium to a later time. - /// - /// - /// Avoiding the flush operation at the end of each append results - /// in a performance gain of 10 to 20 percent. However, there is safety - /// trade-off involved in skipping flushing. Indeed, when flushing is - /// skipped, then it is likely that the last few log events will not - /// be recorded on disk when the application exits. This is a high - /// price to pay even for a 20% performance gain. - /// - /// - public bool ImmediateFlush - { - get { return this.m_immediateFlush; } - set { this.m_immediateFlush = value; } - } - - /// - /// Gets or sets the category parameter sent to the Trace method. - /// - /// - /// - /// Defaults to %logger which will use the logger name of the current - /// as the category parameter. - /// - /// - /// - /// - public PatternLayout Category - { - get { return this.m_category; } - set { this.m_category = value; } + /// + /// The category parameter sent to the Trace method. + /// + /// + /// + /// Defaults to %logger which will use the logger name of the current + /// as the category parameter. + /// + /// + /// + /// + public PatternLayout Category + { + get { return this.m_category; } + set { this.m_category = value; } } - /// - /// Writes the logging event to the system. - /// - /// The event to log. - /// - /// - /// Writes the logging event to the system. - /// - /// - protected override void Append(LoggingEvent loggingEvent) - { - // Write the string to the Trace system - // -#if NETCF - System.Diagnostics.Debug.Write(RenderLoggingEvent(loggingEvent), m_category.Format(loggingEvent)); -#else - System.Diagnostics.Trace.Write(this.RenderLoggingEvent(loggingEvent), this.m_category.Format(loggingEvent)); -#endif - - // - // Flush the Trace system if needed - if (this.m_immediateFlush) - { -#if NETCF - System.Diagnostics.Debug.Flush(); -#else - System.Diagnostics.Trace.Flush(); -#endif - } - } - - /// - /// Gets a value indicating whether this appender requires a to be set. - /// - /// true. - /// - /// - /// This appender requires a to be set. - /// - /// - protected override bool RequiresLayout - { - get { return true; } + /// + /// Writes the logging event to the system. + /// + /// The event to log. + /// + /// + /// Writes the logging event to the system. + /// + /// + protected override void Append(LoggingEvent loggingEvent) + { + // + // Write the string to the Trace system + // +#if NETCF + System.Diagnostics.Debug.Write(RenderLoggingEvent(loggingEvent), m_category.Format(loggingEvent)); +#else + System.Diagnostics.Trace.Write(this.RenderLoggingEvent(loggingEvent), this.m_category.Format(loggingEvent)); +#endif + + // + // Flush the Trace system if needed + // + if (this.m_immediateFlush) + { +#if NETCF + System.Diagnostics.Debug.Flush(); +#else + System.Diagnostics.Trace.Flush(); +#endif + } } - /// - /// Immediate flush means that the underlying writer or output stream - /// will be flushed at the end of each append operation. - /// - /// - /// - /// Immediate flush is slower but ensures that each append request is - /// actually written. If is set to - /// false, then there is a good chance that the last few - /// logs events are not actually written to persistent media if and - /// when the application crashes. - /// - /// - /// The default value is true. - /// - private bool m_immediateFlush = true; - - /// - /// Defaults to %logger. - /// + /// + /// This appender requires a to be set. + /// + /// true + /// + /// + /// This appender requires a to be set. + /// + /// + protected override bool RequiresLayout + { + get { return true; } + } + + /// + /// Immediate flush means that the underlying writer or output stream + /// will be flushed at the end of each append operation. + /// + /// + /// + /// Immediate flush is slower but ensures that each append request is + /// actually written. If is set to + /// false, then there is a good chance that the last few + /// logs events are not actually written to persistent media if and + /// when the application crashes. + /// + /// + /// The default value is true. + /// + private bool m_immediateFlush = true; + + /// + /// Defaults to %logger + /// private PatternLayout m_category = new PatternLayout("%logger"); - /// - /// Flushes any buffered log data. - /// - /// The maximum time to wait for logging events to be flushed. - /// True if all logging events were flushed successfully, else false. - public override bool Flush(int millisecondsTimeout) - { - // Nothing to do if ImmediateFlush is true + /// + /// Flushes any buffered log data. + /// + /// The maximum time to wait for logging events to be flushed. + /// True if all logging events were flushed successfully, else false. + public override bool Flush(int millisecondsTimeout) + { + // Nothing to do if ImmediateFlush is true if (this.m_immediateFlush) { return true; } // System.Diagnostics.Trace and System.Diagnostics.Debug are thread-safe, so no need for lock(this). -#if NETCF - System.Diagnostics.Debug.Flush(); -#else - System.Diagnostics.Trace.Flush(); -#endif - return true; - } - } -} +#if NETCF + System.Diagnostics.Debug.Flush(); +#else + System.Diagnostics.Trace.Flush(); +#endif + return true; + } + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/UdpAppender.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/UdpAppender.cs index 313f9a09ea8..9332f0d06d5 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Appender/UdpAppender.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Appender/UdpAppender.cs @@ -1,527 +1,521 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.Appender -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; - using System.Globalization; - using System.Net; - using System.Net.Sockets; - using System.Text; +using System; +using System.Globalization; +using System.Net; +using System.Net.Sockets; +using System.Text; - using log4net.Core; - using log4net.Layout; - using log4net.Util; +using log4net.Core; - /// - /// Sends logging events as connectionless UDP datagrams to a remote host or a - /// multicast group using an . - /// - /// - /// - /// UDP guarantees neither that messages arrive, nor that they arrive in the correct order. - /// - /// - /// To view the logging results, a custom application can be developed that listens for logging - /// events. - /// - /// - /// When decoding events send via this appender remember to use the same encoding - /// to decode the events as was used to send the events. See the - /// property to specify the encoding to use. - /// - /// - /// - /// This example shows how to log receive logging events that are sent - /// on IP address 244.0.0.1 and port 8080 to the console. The event is - /// encoded in the packet as a unicode string and it is decoded as such. - /// - /// IPEndPoint remoteEndPoint = new IPEndPoint(IPAddress.Any, 0); - /// UdpClient udpClient; - /// byte[] buffer; - /// string loggingEvent; - /// - /// try - /// { - /// udpClient = new UdpClient(8080); - /// - /// while(true) - /// { - /// buffer = udpClient.Receive(ref remoteEndPoint); - /// loggingEvent = System.Text.Encoding.Unicode.GetString(buffer); - /// Console.WriteLine(loggingEvent); - /// } - /// } - /// catch(Exception e) - /// { - /// Console.WriteLine(e.ToString()); - /// } - /// - /// - /// Dim remoteEndPoint as IPEndPoint - /// Dim udpClient as UdpClient - /// Dim buffer as Byte() - /// Dim loggingEvent as String - /// - /// Try - /// remoteEndPoint = new IPEndPoint(IPAddress.Any, 0) - /// udpClient = new UdpClient(8080) - /// - /// While True - /// buffer = udpClient.Receive(ByRef remoteEndPoint) - /// loggingEvent = System.Text.Encoding.Unicode.GetString(buffer) - /// Console.WriteLine(loggingEvent) - /// Wend - /// Catch e As Exception - /// Console.WriteLine(e.ToString()) - /// End Try - /// - /// - /// An example configuration section to log information using this appender to the - /// IP 224.0.0.1 on port 8080: - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// Gert Driesen. - /// Nicko Cadell. - public class UdpAppender : AppenderSkeleton +namespace log4net.Appender +{ + /// + /// Sends logging events as connectionless UDP datagrams to a remote host or a + /// multicast group using an . + /// + /// + /// + /// UDP guarantees neither that messages arrive, nor that they arrive in the correct order. + /// + /// + /// To view the logging results, a custom application can be developed that listens for logging + /// events. + /// + /// + /// When decoding events send via this appender remember to use the same encoding + /// to decode the events as was used to send the events. See the + /// property to specify the encoding to use. + /// + /// + /// + /// This example shows how to log receive logging events that are sent + /// on IP address 244.0.0.1 and port 8080 to the console. The event is + /// encoded in the packet as a unicode string and it is decoded as such. + /// + /// IPEndPoint remoteEndPoint = new IPEndPoint(IPAddress.Any, 0); + /// UdpClient udpClient; + /// byte[] buffer; + /// string loggingEvent; + /// + /// try + /// { + /// udpClient = new UdpClient(8080); + /// + /// while(true) + /// { + /// buffer = udpClient.Receive(ref remoteEndPoint); + /// loggingEvent = System.Text.Encoding.Unicode.GetString(buffer); + /// Console.WriteLine(loggingEvent); + /// } + /// } + /// catch(Exception e) + /// { + /// Console.WriteLine(e.ToString()); + /// } + /// + /// + /// Dim remoteEndPoint as IPEndPoint + /// Dim udpClient as UdpClient + /// Dim buffer as Byte() + /// Dim loggingEvent as String + /// + /// Try + /// remoteEndPoint = new IPEndPoint(IPAddress.Any, 0) + /// udpClient = new UdpClient(8080) + /// + /// While True + /// buffer = udpClient.Receive(ByRef remoteEndPoint) + /// loggingEvent = System.Text.Encoding.Unicode.GetString(buffer) + /// Console.WriteLine(loggingEvent) + /// Wend + /// Catch e As Exception + /// Console.WriteLine(e.ToString()) + /// End Try + /// + /// + /// An example configuration section to log information using this appender to the + /// IP 224.0.0.1 on port 8080: + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// Gert Driesen + /// Nicko Cadell + public class UdpAppender : AppenderSkeleton { - /// - /// Initializes a new instance of the class. - /// - /// - /// The default constructor initializes all fields to their default values. - /// - public UdpAppender() - { + /// + /// Initializes a new instance of the class. + /// + /// + /// The default constructor initializes all fields to their default values. + /// + public UdpAppender() + { } - /// - /// Gets or sets the IP address of the remote host or multicast group to which - /// the underlying should sent the logging event. - /// - /// - /// The IP address of the remote host or multicast group to which the logging event - /// will be sent. - /// - /// - /// - /// Multicast addresses are identified by IP class D addresses (in the range 224.0.0.0 to - /// 239.255.255.255). Multicast packets can pass across different networks through routers, so - /// it is possible to use multicasts in an Internet scenario as long as your network provider - /// supports multicasting. - /// - /// - /// Hosts that want to receive particular multicast messages must register their interest by joining - /// the multicast group. Multicast messages are not sent to networks where no host has joined - /// the multicast group. Class D IP addresses are used for multicast groups, to differentiate - /// them from normal host addresses, allowing nodes to easily detect if a message is of interest. - /// - /// - /// Static multicast addresses that are needed globally are assigned by IANA. A few examples are listed in the table below: - /// - /// - /// - /// - /// IP Address - /// Description - /// - /// - /// 224.0.0.1 - /// - /// - /// Sends a message to all system on the subnet. - /// - /// - /// - /// - /// 224.0.0.2 - /// - /// - /// Sends a message to all routers on the subnet. - /// - /// - /// - /// - /// 224.0.0.12 - /// - /// - /// The DHCP server answers messages on the IP address 224.0.0.12, but only on a subnet. - /// - /// - /// - /// - /// - /// - /// A complete list of actually reserved multicast addresses and their owners in the ranges - /// defined by RFC 3171 can be found at the IANA web site. - /// - /// - /// The address range 239.0.0.0 to 239.255.255.255 is reserved for administrative scope-relative - /// addresses. These addresses can be reused with other local groups. Routers are typically - /// configured with filters to prevent multicast traffic in this range from flowing outside - /// of the local network. - /// - /// - public IPAddress RemoteAddress - { - get { return this.m_remoteAddress; } - set { this.m_remoteAddress = value; } - } - - /// - /// Gets or sets the TCP port number of the remote host or multicast group to which - /// the underlying should sent the logging event. - /// - /// - /// An integer value in the range to - /// indicating the TCP port number of the remote host or multicast group to which the logging event - /// will be sent. - /// - /// - /// The underlying will send messages to this TCP port number - /// on the remote host or multicast group. - /// - /// The value specified is less than or greater than . - public int RemotePort - { - get { return this.m_remotePort; } + /// + /// Gets or sets the IP address of the remote host or multicast group to which + /// the underlying should sent the logging event. + /// + /// + /// The IP address of the remote host or multicast group to which the logging event + /// will be sent. + /// + /// + /// + /// Multicast addresses are identified by IP class D addresses (in the range 224.0.0.0 to + /// 239.255.255.255). Multicast packets can pass across different networks through routers, so + /// it is possible to use multicasts in an Internet scenario as long as your network provider + /// supports multicasting. + /// + /// + /// Hosts that want to receive particular multicast messages must register their interest by joining + /// the multicast group. Multicast messages are not sent to networks where no host has joined + /// the multicast group. Class D IP addresses are used for multicast groups, to differentiate + /// them from normal host addresses, allowing nodes to easily detect if a message is of interest. + /// + /// + /// Static multicast addresses that are needed globally are assigned by IANA. A few examples are listed in the table below: + /// + /// + /// + /// + /// IP Address + /// Description + /// + /// + /// 224.0.0.1 + /// + /// + /// Sends a message to all system on the subnet. + /// + /// + /// + /// + /// 224.0.0.2 + /// + /// + /// Sends a message to all routers on the subnet. + /// + /// + /// + /// + /// 224.0.0.12 + /// + /// + /// The DHCP server answers messages on the IP address 224.0.0.12, but only on a subnet. + /// + /// + /// + /// + /// + /// + /// A complete list of actually reserved multicast addresses and their owners in the ranges + /// defined by RFC 3171 can be found at the IANA web site. + /// + /// + /// The address range 239.0.0.0 to 239.255.255.255 is reserved for administrative scope-relative + /// addresses. These addresses can be reused with other local groups. Routers are typically + /// configured with filters to prevent multicast traffic in this range from flowing outside + /// of the local network. + /// + /// + public IPAddress RemoteAddress + { + get { return this.m_remoteAddress; } + set { this.m_remoteAddress = value; } + } - set - { - if (value < IPEndPoint.MinPort || value > IPEndPoint.MaxPort) - { - throw log4net.Util.SystemInfo.CreateArgumentOutOfRangeException("value", (object)value, - "The value specified is less than " + - IPEndPoint.MinPort.ToString(NumberFormatInfo.InvariantInfo) + - " or greater than " + - IPEndPoint.MaxPort.ToString(NumberFormatInfo.InvariantInfo) + "."); - } - else - { - this.m_remotePort = value; - } - } - } - - /// - /// Gets or sets the TCP port number from which the underlying will communicate. - /// - /// - /// An integer value in the range to - /// indicating the TCP port number from which the underlying will communicate. - /// - /// - /// - /// The underlying will bind to this port for sending messages. - /// - /// - /// Setting the value to 0 (the default) will cause the udp client not to bind to - /// a local port. - /// - /// - /// The value specified is less than or greater than . - public int LocalPort - { - get { return this.m_localPort; } + /// + /// Gets or sets the TCP port number of the remote host or multicast group to which + /// the underlying should sent the logging event. + /// + /// + /// An integer value in the range to + /// indicating the TCP port number of the remote host or multicast group to which the logging event + /// will be sent. + /// + /// + /// The underlying will send messages to this TCP port number + /// on the remote host or multicast group. + /// + /// The value specified is less than or greater than . + public int RemotePort + { + get { return this.m_remotePort; } + set + { + if (value < IPEndPoint.MinPort || value > IPEndPoint.MaxPort) + { + throw Util.SystemInfo.CreateArgumentOutOfRangeException("value", (object)value, + "The value specified is less than " + + IPEndPoint.MinPort.ToString(NumberFormatInfo.InvariantInfo) + + " or greater than " + + IPEndPoint.MaxPort.ToString(NumberFormatInfo.InvariantInfo) + "."); + } + else + { + this.m_remotePort = value; + } + } + } - set - { - if (value != 0 && (value < IPEndPoint.MinPort || value > IPEndPoint.MaxPort)) - { - throw log4net.Util.SystemInfo.CreateArgumentOutOfRangeException("value", (object)value, - "The value specified is less than " + - IPEndPoint.MinPort.ToString(NumberFormatInfo.InvariantInfo) + - " or greater than " + - IPEndPoint.MaxPort.ToString(NumberFormatInfo.InvariantInfo) + "."); - } - else - { - this.m_localPort = value; - } - } - } - - /// - /// Gets or sets used to write the packets. - /// - /// - /// The used to write the packets. - /// - /// - /// - /// The used to write the packets. - /// - /// - public Encoding Encoding - { - get { return this.m_encoding; } - set { this.m_encoding = value; } + /// + /// Gets or sets the TCP port number from which the underlying will communicate. + /// + /// + /// An integer value in the range to + /// indicating the TCP port number from which the underlying will communicate. + /// + /// + /// + /// The underlying will bind to this port for sending messages. + /// + /// + /// Setting the value to 0 (the default) will cause the udp client not to bind to + /// a local port. + /// + /// + /// The value specified is less than or greater than . + public int LocalPort + { + get { return this.m_localPort; } + set + { + if (value != 0 && (value < IPEndPoint.MinPort || value > IPEndPoint.MaxPort)) + { + throw Util.SystemInfo.CreateArgumentOutOfRangeException("value", (object)value, + "The value specified is less than " + + IPEndPoint.MinPort.ToString(NumberFormatInfo.InvariantInfo) + + " or greater than " + + IPEndPoint.MaxPort.ToString(NumberFormatInfo.InvariantInfo) + "."); + } + else + { + this.m_localPort = value; + } + } } - /// - /// Gets or sets the underlying . - /// - /// - /// The underlying . - /// - /// - /// creates a to send logging events - /// over a network. Classes deriving from can use this - /// property to get or set this . Use the underlying - /// returned from if you require access beyond that which - /// provides. - /// - protected UdpClient Client - { - get { return this.m_client; } - set { this.m_client = value; } - } - - /// - /// Gets or sets the cached remote endpoint to which the logging events should be sent. - /// - /// - /// The cached remote endpoint to which the logging events will be sent. - /// - /// - /// The method will initialize the remote endpoint - /// with the values of the and - /// properties. - /// - protected IPEndPoint RemoteEndPoint - { - get { return this.m_remoteEndPoint; } - set { this.m_remoteEndPoint = value; } + /// + /// Gets or sets used to write the packets. + /// + /// + /// The used to write the packets. + /// + /// + /// + /// The used to write the packets. + /// + /// + public Encoding Encoding + { + get { return this.m_encoding; } + set { this.m_encoding = value; } } - /// - /// Initialize the appender based on the options set. - /// - /// - /// - /// This is part of the delayed object - /// activation scheme. The method must - /// be called on this object after the configuration properties have - /// been set. Until is called this - /// object is in an undefined state and must not be used. - /// - /// - /// If any of the configuration properties are modified then - /// must be called again. - /// - /// - /// The appender will be ignored if no was specified or - /// an invalid remote or local TCP port number was specified. - /// - /// - /// The required property was not specified. - /// The TCP port number assigned to or is less than or greater than . - public override void ActivateOptions() - { - base.ActivateOptions(); - - if (this.RemoteAddress == null) - { - throw new ArgumentNullException("The required property 'Address' was not specified."); - } - else if (this.RemotePort < IPEndPoint.MinPort || this.RemotePort > IPEndPoint.MaxPort) - { - throw log4net.Util.SystemInfo.CreateArgumentOutOfRangeException("this.RemotePort", (object)this.RemotePort, - "The RemotePort is less than " + - IPEndPoint.MinPort.ToString(NumberFormatInfo.InvariantInfo) + - " or greater than " + - IPEndPoint.MaxPort.ToString(NumberFormatInfo.InvariantInfo) + "."); - } - else if (this.LocalPort != 0 && (this.LocalPort < IPEndPoint.MinPort || this.LocalPort > IPEndPoint.MaxPort)) - { - throw log4net.Util.SystemInfo.CreateArgumentOutOfRangeException("this.LocalPort", (object)this.LocalPort, - "The LocalPort is less than " + - IPEndPoint.MinPort.ToString(NumberFormatInfo.InvariantInfo) + - " or greater than " + - IPEndPoint.MaxPort.ToString(NumberFormatInfo.InvariantInfo) + "."); - } - else - { - this.RemoteEndPoint = new IPEndPoint(this.RemoteAddress, this.RemotePort); - this.InitializeClientConnection(); - } + /// + /// Gets or sets the underlying . + /// + /// + /// The underlying . + /// + /// + /// creates a to send logging events + /// over a network. Classes deriving from can use this + /// property to get or set this . Use the underlying + /// returned from if you require access beyond that which + /// provides. + /// + protected UdpClient Client + { + get { return this.m_client; } + set { this.m_client = value; } } - /// - /// This method is called by the method. - /// - /// The event to log. - /// - /// - /// Sends the event using an UDP datagram. - /// - /// - /// Exceptions are passed to the . - /// - /// - protected override void Append(LoggingEvent loggingEvent) - { - try - { - byte[] buffer = this.m_encoding.GetBytes(this.RenderLoggingEvent(loggingEvent).ToCharArray()); -#if NETSTANDARD1_3 - Client.SendAsync(buffer, buffer.Length, RemoteEndPoint).Wait(); -#else - this.Client.Send(buffer, buffer.Length, this.RemoteEndPoint); -#endif - } - catch (Exception ex) - { - this.ErrorHandler.Error( - "Unable to send logging event to remote host " + - this.RemoteAddress.ToString() + - " on port " + - this.RemotePort + ".", - ex, - ErrorCode.WriteFailure); - } - } - - /// - /// Gets a value indicating whether this appender requires a to be set. - /// - /// true. - /// - /// - /// This appender requires a to be set. - /// - /// - protected override bool RequiresLayout - { - get { return true; } - } - - /// - /// Closes the UDP connection and releases all resources associated with - /// this instance. - /// - /// - /// - /// Disables the underlying and releases all managed - /// and unmanaged resources associated with the . - /// - /// - protected override void OnClose() - { - base.OnClose(); - - if (this.Client != null) - { - this.Client.Close(); - this.Client = null; - } + /// + /// Gets or sets the cached remote endpoint to which the logging events should be sent. + /// + /// + /// The cached remote endpoint to which the logging events will be sent. + /// + /// + /// The method will initialize the remote endpoint + /// with the values of the and + /// properties. + /// + protected IPEndPoint RemoteEndPoint + { + get { return this.m_remoteEndPoint; } + set { this.m_remoteEndPoint = value; } + } + + /// + /// Initialize the appender based on the options set. + /// + /// + /// + /// This is part of the delayed object + /// activation scheme. The method must + /// be called on this object after the configuration properties have + /// been set. Until is called this + /// object is in an undefined state and must not be used. + /// + /// + /// If any of the configuration properties are modified then + /// must be called again. + /// + /// + /// The appender will be ignored if no was specified or + /// an invalid remote or local TCP port number was specified. + /// + /// + /// The required property was not specified. + /// The TCP port number assigned to or is less than or greater than . + public override void ActivateOptions() + { + base.ActivateOptions(); + + if (this.RemoteAddress == null) + { + throw new ArgumentNullException("The required property 'Address' was not specified."); + } + else if (this.RemotePort < IPEndPoint.MinPort || this.RemotePort > IPEndPoint.MaxPort) + { + throw Util.SystemInfo.CreateArgumentOutOfRangeException("this.RemotePort", (object)this.RemotePort, + "The RemotePort is less than " + + IPEndPoint.MinPort.ToString(NumberFormatInfo.InvariantInfo) + + " or greater than " + + IPEndPoint.MaxPort.ToString(NumberFormatInfo.InvariantInfo) + "."); + } + else if (this.LocalPort != 0 && (this.LocalPort < IPEndPoint.MinPort || this.LocalPort > IPEndPoint.MaxPort)) + { + throw Util.SystemInfo.CreateArgumentOutOfRangeException("this.LocalPort", (object)this.LocalPort, + "The LocalPort is less than " + + IPEndPoint.MinPort.ToString(NumberFormatInfo.InvariantInfo) + + " or greater than " + + IPEndPoint.MaxPort.ToString(NumberFormatInfo.InvariantInfo) + "."); + } + else + { + this.RemoteEndPoint = new IPEndPoint(this.RemoteAddress, this.RemotePort); + this.InitializeClientConnection(); + } } - /// - /// Initializes the underlying connection. - /// - /// - /// - /// The underlying is initialized and binds to the - /// port number from which you intend to communicate. - /// - /// - /// Exceptions are passed to the . - /// - /// - protected virtual void InitializeClientConnection() - { - try - { - if (this.LocalPort == 0) - { -#if NETCF || NET_1_0 || SSCLI_1_0 || CLI_1_0 - this.Client = new UdpClient(); -#else - this.Client = new UdpClient(this.RemoteAddress.AddressFamily); -#endif - } - else - { -#if NETCF || NET_1_0 || SSCLI_1_0 || CLI_1_0 - this.Client = new UdpClient(this.LocalPort); -#else - this.Client = new UdpClient(this.LocalPort, this.RemoteAddress.AddressFamily); -#endif - } - } - catch (Exception ex) - { - this.ErrorHandler.Error( - "Could not initialize the UdpClient connection on port " + - this.LocalPort.ToString(NumberFormatInfo.InvariantInfo) + ".", - ex, - ErrorCode.GenericFailure); - - this.Client = null; - } + /// + /// This method is called by the method. + /// + /// The event to log. + /// + /// + /// Sends the event using an UDP datagram. + /// + /// + /// Exceptions are passed to the . + /// + /// + protected override void Append(LoggingEvent loggingEvent) + { + try + { + Byte [] buffer = this.m_encoding.GetBytes(this.RenderLoggingEvent(loggingEvent).ToCharArray()); +#if NETSTANDARD + Client.SendAsync(buffer, buffer.Length, RemoteEndPoint).Wait(); +#else + this.Client.Send(buffer, buffer.Length, this.RemoteEndPoint); +#endif + } + catch (Exception ex) + { + this.ErrorHandler.Error( + "Unable to send logging event to remote host " + + this.RemoteAddress.ToString() + + " on port " + + this.RemotePort + ".", + ex, + ErrorCode.WriteFailure); + } } - /// - /// The IP address of the remote host or multicast group to which - /// the logging event will be sent. - /// - private IPAddress m_remoteAddress; - - /// - /// The TCP port number of the remote host or multicast group to - /// which the logging event will be sent. - /// - private int m_remotePort; - - /// - /// The cached remote endpoint to which the logging events will be sent. - /// - private IPEndPoint m_remoteEndPoint; - - /// - /// The TCP port number from which the will communicate. - /// - private int m_localPort; - - /// - /// The instance that will be used for sending the - /// logging events. - /// + /// + /// This appender requires a to be set. + /// + /// true + /// + /// + /// This appender requires a to be set. + /// + /// + protected override bool RequiresLayout + { + get { return true; } + } + + /// + /// Closes the UDP connection and releases all resources associated with + /// this instance. + /// + /// + /// + /// Disables the underlying and releases all managed + /// and unmanaged resources associated with the . + /// + /// + protected override void OnClose() + { + base.OnClose(); + + if (this.Client != null) + { + this.Client.Close(); + } + } + + /// + /// Initializes the underlying connection. + /// + /// + /// + /// The underlying is initialized and binds to the + /// port number from which you intend to communicate. + /// + /// + /// Exceptions are passed to the . + /// + /// + protected virtual void InitializeClientConnection() + { + try + { + if (this.LocalPort == 0) + { +#if NETCF || NET_1_0 || SSCLI_1_0 || CLI_1_0 + this.Client = new UdpClient(); +#else + this.Client = new UdpClient(this.RemoteAddress.AddressFamily); +#endif + } + else + { +#if NETCF || NET_1_0 || SSCLI_1_0 || CLI_1_0 + this.Client = new UdpClient(this.LocalPort); +#else + this.Client = new UdpClient(this.LocalPort, this.RemoteAddress.AddressFamily); +#endif + } + } + catch (Exception ex) + { + this.ErrorHandler.Error( + "Could not initialize the UdpClient connection on port " + + this.LocalPort.ToString(NumberFormatInfo.InvariantInfo) + ".", + ex, + ErrorCode.GenericFailure); + + this.Client = null; + } + } + + /// + /// The IP address of the remote host or multicast group to which + /// the logging event will be sent. + /// + private IPAddress m_remoteAddress; + + /// + /// The TCP port number of the remote host or multicast group to + /// which the logging event will be sent. + /// + private int m_remotePort; + + /// + /// The cached remote endpoint to which the logging events will be sent. + /// + private IPEndPoint m_remoteEndPoint; + + /// + /// The TCP port number from which the will communicate. + /// + private int m_localPort; + + /// + /// The instance that will be used for sending the + /// logging events. + /// private UdpClient m_client; - /// - /// The encoding to use for the packet. - /// -#if NETSTANDARD1_3 - private Encoding m_encoding = Encoding.Unicode; -#else + /// + /// The encoding to use for the packet. + /// +#if NETSTANDARD + private Encoding m_encoding = Encoding.Unicode; +#else private Encoding m_encoding = Encoding.Default; -#endif - - } -} +#endif + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/AssemblyInfo.cs b/DNN Platform/DotNetNuke.Log4net/log4net/AssemblyInfo.cs index 5cd3923951b..d587b76f117 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/AssemblyInfo.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/AssemblyInfo.cs @@ -1,142 +1,179 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information - -// +// // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at -// +// // http://www.apache.org/licenses/LICENSE-2.0 -// +// // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. +// + +using System.Reflection; +using System.Runtime.CompilerServices; + +#if (!SSCLI) +// +// log4net makes use of static methods which cannot be made com visible // -using System.Reflection; -using System.Runtime.CompilerServices; - -#if !SSCLI -// -// log4net makes use of static methods which cannot be made com visible -// -[assembly: System.Runtime.InteropServices.ComVisible(false)] -#endif - -// -// log4net is CLS compliant -// -[assembly: System.CLSCompliant(true)] - -#if !NETCF -// -// If log4net is strongly named it still allows partially trusted callers -// -[assembly: System.Security.AllowPartiallyTrustedCallers] -#endif - -#if NET_4_0 -// -// Allows partial trust applications (e.g. ASP.NET shared hosting) on .NET 4.0 to work -// given our implementation of ISerializable. -// -[assembly: System.Security.SecurityRules(System.Security.SecurityRuleSet.Level1)] -#endif - -// -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -// -#if CLI_1_0 -[assembly: AssemblyInformationalVersionAttribute("2.0.6.0-.CLI 1.0")] -[assembly: AssemblyTitle("Apache log4net for CLI 1.0 Compatible Frameworks")] -#elif NET_1_0 -[assembly: AssemblyInformationalVersionAttribute("2.0.6.0-.NET 1.0")] -[assembly: AssemblyTitle("Apache log4net for .NET Framework 1.0")] -#elif NET_1_1 -[assembly: AssemblyInformationalVersionAttribute("2.0.6.0-.NET 1.1")] -[assembly: AssemblyTitle("Apache log4net for .NET Framework 1.1")] -#elif NET_4_5 -[assembly: AssemblyInformationalVersionAttribute("2.0.6.0-.NET 4.5")] -[assembly: AssemblyTitle("Apache log4net for .NET Framework 4.5")] -#elif NET_4_0 -#if CLIENT_PROFILE -[assembly: AssemblyInformationalVersionAttribute("2.0.6.0-.NET 4.0 CP")] -[assembly: AssemblyTitle("Apache log4net for .NET Framework 4.0 Client Profile")] -#else -[assembly: AssemblyInformationalVersionAttribute("2.0.6.0-.NET 4.0")] -[assembly: AssemblyTitle("Apache log4net for .NET Framework 4.0")] -#endif // Client Profile -#elif NET_2_0 -#if CLIENT_PROFILE -[assembly: AssemblyInformationalVersionAttribute("2.0.6.0-.NET 3.5 CP")] -[assembly: AssemblyTitle("Apache log4net for .NET Framework 3.5 Client Profile")] -#else -[assembly: AssemblyInformationalVersionAttribute("2.0.6.0-.NET 2.0")] -[assembly: AssemblyTitle("Apache log4net for .NET Framework 2.0")] -#endif // Client Profile -#elif NETCF_1_0 -[assembly: AssemblyInformationalVersionAttribute("2.0.6.0-.NETCF 1.0")] -[assembly: AssemblyTitle("Apache log4net for .NET Compact Framework 1.0")] -#elif NETCF_2_0 -[assembly: AssemblyInformationalVersionAttribute("2.0.6.0-.NETCF 2.0")] -[assembly: AssemblyTitle("Apache log4net for .NET Compact Framework 2.0")] -#elif MONO_1_0 -[assembly: AssemblyInformationalVersionAttribute("2.0.6.0-Mono 1.0")] -[assembly: AssemblyTitle("Apache log4net for Mono 1.0")] -#elif MONO_2_0 -[assembly: AssemblyInformationalVersionAttribute("2.0.6.0-Mono 2.0")] -[assembly: AssemblyTitle("Apache log4net for Mono 2.0")] -#elif MONO_3_5 -[assembly: AssemblyInformationalVersionAttribute("2.0.6.0-Mono 3.5")] -[assembly: AssemblyTitle("Apache log4net for Mono 3.5")] -#elif MONO_4_0 -[assembly: AssemblyInformationalVersionAttribute("2.0.6.0-Mono 4.0")] -[assembly: AssemblyTitle("Apache log4net for Mono 4.0")] -#elif SSCLI_1_0 -[assembly: AssemblyInformationalVersionAttribute("2.0.6.0-SSCLI 1.0")] -[assembly: AssemblyTitle("Apache log4net for Shared Source CLI 1.0")] -#elif NET -[assembly: AssemblyInformationalVersionAttribute("2.0.6.0-.NET")] -[assembly: AssemblyTitle("Apache log4net for .NET Framework")] -#elif NETSTANDARD1_3 -[assembly: AssemblyInformationalVersionAttribute("2.0.6.0-.NET Core 1.0")] -[assembly: AssemblyTitle("DotNetNuke.log4net for .NET Core 1.0")] -#elif NETCF -[assembly: AssemblyInformationalVersionAttribute("2.0.6.0-.NETCF")] -[assembly: AssemblyTitle("DotNetNuke.log4net for .NET Compact Framework")] -#elif MONO -[assembly: AssemblyInformationalVersionAttribute("2.0.6.0-Mono")] -[assembly: AssemblyTitle("DotNetNuke.log4net for Mono")] -#elif SSCLI -[assembly: AssemblyInformationalVersionAttribute("2.0.6.0-SSCLI")] -[assembly: AssemblyTitle("DotNetNuke.log4net for Shared Source CLI")] -#else -[assembly: AssemblyInformationalVersionAttribute("2.0.6.0")] -[assembly: AssemblyTitle("DotNetNuke.log4net")] -#endif - -#if DEBUG -[assembly: AssemblyConfiguration("Debug")] -#else -[assembly: AssemblyConfiguration("Retail")] -#endif - -[assembly: AssemblyProduct("log4net")] -[assembly: AssemblyDefaultAlias("log4net")] -[assembly: AssemblyCulture("")] -[assembly: AssemblyDescription("DotNetNuke branded version of log4net")] - -#if STRONG && (CLI_1_0 || NET_1_0 || NET_1_1 || NETCF_1_0 || SSCLI) -[assembly: AssemblyDelaySign(false)] -[assembly: AssemblyKeyFile(@"..\..\..\log4net.snk")] -#endif +[assembly: System.Runtime.InteropServices.ComVisible(false)] +#endif + +// +// log4net is CLS compliant +// +[assembly: System.CLSCompliant(true)] + +#if (!NETCF) +// +// If log4net is strongly named it still allows partially trusted callers +// +[assembly: System.Security.AllowPartiallyTrustedCallers] +#endif + +#if (NET_4_0 || NETSTANDARD2_0) +// +// Allows partial trust applications (e.g. ASP.NET shared hosting) on .NET 4.0 to work +// given our implementation of ISerializable. +// +[assembly: System.Security.SecurityRules(System.Security.SecurityRuleSet.Level1)] +#endif +// +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +// + +#if (CLI_1_0) +[assembly: AssemblyInformationalVersionAttribute("2.0.14.0-.CLI 1.0")] +[assembly: AssemblyTitle("Apache log4net for CLI 1.0 Compatible Frameworks")] +#elif (NET_1_0) +[assembly: AssemblyInformationalVersionAttribute("2.0.14.0-.NET 1.0")] +[assembly: AssemblyTitle("Apache log4net for .NET Framework 1.0")] +#elif (NET_1_1) +[assembly: AssemblyInformationalVersionAttribute("2.0.14.0-.NET 1.1")] +[assembly: AssemblyTitle("Apache log4net for .NET Framework 1.1")] +#elif (NET_4_5) +[assembly: AssemblyInformationalVersionAttribute("2.0.14.0-.NET 4.5")] +[assembly: AssemblyTitle("Apache log4net for .NET Framework 4.5")] +#elif (NET_4_0) +#if CLIENT_PROFILE +[assembly: AssemblyInformationalVersionAttribute("2.0.14.0-.NET 4.0 CP")] +[assembly: AssemblyTitle("Apache log4net for .NET Framework 4.0 Client Profile")] +#else +[assembly: AssemblyInformationalVersionAttribute("2.0.14.0-.NET 4.0")] +[assembly: AssemblyTitle("Apache log4net for .NET Framework 4.0")] +#endif // Client Profile +#elif (NET_3_5) +#if CLIENT_PROFILE +[assembly: AssemblyInformationalVersionAttribute("2.0.14.0-.NET 3.5 CP")] +[assembly: AssemblyTitle("Apache log4net for .NET Framework 3.5 Client Profile")] +#else +[assembly: AssemblyInformationalVersionAttribute("2.0.14.0-.NET 3.5")] +[assembly: AssemblyTitle("Apache log4net for .NET Framework 3.5")] +#endif // Client Profile +#elif (NET_2_0) +[assembly: AssemblyInformationalVersionAttribute("2.0.14.0-.NET 2.0")] +[assembly: AssemblyTitle("Apache log4net for .NET Framework 2.0")] +#elif (NETCF_1_0) +[assembly: AssemblyInformationalVersionAttribute("2.0.14.0-.NETCF 1.0")] +[assembly: AssemblyTitle("Apache log4net for .NET Compact Framework 1.0")] +#elif (NETCF_2_0) +[assembly: AssemblyInformationalVersionAttribute("2.0.14.0-.NETCF 2.0")] +[assembly: AssemblyTitle("Apache log4net for .NET Compact Framework 2.0")] +#elif (MONO_1_0) +[assembly: AssemblyInformationalVersionAttribute("2.0.14.0-Mono 1.0")] +[assembly: AssemblyTitle("Apache log4net for Mono 1.0")] +#elif (MONO_2_0) +[assembly: AssemblyInformationalVersionAttribute("2.0.14.0-Mono 2.0")] +[assembly: AssemblyTitle("Apache log4net for Mono 2.0")] +#elif (MONO_3_5) +[assembly: AssemblyInformationalVersionAttribute("2.0.14.0-Mono 3.5")] +[assembly: AssemblyTitle("Apache log4net for Mono 3.5")] +#elif (MONO_4_0) +[assembly: AssemblyInformationalVersionAttribute("2.0.14.0-Mono 4.0")] +[assembly: AssemblyTitle("Apache log4net for Mono 4.0")] +#elif (SSCLI_1_0) +[assembly: AssemblyInformationalVersionAttribute("2.0.14.0-SSCLI 1.0")] +[assembly: AssemblyTitle("Apache log4net for Shared Source CLI 1.0")] +#elif (NET) +[assembly: AssemblyInformationalVersionAttribute("2.0.14.0-.NET")] +[assembly: AssemblyTitle("Apache log4net for .NET Framework")] +#elif (NETSTANDARD1_3) +[assembly: AssemblyInformationalVersionAttribute("2.0.14.0-.NET Standard 1.3")] +[assembly: AssemblyTitle("Apache log4net for .NET Standard 1.3")] +#elif (NETSTANDARD2_0) +[assembly: AssemblyInformationalVersionAttribute("2.0.14.0-.NET Standard 2.0")] +[assembly: AssemblyTitle("Apache log4net for .NET Standard 2.0")] +#elif (NETCF) +[assembly: AssemblyInformationalVersionAttribute("2.0.14.0-.NETCF")] +[assembly: AssemblyTitle("Apache log4net for .NET Compact Framework")] +#elif (MONO) +[assembly: AssemblyInformationalVersionAttribute("2.0.14.0-Mono")] +[assembly: AssemblyTitle("Apache log4net for Mono")] +#elif (SSCLI) +[assembly: AssemblyInformationalVersionAttribute("2.0.14.0-SSCLI")] +[assembly: AssemblyTitle("Apache log4net for Shared Source CLI")] +#else +[assembly: AssemblyInformationalVersionAttribute("2.0.14.0")] +[assembly: AssemblyTitle("Apache log4net")] +#endif + +#if DEBUG +[assembly: AssemblyConfiguration("Debug")] +#else +[assembly: AssemblyConfiguration("Retail")] +#endif + +[assembly: AssemblyProduct("log4net")] +[assembly: AssemblyDefaultAlias("log4net")] +[assembly: AssemblyCulture("")] +[assembly: AssemblyDescription("DotNetNuke branded version of log4net")] + +// +// In order to sign your assembly you must specify a key to use. Refer to the +// Microsoft .NET Framework documentation for more information on assembly signing. +// +// Use the attributes below to control which key is used for signing. +// +// Notes: +// (*) If no key is specified, the assembly is not signed. +// (*) KeyName refers to a key that has been installed in the Crypto Service +// Provider (CSP) on your machine. KeyFile refers to a file which contains +// a key. +// (*) If the KeyFile and the KeyName values are both specified, the +// following processing occurs: +// (1) If the KeyName can be found in the CSP, that key is used. +// (2) If the KeyName does not exist and the KeyFile does exist, the key +// in the KeyFile is installed into the CSP and used. +// (*) In order to create a KeyFile, you can use the sn.exe (Strong Name) utility. +// When specifying the KeyFile, the location of the KeyFile should be +// relative to the project output directory which is +// %Project Directory%\obj\. For example, if your KeyFile is +// located in the project directory, you would specify the AssemblyKeyFile +// attribute as [assembly: AssemblyKeyFile("..\\..\\mykey.snk")] +// (*) Delay Signing is an advanced option - see the Microsoft .NET Framework +// documentation for more information on this. +// +#if STRONG && (CLI_1_0 || NET_1_0 || NET_1_1 || NETCF_1_0 || SSCLI) +[assembly: AssemblyDelaySign(false)] +[assembly: AssemblyKeyFile(@"..\..\..\log4net.snk")] +#endif +// We do not use a CSP key for strong naming +// [assembly: AssemblyKeyName("")] + +[assembly: InternalsVisibleTo("log4net.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100297dcac908e286" + + "89360399027b0ea4cd852fbb74e1ed95e695a5ba55cbd1d075ec20cdb5fa6fc593d3d571527b20" + + "558d6f39e1f4d5cfe0798428c589c311965244b209c38a02aaa8c9da3b72405b6fedeeb4292c34" + + "57e9769b74e645c19cb06c2be75fb2d12281a585fbeabf7bd195d6961ba113286fc3e286d7bbd6" + + "9024ceda")] -// We do not use a CSP key for strong naming -// [assembly: AssemblyKeyName("")] diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/AssemblyVersionInfo.cs b/DNN Platform/DotNetNuke.Log4net/log4net/AssemblyVersionInfo.cs index 3fb82b90563..ba20d3b4054 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/AssemblyVersionInfo.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/AssemblyVersionInfo.cs @@ -1,23 +1,22 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information - -// +// // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at -// +// // http://www.apache.org/licenses/LICENSE-2.0 -// +// // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. -// +// // // Version information for an assembly consists of the following four values: @@ -29,11 +28,11 @@ // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: -[assembly: System.Reflection.AssemblyVersion("3.0.1.0")] +[assembly: System.Reflection.AssemblyVersion("3.0.2.0")] #if !NETCF #if !SSCLI -[assembly: System.Reflection.AssemblyFileVersion("3.0.1.0")] +[assembly: System.Reflection.AssemblyFileVersion("3.0.2.0")] #endif #endif diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Config/AliasDomainAttribute.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Config/AliasDomainAttribute.cs index 452262e289b..44f549aeeae 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Config/AliasDomainAttribute.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Config/AliasDomainAttribute.cs @@ -1,73 +1,71 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -// .NET Compact Framework 1.0 has no support for reading assembly attributes -#if !NETCF - -using System; - -namespace log4net.Config -{ - /// - /// Assembly level attribute that specifies a domain to alias to this assembly's repository. - /// - /// - /// - /// AliasDomainAttribute is obsolete. Use AliasRepositoryAttribute instead of AliasDomainAttribute. - /// - /// - /// An assembly's logger repository is defined by its , - /// however this can be overridden by an assembly loaded before the target assembly. - /// - /// - /// An assembly can alias another assembly's domain to its repository by - /// specifying this attribute with the name of the target domain. - /// - /// - /// This attribute can only be specified on the assembly and may be used - /// as many times as necessary to alias all the required domains. - /// - /// - /// Nicko Cadell. - /// Gert Driesen. - [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] - [Serializable] - [Obsolete("Use AliasRepositoryAttribute instead of AliasDomainAttribute. Scheduled removal in v10.0.0.")] - public sealed class AliasDomainAttribute : AliasRepositoryAttribute +// .NET Compact Framework 1.0 has no support for reading assembly attributes +#if !NETCF + +using System; + +namespace log4net.Config +{ + /// + /// Assembly level attribute that specifies a domain to alias to this assembly's repository. + /// + /// + /// + /// AliasDomainAttribute is obsolete. Use AliasRepositoryAttribute instead of AliasDomainAttribute. + /// + /// + /// An assembly's logger repository is defined by its , + /// however this can be overridden by an assembly loaded before the target assembly. + /// + /// + /// An assembly can alias another assembly's domain to its repository by + /// specifying this attribute with the name of the target domain. + /// + /// + /// This attribute can only be specified on the assembly and may be used + /// as many times as necessary to alias all the required domains. + /// + /// + /// Nicko Cadell + /// Gert Driesen + [AttributeUsage(AttributeTargets.Assembly,AllowMultiple=true)] + [Serializable] + [Obsolete("Use AliasRepositoryAttribute instead of AliasDomainAttribute")] + public sealed class AliasDomainAttribute : AliasRepositoryAttribute { - /// - /// Initializes a new instance of the class with - /// the specified domain to alias to this assembly's repository. - /// - /// The domain to alias to this assembly's repository. - /// - /// - /// Obsolete. Use instead of . - /// - /// - public AliasDomainAttribute(string name) - : base(name) - { + /// + /// Initializes a new instance of the class with + /// the specified domain to alias to this assembly's repository. + /// + /// The domain to alias to this assembly's repository. + /// + /// + /// Obsolete. Use instead of . + /// + /// + public AliasDomainAttribute(string name) : base(name) + { } - } -} - -#endif // !NETCF + } +} + +#endif // !NETCF diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Config/AliasRepositoryAttribute.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Config/AliasRepositoryAttribute.cs index 1ae747522ad..67bbf2c4d2e 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Config/AliasRepositoryAttribute.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Config/AliasRepositoryAttribute.cs @@ -1,92 +1,92 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -// .NET Compact Framework 1.0 has no support for reading assembly attributes -#if !NETCF - -using System; - -namespace log4net.Config -{ - /// - /// Assembly level attribute that specifies a repository to alias to this assembly's repository. - /// - /// - /// - /// An assembly's logger repository is defined by its , - /// however this can be overridden by an assembly loaded before the target assembly. - /// - /// - /// An assembly can alias another assembly's repository to its repository by - /// specifying this attribute with the name of the target repository. - /// - /// - /// This attribute can only be specified on the assembly and may be used - /// as many times as necessary to alias all the required repositories. - /// - /// - /// Nicko Cadell. - /// Gert Driesen. - [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] - [Serializable] - public /*sealed*/ class AliasRepositoryAttribute : Attribute +// .NET Compact Framework 1.0 has no support for reading assembly attributes +#if !NETCF + +using System; + +namespace log4net.Config +{ + /// + /// Assembly level attribute that specifies a repository to alias to this assembly's repository. + /// + /// + /// + /// An assembly's logger repository is defined by its , + /// however this can be overridden by an assembly loaded before the target assembly. + /// + /// + /// An assembly can alias another assembly's repository to its repository by + /// specifying this attribute with the name of the target repository. + /// + /// + /// This attribute can only be specified on the assembly and may be used + /// as many times as necessary to alias all the required repositories. + /// + /// + /// Nicko Cadell + /// Gert Driesen + [AttributeUsage(AttributeTargets.Assembly,AllowMultiple=true)] + [Serializable] + public /*sealed*/ class AliasRepositoryAttribute : Attribute { - // Class is not sealed because AliasDomainAttribute extends it while it is obsoleted // + // Class is not sealed because AliasDomainAttribute extends it while it is obsoleted + // - /// - /// Initializes a new instance of the class with - /// the specified repository to alias to this assembly's repository. - /// - /// The repository to alias to this assembly's repository. - /// - /// - /// Initializes a new instance of the class with - /// the specified repository to alias to this assembly's repository. - /// - /// - public AliasRepositoryAttribute(string name) - { - this.Name = name; + /// + /// Initializes a new instance of the class with + /// the specified repository to alias to this assembly's repository. + /// + /// The repository to alias to this assembly's repository. + /// + /// + /// Initializes a new instance of the class with + /// the specified repository to alias to this assembly's repository. + /// + /// + public AliasRepositoryAttribute(string name) + { + this.Name = name; } - /// - /// Gets or sets the repository to alias to this assembly's repository. - /// - /// - /// The repository to alias to this assemby's repository. - /// - /// - /// - /// The name of the repository to alias to this assembly's repository. - /// - /// - public string Name - { - get { return this.m_name; } - set { this.m_name = value; } + /// + /// Gets or sets the repository to alias to this assembly's repository. + /// + /// + /// The repository to alias to this assemby's repository. + /// + /// + /// + /// The name of the repository to alias to this assembly's repository. + /// + /// + public string Name + { + get { return this.m_name; } + set { this.m_name = value; } } private string m_name = null; - } -} - -#endif // !NETCF + } +} + +#endif // !NETCF diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Config/BasicConfigurator.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Config/BasicConfigurator.cs index 901357b21c3..f1f451e3700 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Config/BasicConfigurator.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Config/BasicConfigurator.cs @@ -1,229 +1,225 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.Config -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; - using System.Collections; - using System.Reflection; - - using log4net.Appender; - using log4net.Layout; - using log4net.Repository; - using log4net.Repository.Hierarchy; - using log4net.Util; - - /// - /// Use this class to quickly configure a . - /// - /// - /// - /// Allows very simple programmatic configuration of log4net. - /// - /// - /// Only one appender can be configured using this configurator. - /// The appender is set at the root of the hierarchy and all logging - /// events will be delivered to that appender. - /// - /// - /// Appenders can also implement the interface. Therefore - /// they would require that the method - /// be called after the appenders properties have been configured. - /// - /// - /// Nicko Cadell. - /// Gert Driesen. - public sealed class BasicConfigurator +using System; +using System.Collections; +#if !NETSTANDARD1_3 +using System.Reflection; +#endif + +using log4net.Appender; +using log4net.Layout; +using log4net.Util; +using log4net.Repository; +using log4net.Repository.Hierarchy; + +namespace log4net.Config +{ + /// + /// Use this class to quickly configure a . + /// + /// + /// + /// Allows very simple programmatic configuration of log4net. + /// + /// + /// Only one appender can be configured using this configurator. + /// The appender is set at the root of the hierarchy and all logging + /// events will be delivered to that appender. + /// + /// + /// Appenders can also implement the interface. Therefore + /// they would require that the method + /// be called after the appenders properties have been configured. + /// + /// + /// Nicko Cadell + /// Gert Driesen + public sealed class BasicConfigurator { - /// - /// The fully qualified type of the BasicConfigurator class. - /// - /// - /// Used by the internal logger to record the Type of the - /// log message. - /// + /// + /// The fully qualified type of the BasicConfigurator class. + /// + /// + /// Used by the internal logger to record the Type of the + /// log message. + /// private static readonly Type declaringType = typeof(BasicConfigurator); - /// - /// Initializes a new instance of the class. - /// - /// - /// - /// Uses a private access modifier to prevent instantiation of this class. - /// - /// - private BasicConfigurator() - { + /// + /// Initializes a new instance of the class. + /// + /// + /// + /// Uses a private access modifier to prevent instantiation of this class. + /// + /// + private BasicConfigurator() + { } -#if !NETSTANDARD1_3 - /// - /// Initializes the log4net system with a default configuration. - /// - /// - /// - /// Initializes the log4net logging system using a - /// that will write to Console.Out. The log messages are - /// formatted using the layout object - /// with the - /// layout style. - /// +#if !NETSTANDARD1_3 + /// + /// Initializes the log4net system with a default configuration. + /// + /// + /// + /// Initializes the log4net logging system using a + /// that will write to Console.Out. The log messages are + /// formatted using the layout object + /// with the + /// layout style. + /// /// - /// - public static ICollection Configure() - { - return BasicConfigurator.Configure(LogManager.GetRepository(Assembly.GetCallingAssembly())); - } - - /// - /// Initializes the log4net system using the specified appenders. - /// - /// The appenders to use to log all logging events. - /// - /// - /// Initializes the log4net system using the specified appenders. - /// + public static ICollection Configure() + { + return Configure(LogManager.GetRepository(Assembly.GetCallingAssembly())); + } + + /// + /// Initializes the log4net system using the specified appenders. + /// + /// The appenders to use to log all logging events. + /// + /// + /// Initializes the log4net system using the specified appenders. + /// /// - /// - public static ICollection Configure(params IAppender[] appenders) - { - ArrayList configurationMessages = new ArrayList(); - - ILoggerRepository repository = LogManager.GetRepository(Assembly.GetCallingAssembly()); - - using (new LogLog.LogReceivedAdapter(configurationMessages)) - { - InternalConfigure(repository, appenders); - } - - repository.ConfigurationMessages = configurationMessages; - - return configurationMessages; - } - - /// - /// Initializes the log4net system using the specified appender. - /// - /// The appender to use to log all logging events. - /// - /// - /// Initializes the log4net system using the specified appender. - /// + public static ICollection Configure(params IAppender[] appenders) + { + ArrayList configurationMessages = new ArrayList(); + + ILoggerRepository repository = LogManager.GetRepository(Assembly.GetCallingAssembly()); + + using (new LogLog.LogReceivedAdapter(configurationMessages)) + { + InternalConfigure(repository, appenders); + } + + repository.ConfigurationMessages = configurationMessages; + + return configurationMessages; + } + + /// + /// Initializes the log4net system using the specified appender. + /// + /// The appender to use to log all logging events. + /// + /// + /// Initializes the log4net system using the specified appender. + /// /// - /// - public static ICollection Configure(IAppender appender) - { - return Configure(new IAppender[] { appender }); - } -#endif // !NETSTANDARD1_3 - - /// - /// Initializes the with a default configuration. - /// - /// The repository to configure. - /// - /// - /// Initializes the specified repository using a - /// that will write to Console.Out. The log messages are - /// formatted using the layout object - /// with the - /// layout style. - /// + public static ICollection Configure(IAppender appender) + { + return Configure(new IAppender[] { appender }); + } +#endif // !NETSTANDARD1_3 + + /// + /// Initializes the with a default configuration. + /// + /// The repository to configure. + /// + /// + /// Initializes the specified repository using a + /// that will write to Console.Out. The log messages are + /// formatted using the layout object + /// with the + /// layout style. + /// /// - /// - public static ICollection Configure(ILoggerRepository repository) - { - ArrayList configurationMessages = new ArrayList(); - - using (new LogLog.LogReceivedAdapter(configurationMessages)) - { - // Create the layout - PatternLayout layout = new PatternLayout(); - layout.ConversionPattern = PatternLayout.DetailConversionPattern; - layout.ActivateOptions(); - - // Create the appender - ConsoleAppender appender = new ConsoleAppender(); - appender.Layout = layout; - appender.ActivateOptions(); - - InternalConfigure(repository, appender); - } - - repository.ConfigurationMessages = configurationMessages; - - return configurationMessages; - } - - /// - /// Initializes the using the specified appender. - /// - /// The repository to configure. - /// The appender to use to log all logging events. - /// - /// - /// Initializes the using the specified appender. - /// + public static ICollection Configure(ILoggerRepository repository) + { + ArrayList configurationMessages = new ArrayList(); + + using (new LogLog.LogReceivedAdapter(configurationMessages)) + { + // Create the layout + PatternLayout layout = new PatternLayout(); + layout.ConversionPattern = PatternLayout.DetailConversionPattern; + layout.ActivateOptions(); + + // Create the appender + ConsoleAppender appender = new ConsoleAppender(); + appender.Layout = layout; + appender.ActivateOptions(); + + InternalConfigure(repository, appender); + } + + repository.ConfigurationMessages = configurationMessages; + + return configurationMessages; + } + + /// + /// Initializes the using the specified appender. + /// + /// The repository to configure. + /// The appender to use to log all logging events. + /// + /// + /// Initializes the using the specified appender. + /// /// - /// - public static ICollection Configure(ILoggerRepository repository, IAppender appender) - { - return Configure(repository, new IAppender[] { appender }); - } - - /// - /// Initializes the using the specified appenders. - /// - /// The repository to configure. - /// The appenders to use to log all logging events. - /// - /// - /// Initializes the using the specified appender. - /// + public static ICollection Configure(ILoggerRepository repository, IAppender appender) + { + return Configure(repository, new IAppender[] { appender }); + } + + /// + /// Initializes the using the specified appenders. + /// + /// The repository to configure. + /// The appenders to use to log all logging events. + /// + /// + /// Initializes the using the specified appender. + /// /// - /// - public static ICollection Configure(ILoggerRepository repository, params IAppender[] appenders) - { - ArrayList configurationMessages = new ArrayList(); - - using (new LogLog.LogReceivedAdapter(configurationMessages)) - { - InternalConfigure(repository, appenders); - } - - repository.ConfigurationMessages = configurationMessages; - - return configurationMessages; - } - - private static void InternalConfigure(ILoggerRepository repository, params IAppender[] appenders) - { - IBasicRepositoryConfigurator configurableRepository = repository as IBasicRepositoryConfigurator; - if (configurableRepository != null) - { - configurableRepository.Configure(appenders); - } - else - { - LogLog.Warn(declaringType, "BasicConfigurator: Repository [" + repository + "] does not support the BasicConfigurator"); - } + public static ICollection Configure(ILoggerRepository repository, params IAppender[] appenders) + { + ArrayList configurationMessages = new ArrayList(); + + using (new LogLog.LogReceivedAdapter(configurationMessages)) + { + InternalConfigure(repository, appenders); + } + + repository.ConfigurationMessages = configurationMessages; + + return configurationMessages; + } + + private static void InternalConfigure(ILoggerRepository repository, params IAppender[] appenders) + { + IBasicRepositoryConfigurator configurableRepository = repository as IBasicRepositoryConfigurator; + if (configurableRepository != null) + { + configurableRepository.Configure(appenders); + } + else + { + LogLog.Warn(declaringType, "BasicConfigurator: Repository [" + repository + "] does not support the BasicConfigurator"); + } } - } -} + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Config/ConfiguratorAttribute.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Config/ConfiguratorAttribute.cs index e3753f59f2f..9d08203b267 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Config/ConfiguratorAttribute.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Config/ConfiguratorAttribute.cs @@ -1,117 +1,114 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -// .NET Compact Framework 1.0 has no support for reading assembly attributes -#if !NETCF - -using System; -using System.Reflection; +// .NET Compact Framework 1.0 has no support for reading assembly attributes +#if !NETCF -using log4net.Repository; - -namespace log4net.Config -{ - /// - /// Base class for all log4net configuration attributes. - /// - /// - /// This is an abstract class that must be extended by - /// specific configurators. This attribute allows the - /// configurator to be parameterized by an assembly level - /// attribute. - /// - /// Nicko Cadell. - /// Gert Driesen. - [AttributeUsage(AttributeTargets.Assembly)] - public abstract class ConfiguratorAttribute : Attribute, IComparable - { +using System; +using System.Reflection; + +using log4net.Repository; + +namespace log4net.Config +{ + /// + /// Base class for all log4net configuration attributes. + /// + /// + /// This is an abstract class that must be extended by + /// specific configurators. This attribute allows the + /// configurator to be parameterized by an assembly level + /// attribute. + /// + /// Nicko Cadell + /// Gert Driesen + [AttributeUsage(AttributeTargets.Assembly)] + public abstract class ConfiguratorAttribute : Attribute, IComparable + { private int m_priority = 0; /// - /// Initializes a new instance of the class. - /// Constructor used by subclasses. - /// - /// the ordering priority for this configurator. - /// - /// - /// The is used to order the configurator - /// attributes before they are invoked. Higher priority configurators are executed - /// before lower priority ones. - /// - /// - protected ConfiguratorAttribute(int priority) - { - this.m_priority = priority; - } - - /// - /// Configures the for the specified assembly. - /// - /// The assembly that this attribute was defined on. - /// The repository to configure. - /// - /// - /// Abstract method implemented by a subclass. When this method is called - /// the subclass should configure the . - /// - /// - public abstract void Configure(Assembly sourceAssembly, ILoggerRepository targetRepository); - - /// - /// Compare this instance to another ConfiguratorAttribute. - /// - /// the object to compare to. - /// see . - /// - /// - /// Compares the priorities of the two instances. - /// Sorts by priority in descending order. Objects with the same priority are - /// randomly ordered. - /// - /// - public int CompareTo(object obj) - { - // Reference equals - if ((object)this == obj) - { - return 0; - } - - int result = -1; - - ConfiguratorAttribute target = obj as ConfiguratorAttribute; - if (target != null) - { - // Compare the priorities - result = target.m_priority.CompareTo(this.m_priority); - if (result == 0) - { - // Same priority, so have to provide some ordering - result = -1; - } - } + /// Constructor used by subclasses. + /// + /// the ordering priority for this configurator + /// + /// + /// The is used to order the configurator + /// attributes before they are invoked. Higher priority configurators are executed + /// before lower priority ones. + /// + /// + protected ConfiguratorAttribute(int priority) + { + this.m_priority = priority; + } + + /// + /// Configures the for the specified assembly. + /// + /// The assembly that this attribute was defined on. + /// The repository to configure. + /// + /// + /// Abstract method implemented by a subclass. When this method is called + /// the subclass should configure the . + /// + /// + public abstract void Configure(Assembly sourceAssembly, ILoggerRepository targetRepository); + + /// + /// Compare this instance to another ConfiguratorAttribute + /// + /// the object to compare to + /// see + /// + /// + /// Compares the priorities of the two instances. + /// Sorts by priority in descending order. Objects with the same priority are + /// randomly ordered. + /// + /// + public int CompareTo(object obj) + { + // Reference equals + if ((object)this == obj) + { + return 0; + } + + int result = -1; + + ConfiguratorAttribute target = obj as ConfiguratorAttribute; + if (target != null) + { + // Compare the priorities + result = target.m_priority.CompareTo(this.m_priority); + if (result == 0) + { + // Same priority, so have to provide some ordering + result = -1; + } + } + return result; + } + } +} - return result; - } - } -} - -#endif //!NETCF +#endif //!NETCF diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Config/DOMConfigurator.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Config/DOMConfigurator.cs index 3b817065f68..4c11230546e 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Config/DOMConfigurator.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Config/DOMConfigurator.cs @@ -1,347 +1,348 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.Config -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; - using System.Collections; - using System.IO; - using System.Reflection; - using System.Threading; - using System.Xml; +#if NET_2_0 // really only because netstandard doesn't understand Assembly.GetCallingAssembly() +using System; +using System.Xml; +using System.Collections; +using System.IO; +using System.Reflection; +using System.Threading; - using log4net.Appender; - using log4net.Repository; - using log4net.Util; +using log4net.Appender; +using log4net.Util; +using log4net.Repository; - /// - /// Use this class to initialize the log4net environment using an Xml tree. - /// - /// - /// - /// DOMConfigurator is obsolete. Use XmlConfigurator instead of DOMConfigurator. - /// - /// - /// Configures a using an Xml tree. - /// - /// - /// Nicko Cadell. - /// Gert Driesen. - [Obsolete("Use XmlConfigurator instead of DOMConfigurator. Scheduled removal in v10.0.0.")] - public sealed class DOMConfigurator +namespace log4net.Config +{ + /// + /// Use this class to initialize the log4net environment using an Xml tree. + /// + /// + /// + /// DOMConfigurator is obsolete. Use XmlConfigurator instead of DOMConfigurator. + /// + /// + /// Configures a using an Xml tree. + /// + /// + /// Nicko Cadell + /// Gert Driesen + [Obsolete("Use XmlConfigurator instead of DOMConfigurator")] + public sealed class DOMConfigurator { /// - /// Initializes a new instance of the class. - /// Private constructor. - /// - private DOMConfigurator() - { + /// Private constructor + /// + private DOMConfigurator() + { } - /// - /// Automatically configures the log4net system based on the - /// application's configuration settings. - /// - /// - /// - /// DOMConfigurator is obsolete. Use XmlConfigurator instead of DOMConfigurator. - /// - /// Each application has a configuration file. This has the - /// same name as the application with '.config' appended. - /// This file is XML and calling this function prompts the - /// configurator to look in that file for a section called - /// log4net that contains the configuration data. - /// - [Obsolete("Use XmlConfigurator.Configure instead of DOMConfigurator.Configure. Scheduled removal in v11.0.0.")] - public static void Configure() - { - XmlConfigurator.Configure(LogManager.GetRepository(Assembly.GetCallingAssembly())); - } - - /// - /// Automatically configures the using settings - /// stored in the application's configuration file. - /// - /// - /// - /// DOMConfigurator is obsolete. Use XmlConfigurator instead of DOMConfigurator. - /// - /// Each application has a configuration file. This has the - /// same name as the application with '.config' appended. - /// This file is XML and calling this function prompts the - /// configurator to look in that file for a section called - /// log4net that contains the configuration data. - /// - /// The repository to configure. - [Obsolete("Use XmlConfigurator.Configure instead of DOMConfigurator.Configure. Scheduled removal in v10.0.0.")] - public static void Configure(ILoggerRepository repository) - { - XmlConfigurator.Configure(repository); - } - - /// - /// Configures log4net using a log4net element. - /// - /// - /// - /// DOMConfigurator is obsolete. Use XmlConfigurator instead of DOMConfigurator. - /// - /// Loads the log4net configuration from the XML element - /// supplied as . - /// - /// The element to parse. - [Obsolete("Use XmlConfigurator.Configure instead of DOMConfigurator.Configure. Scheduled removal in v10.0.0.")] - public static void Configure(XmlElement element) - { - XmlConfigurator.Configure(LogManager.GetRepository(Assembly.GetCallingAssembly()), element); - } - - /// - /// Configures the using the specified XML - /// element. - /// - /// - /// - /// DOMConfigurator is obsolete. Use XmlConfigurator instead of DOMConfigurator. - /// - /// Loads the log4net configuration from the XML element - /// supplied as . - /// - /// The repository to configure. - /// The element to parse. - [Obsolete("Use XmlConfigurator.Configure instead of DOMConfigurator.Configure. Scheduled removal in v10.0.0.")] - public static void Configure(ILoggerRepository repository, XmlElement element) - { - XmlConfigurator.Configure(repository, element); - } - - /// - /// Configures log4net using the specified configuration file. - /// - /// The XML file to load the configuration from. - /// - /// - /// DOMConfigurator is obsolete. Use XmlConfigurator instead of DOMConfigurator. - /// - /// - /// The configuration file must be valid XML. It must contain - /// at least one element called log4net that holds - /// the log4net configuration data. - /// - /// - /// The log4net configuration file can possible be specified in the application's - /// configuration file (either MyAppName.exe.config for a - /// normal application on Web.config for an ASP.NET application). - /// - /// - /// The following example configures log4net using a configuration file, of which the - /// location is stored in the application's configuration file : - /// - /// - /// using log4net.Config; - /// using System.IO; - /// using System.Configuration; - /// - /// ... - /// - /// DOMConfigurator.Configure(new FileInfo(ConfigurationSettings.AppSettings["log4net-config-file"])); - /// - /// - /// In the .config file, the path to the log4net can be specified like this : - /// - /// - /// - /// - /// - /// - /// - /// - /// - [Obsolete("Use XmlConfigurator.Configure instead of DOMConfigurator.Configure. Scheduled removal in v10.0.0.")] - public static void Configure(FileInfo configFile) - { - XmlConfigurator.Configure(LogManager.GetRepository(Assembly.GetCallingAssembly()), configFile); - } - - /// - /// Configures log4net using the specified configuration file. - /// - /// A stream to load the XML configuration from. - /// - /// - /// DOMConfigurator is obsolete. Use XmlConfigurator instead of DOMConfigurator. - /// - /// - /// The configuration data must be valid XML. It must contain - /// at least one element called log4net that holds - /// the log4net configuration data. - /// - /// - /// Note that this method will NOT close the stream parameter. - /// - /// - [Obsolete("Use XmlConfigurator.Configure instead of DOMConfigurator.Configure. Scheduled removal in v10.0.0.")] - public static void Configure(Stream configStream) - { - XmlConfigurator.Configure(LogManager.GetRepository(Assembly.GetCallingAssembly()), configStream); - } - - /// - /// Configures the using the specified configuration - /// file. - /// - /// The repository to configure. - /// The XML file to load the configuration from. - /// - /// - /// DOMConfigurator is obsolete. Use XmlConfigurator instead of DOMConfigurator. - /// - /// - /// The configuration file must be valid XML. It must contain - /// at least one element called log4net that holds - /// the configuration data. - /// - /// - /// The log4net configuration file can possible be specified in the application's - /// configuration file (either MyAppName.exe.config for a - /// normal application on Web.config for an ASP.NET application). - /// - /// - /// The following example configures log4net using a configuration file, of which the - /// location is stored in the application's configuration file : - /// - /// - /// using log4net.Config; - /// using System.IO; - /// using System.Configuration; - /// - /// ... - /// - /// DOMConfigurator.Configure(new FileInfo(ConfigurationSettings.AppSettings["log4net-config-file"])); - /// - /// - /// In the .config file, the path to the log4net can be specified like this : - /// - /// - /// - /// - /// - /// - /// - /// - /// - [Obsolete("Use XmlConfigurator.Configure instead of DOMConfigurator.Configure. Scheduled removal in v10.0.0.")] - public static void Configure(ILoggerRepository repository, FileInfo configFile) - { - XmlConfigurator.Configure(repository, configFile); - } + /// + /// Automatically configures the log4net system based on the + /// application's configuration settings. + /// + /// + /// + /// DOMConfigurator is obsolete. Use XmlConfigurator instead of DOMConfigurator. + /// + /// Each application has a configuration file. This has the + /// same name as the application with '.config' appended. + /// This file is XML and calling this function prompts the + /// configurator to look in that file for a section called + /// log4net that contains the configuration data. + /// + [Obsolete("Use XmlConfigurator.Configure instead of DOMConfigurator.Configure")] + public static void Configure() + { + XmlConfigurator.Configure(LogManager.GetRepository(Assembly.GetCallingAssembly())); + } - /// - /// Configures the using the specified configuration - /// file. - /// - /// The repository to configure. - /// The stream to load the XML configuration from. - /// - /// - /// DOMConfigurator is obsolete. Use XmlConfigurator instead of DOMConfigurator. - /// - /// - /// The configuration data must be valid XML. It must contain - /// at least one element called log4net that holds - /// the configuration data. - /// - /// - /// Note that this method will NOT close the stream parameter. - /// - /// - [Obsolete("Use XmlConfigurator.Configure instead of DOMConfigurator.Configure. Scheduled removal in v10.0.0.")] - public static void Configure(ILoggerRepository repository, Stream configStream) - { - XmlConfigurator.Configure(repository, configStream); + /// + /// Automatically configures the using settings + /// stored in the application's configuration file. + /// + /// + /// + /// DOMConfigurator is obsolete. Use XmlConfigurator instead of DOMConfigurator. + /// + /// Each application has a configuration file. This has the + /// same name as the application with '.config' appended. + /// This file is XML and calling this function prompts the + /// configurator to look in that file for a section called + /// log4net that contains the configuration data. + /// + /// The repository to configure. + [Obsolete("Use XmlConfigurator.Configure instead of DOMConfigurator.Configure")] + public static void Configure(ILoggerRepository repository) + { + XmlConfigurator.Configure(repository); } -#if !NETCF && !SSCLI + /// + /// Configures log4net using a log4net element + /// + /// + /// + /// DOMConfigurator is obsolete. Use XmlConfigurator instead of DOMConfigurator. + /// + /// Loads the log4net configuration from the XML element + /// supplied as . + /// + /// The element to parse. + [Obsolete("Use XmlConfigurator.Configure instead of DOMConfigurator.Configure")] + public static void Configure(XmlElement element) + { + XmlConfigurator.Configure(LogManager.GetRepository(Assembly.GetCallingAssembly()), element); + } - /// - /// Configures log4net using the file specified, monitors the file for changes - /// and reloads the configuration if a change is detected. - /// - /// The XML file to load the configuration from. - /// - /// - /// DOMConfigurator is obsolete. Use XmlConfigurator instead of DOMConfigurator. - /// - /// - /// The configuration file must be valid XML. It must contain - /// at least one element called log4net that holds - /// the configuration data. - /// - /// - /// The configuration file will be monitored using a - /// and depends on the behavior of that class. - /// - /// - /// For more information on how to configure log4net using - /// a separate configuration file, see . - /// - /// - /// - [Obsolete("Use XmlConfigurator.ConfigureAndWatch instead of DOMConfigurator.ConfigureAndWatch. Scheduled removal in v10.0.0.")] - public static void ConfigureAndWatch(FileInfo configFile) - { - XmlConfigurator.ConfigureAndWatch(LogManager.GetRepository(Assembly.GetCallingAssembly()), configFile); - } - - /// - /// Configures the using the file specified, - /// monitors the file for changes and reloads the configuration if a change - /// is detected. - /// - /// The repository to configure. - /// The XML file to load the configuration from. - /// - /// - /// DOMConfigurator is obsolete. Use XmlConfigurator instead of DOMConfigurator. - /// - /// - /// The configuration file must be valid XML. It must contain - /// at least one element called log4net that holds - /// the configuration data. - /// - /// - /// The configuration file will be monitored using a - /// and depends on the behavior of that class. - /// - /// - /// For more information on how to configure log4net using - /// a separate configuration file, see . - /// - /// - /// - [Obsolete("Use XmlConfigurator.ConfigureAndWatch instead of DOMConfigurator.ConfigureAndWatch. Scheduled removal in v10.0.0.")] - public static void ConfigureAndWatch(ILoggerRepository repository, FileInfo configFile) - { - XmlConfigurator.ConfigureAndWatch(repository, configFile); + /// + /// Configures the using the specified XML + /// element. + /// + /// + /// + /// DOMConfigurator is obsolete. Use XmlConfigurator instead of DOMConfigurator. + /// + /// Loads the log4net configuration from the XML element + /// supplied as . + /// + /// The repository to configure. + /// The element to parse. + [Obsolete("Use XmlConfigurator.Configure instead of DOMConfigurator.Configure")] + public static void Configure(ILoggerRepository repository, XmlElement element) + { + XmlConfigurator.Configure(repository, element); } -#endif - } + /// + /// Configures log4net using the specified configuration file. + /// + /// The XML file to load the configuration from. + /// + /// + /// DOMConfigurator is obsolete. Use XmlConfigurator instead of DOMConfigurator. + /// + /// + /// The configuration file must be valid XML. It must contain + /// at least one element called log4net that holds + /// the log4net configuration data. + /// + /// + /// The log4net configuration file can possible be specified in the application's + /// configuration file (either MyAppName.exe.config for a + /// normal application on Web.config for an ASP.NET application). + /// + /// + /// The following example configures log4net using a configuration file, of which the + /// location is stored in the application's configuration file : + /// + /// + /// using log4net.Config; + /// using System.IO; + /// using System.Configuration; + /// + /// ... + /// + /// DOMConfigurator.Configure(new FileInfo(ConfigurationSettings.AppSettings["log4net-config-file"])); + /// + /// + /// In the .config file, the path to the log4net can be specified like this : + /// + /// + /// + /// + /// + /// + /// + /// + /// + [Obsolete("Use XmlConfigurator.Configure instead of DOMConfigurator.Configure")] + public static void Configure(FileInfo configFile) + { + XmlConfigurator.Configure(LogManager.GetRepository(Assembly.GetCallingAssembly()), configFile); + } + + /// + /// Configures log4net using the specified configuration file. + /// + /// A stream to load the XML configuration from. + /// + /// + /// DOMConfigurator is obsolete. Use XmlConfigurator instead of DOMConfigurator. + /// + /// + /// The configuration data must be valid XML. It must contain + /// at least one element called log4net that holds + /// the log4net configuration data. + /// + /// + /// Note that this method will NOT close the stream parameter. + /// + /// + [Obsolete("Use XmlConfigurator.Configure instead of DOMConfigurator.Configure")] + public static void Configure(Stream configStream) + { + XmlConfigurator.Configure(LogManager.GetRepository(Assembly.GetCallingAssembly()), configStream); + } + + /// + /// Configures the using the specified configuration + /// file. + /// + /// The repository to configure. + /// The XML file to load the configuration from. + /// + /// + /// DOMConfigurator is obsolete. Use XmlConfigurator instead of DOMConfigurator. + /// + /// + /// The configuration file must be valid XML. It must contain + /// at least one element called log4net that holds + /// the configuration data. + /// + /// + /// The log4net configuration file can possible be specified in the application's + /// configuration file (either MyAppName.exe.config for a + /// normal application on Web.config for an ASP.NET application). + /// + /// + /// The following example configures log4net using a configuration file, of which the + /// location is stored in the application's configuration file : + /// + /// + /// using log4net.Config; + /// using System.IO; + /// using System.Configuration; + /// + /// ... + /// + /// DOMConfigurator.Configure(new FileInfo(ConfigurationSettings.AppSettings["log4net-config-file"])); + /// + /// + /// In the .config file, the path to the log4net can be specified like this : + /// + /// + /// + /// + /// + /// + /// + /// + /// + [Obsolete("Use XmlConfigurator.Configure instead of DOMConfigurator.Configure")] + public static void Configure(ILoggerRepository repository, FileInfo configFile) + { + XmlConfigurator.Configure(repository, configFile); + } + + + /// + /// Configures the using the specified configuration + /// file. + /// + /// The repository to configure. + /// The stream to load the XML configuration from. + /// + /// + /// DOMConfigurator is obsolete. Use XmlConfigurator instead of DOMConfigurator. + /// + /// + /// The configuration data must be valid XML. It must contain + /// at least one element called log4net that holds + /// the configuration data. + /// + /// + /// Note that this method will NOT close the stream parameter. + /// + /// + [Obsolete("Use XmlConfigurator.Configure instead of DOMConfigurator.Configure")] + public static void Configure(ILoggerRepository repository, Stream configStream) + { + XmlConfigurator.Configure(repository, configStream); + } + +#if (!NETCF && !SSCLI) + + /// + /// Configures log4net using the file specified, monitors the file for changes + /// and reloads the configuration if a change is detected. + /// + /// The XML file to load the configuration from. + /// + /// + /// DOMConfigurator is obsolete. Use XmlConfigurator instead of DOMConfigurator. + /// + /// + /// The configuration file must be valid XML. It must contain + /// at least one element called log4net that holds + /// the configuration data. + /// + /// + /// The configuration file will be monitored using a + /// and depends on the behavior of that class. + /// + /// + /// For more information on how to configure log4net using + /// a separate configuration file, see . + /// + /// + /// + [Obsolete("Use XmlConfigurator.ConfigureAndWatch instead of DOMConfigurator.ConfigureAndWatch")] + public static void ConfigureAndWatch(FileInfo configFile) + { + XmlConfigurator.ConfigureAndWatch(LogManager.GetRepository(Assembly.GetCallingAssembly()), configFile); + } + + /// + /// Configures the using the file specified, + /// monitors the file for changes and reloads the configuration if a change + /// is detected. + /// + /// The repository to configure. + /// The XML file to load the configuration from. + /// + /// + /// DOMConfigurator is obsolete. Use XmlConfigurator instead of DOMConfigurator. + /// + /// + /// The configuration file must be valid XML. It must contain + /// at least one element called log4net that holds + /// the configuration data. + /// + /// + /// The configuration file will be monitored using a + /// and depends on the behavior of that class. + /// + /// + /// For more information on how to configure log4net using + /// a separate configuration file, see . + /// + /// + /// + [Obsolete("Use XmlConfigurator.ConfigureAndWatch instead of DOMConfigurator.ConfigureAndWatch")] + public static void ConfigureAndWatch(ILoggerRepository repository, FileInfo configFile) + { + XmlConfigurator.ConfigureAndWatch(repository, configFile); + } +#endif + } } +#endif // NET_2_0 diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Config/DOMConfiguratorAttribute.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Config/DOMConfiguratorAttribute.cs index 200d2d16e37..fa514fd6592 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Config/DOMConfiguratorAttribute.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Config/DOMConfiguratorAttribute.cs @@ -1,62 +1,61 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -// .NET Compact Framework 1.0 has no support for reading assembly attributes -#if !NETCF - -using System; -using System.IO; -using System.Reflection; +// .NET Compact Framework 1.0 has no support for reading assembly attributes +#if !NETCF -using log4net.Repository; -using log4net.Repository.Hierarchy; -using log4net.Util; - -namespace log4net.Config -{ - /// - /// Assembly level attribute to configure the . - /// - /// - /// - /// AliasDomainAttribute is obsolete. Use AliasRepositoryAttribute instead of AliasDomainAttribute. - /// - /// - /// This attribute may only be used at the assembly scope and can only - /// be used once per assembly. - /// - /// - /// Use this attribute to configure the - /// without calling one of the - /// methods. - /// - /// - /// Nicko Cadell. - /// Gert Driesen. - [AttributeUsage(AttributeTargets.Assembly)] - [Serializable] - [Obsolete("Use XmlConfiguratorAttribute instead of DOMConfiguratorAttribute. Scheduled removal in v10.0.0.")] - public sealed class DOMConfiguratorAttribute : XmlConfiguratorAttribute - { - } -} - -#endif // !NETCF +using System; +using System.Reflection; +using System.IO; + +using log4net.Util; +using log4net.Repository; +using log4net.Repository.Hierarchy; + +namespace log4net.Config +{ + /// + /// Assembly level attribute to configure the . + /// + /// + /// + /// AliasDomainAttribute is obsolete. Use AliasRepositoryAttribute instead of AliasDomainAttribute. + /// + /// + /// This attribute may only be used at the assembly scope and can only + /// be used once per assembly. + /// + /// + /// Use this attribute to configure the + /// without calling one of the + /// methods. + /// + /// + /// Nicko Cadell + /// Gert Driesen + [AttributeUsage(AttributeTargets.Assembly)] + [Serializable] + [Obsolete("Use XmlConfiguratorAttribute instead of DOMConfiguratorAttribute")] + public sealed class DOMConfiguratorAttribute : XmlConfiguratorAttribute + { + } +} + +#endif // !NETCF diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Config/DomainAttribute.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Config/DomainAttribute.cs index 72f7c5c6688..232f66bea51 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Config/DomainAttribute.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Config/DomainAttribute.cs @@ -1,88 +1,84 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -// .NET Compact Framework 1.0 has no support for reading assembly attributes -#if !NETCF - -using System; - -namespace log4net.Config -{ - /// - /// Assembly level attribute that specifies the logging domain for the assembly. - /// - /// - /// - /// DomainAttribute is obsolete. Use RepositoryAttribute instead of DomainAttribute. - /// - /// - /// Assemblies are mapped to logging domains. Each domain has its own - /// logging repository. This attribute specified on the assembly controls - /// the configuration of the domain. The property specifies the name - /// of the domain that this assembly is a part of. The - /// specifies the type of the repository objects to create for the domain. If - /// this attribute is not specified and a is not specified - /// then the assembly will be part of the default shared logging domain. - /// - /// - /// This attribute can only be specified on the assembly and may only be used - /// once per assembly. - /// - /// - /// Nicko Cadell. - /// Gert Driesen. - [AttributeUsage(AttributeTargets.Assembly)] - [Serializable] - [Obsolete("Use RepositoryAttribute instead of DomainAttribute. Scheduled removal in v10.0.0.")] - public sealed class DomainAttribute : RepositoryAttribute +// .NET Compact Framework 1.0 has no support for reading assembly attributes +#if !NETCF + +using System; + +namespace log4net.Config +{ + /// + /// Assembly level attribute that specifies the logging domain for the assembly. + /// + /// + /// + /// DomainAttribute is obsolete. Use RepositoryAttribute instead of DomainAttribute. + /// + /// + /// Assemblies are mapped to logging domains. Each domain has its own + /// logging repository. This attribute specified on the assembly controls + /// the configuration of the domain. The property specifies the name + /// of the domain that this assembly is a part of. The + /// specifies the type of the repository objects to create for the domain. If + /// this attribute is not specified and a is not specified + /// then the assembly will be part of the default shared logging domain. + /// + /// + /// This attribute can only be specified on the assembly and may only be used + /// once per assembly. + /// + /// + /// Nicko Cadell + /// Gert Driesen + [AttributeUsage(AttributeTargets.Assembly)] + [Serializable] + [Obsolete("Use RepositoryAttribute instead of DomainAttribute")] + public sealed class DomainAttribute : RepositoryAttribute { - /// - /// Initializes a new instance of the class. - /// - /// - /// - /// Obsolete. Use RepositoryAttribute instead of DomainAttribute. - /// - /// - public DomainAttribute() - : base() - { + /// + /// Initializes a new instance of the class. + /// + /// + /// + /// Obsolete. Use RepositoryAttribute instead of DomainAttribute. + /// + /// + public DomainAttribute() : base() + { } /// - /// Initializes a new instance of the class. - /// Initialize a new instance of the class - /// with the name of the domain. - /// - /// The name of the domain. - /// - /// - /// Obsolete. Use RepositoryAttribute instead of DomainAttribute. - /// - /// - public DomainAttribute(string name) - : base(name) - { + /// Initialize a new instance of the class + /// with the name of the domain. + /// + /// The name of the domain. + /// + /// + /// Obsolete. Use RepositoryAttribute instead of DomainAttribute. + /// + /// + public DomainAttribute(string name) : base(name) + { } - } -} - -#endif // !NETCF + } +} + +#endif // !NETCF diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Config/Log4NetConfigurationSectionHandler.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Config/Log4NetConfigurationSectionHandler.cs index af821518abb..41f3e365a5c 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Config/Log4NetConfigurationSectionHandler.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Config/Log4NetConfigurationSectionHandler.cs @@ -1,86 +1,87 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -// .NET Compact Framework 1.0 has no support for application .config files -#if !NETCF - -using System.Configuration; -using System.Xml; - -namespace log4net.Config -{ - /// - /// Class to register for the log4net section of the configuration file. - /// - /// - /// The log4net section of the configuration file needs to have a section - /// handler registered. This is the section handler used. It simply returns - /// the XML element that is the root of the section. - /// - /// - /// Example of registering the log4net section handler : - /// - /// - /// - ///
- /// - /// - /// log4net configuration XML goes here - /// - /// - /// - /// - /// Nicko Cadell. - /// Gert Driesen. - public class Log4NetConfigurationSectionHandler : IConfigurationSectionHandler +#if NET_2_0 || NETSTANDARD2_0 +// .NET Compact Framework 1.0 has no support for application .config files +#if !NETCF + +using System.Configuration; +using System.Xml; + +namespace log4net.Config +{ + /// + /// Class to register for the log4net section of the configuration file + /// + /// + /// The log4net section of the configuration file needs to have a section + /// handler registered. This is the section handler used. It simply returns + /// the XML element that is the root of the section. + /// + /// + /// Example of registering the log4net section handler : + /// + /// + /// + ///
+ /// + /// + /// log4net configuration XML goes here + /// + /// + /// + /// + /// Nicko Cadell + /// Gert Driesen + public class Log4NetConfigurationSectionHandler : IConfigurationSectionHandler { - /// - /// Initializes a new instance of the class. - /// - /// - /// - /// Default constructor. - /// - /// - public Log4NetConfigurationSectionHandler() - { + /// + /// Initializes a new instance of the class. + /// + /// + /// + /// Default constructor. + /// + /// + public Log4NetConfigurationSectionHandler() + { } - /// - /// Parses the configuration section. - /// - /// The configuration settings in a corresponding parent configuration section. - /// The configuration context when called from the ASP.NET configuration system. Otherwise, this parameter is reserved and is a null reference. - /// The for the log4net section. - /// The for the log4net section. - /// - /// - /// Returns the containing the configuration data. - /// - /// - public object Create(object parent, object configContext, XmlNode section) - { - return section; + /// + /// Parses the configuration section. + /// + /// The configuration settings in a corresponding parent configuration section. + /// The configuration context when called from the ASP.NET configuration system. Otherwise, this parameter is reserved and is a null reference. + /// The for the log4net section. + /// The for the log4net section. + /// + /// + /// Returns the containing the configuration data, + /// + /// + public object Create(object parent, object configContext, XmlNode section) + { + return section; } - } -} - -#endif // !NETCF + } +} + +#endif // !NETCF +#endif // NET_2_0 || NETSTANDARD2_0 diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Config/PluginAttribute.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Config/PluginAttribute.cs index 4619efa162d..879522b628b 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Config/PluginAttribute.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Config/PluginAttribute.cs @@ -1,182 +1,179 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -// .NET Compact Framework 1.0 has no support for reading assembly attributes -#if !NETCF - -using System; -using System.Globalization; -using System.Reflection; +// .NET Compact Framework 1.0 has no support for reading assembly attributes +#if !NETCF -using log4net.Core; -using log4net.Plugin; -using log4net.Util; - -namespace log4net.Config -{ - /// - /// Assembly level attribute that specifies a plugin to attach to - /// the repository. - /// - /// - /// - /// Specifies the type of a plugin to create and attach to the - /// assembly's repository. The plugin type must implement the - /// interface. - /// - /// - /// Nicko Cadell. - /// Gert Driesen. - [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] - [Serializable] - public sealed class PluginAttribute : Attribute, IPluginFactory +using System; + +using log4net.Core; +#if !NETSTANDARD1_3 +using log4net.Util; +#endif +using log4net.Plugin; + +namespace log4net.Config +{ + /// + /// Assembly level attribute that specifies a plugin to attach to + /// the repository. + /// + /// + /// + /// Specifies the type of a plugin to create and attach to the + /// assembly's repository. The plugin type must implement the + /// interface. + /// + /// + /// Nicko Cadell + /// Gert Driesen + [AttributeUsage(AttributeTargets.Assembly,AllowMultiple=true)] + [Serializable] + public sealed class PluginAttribute : Attribute, IPluginFactory { -#if !NETSTANDARD1_3 // Excluded because GetCallingAssembly() is not available in CoreFX (https://github.com/dotnet/corefx/issues/2221). - /// - /// Initializes a new instance of the class - /// with the specified type. - /// - /// The type name of plugin to create. - /// - /// - /// Create the attribute with the plugin type specified. - /// - /// - /// Where possible use the constructor that takes a . - /// - /// - public PluginAttribute(string typeName) - { - this.m_typeName = typeName; - } -#endif - - /// - /// Initializes a new instance of the class - /// with the specified type. - /// - /// The type of plugin to create. - /// - /// - /// Create the attribute with the plugin type specified. - /// - /// - public PluginAttribute(Type type) - { - this.m_type = type; +#if !NETSTANDARD1_3 // Excluded because GetCallingAssembly() is not available in CoreFX (https://github.com/dotnet/corefx/issues/2221). + /// + /// Initializes a new instance of the class + /// with the specified type. + /// + /// The type name of plugin to create. + /// + /// + /// Create the attribute with the plugin type specified. + /// + /// + /// Where possible use the constructor that takes a . + /// + /// + public PluginAttribute(string typeName) + { + this.m_typeName = typeName; } +#endif - /// - /// Gets or sets the type for the plugin. - /// - /// - /// The type for the plugin. - /// - /// - /// - /// The type for the plugin. - /// - /// - public Type Type - { - get { return this.m_type; } - set { this.m_type = value; } - } - - /// - /// Gets or sets the type name for the plugin. - /// - /// - /// The type name for the plugin. - /// - /// - /// - /// The type name for the plugin. - /// - /// - /// Where possible use the property instead. - /// - /// - public string TypeName - { - get { return this.m_typeName; } - set { this.m_typeName = value; } + /// + /// Initializes a new instance of the class + /// with the specified type. + /// + /// The type of plugin to create. + /// + /// + /// Create the attribute with the plugin type specified. + /// + /// + public PluginAttribute(Type type) + { + this.m_type = type; } - /// - /// Creates the plugin object defined by this attribute. - /// - /// - /// - /// Creates the instance of the object as - /// specified by this attribute. - /// - /// - /// The plugin object. - public IPlugin CreatePlugin() - { - Type pluginType = this.m_type; -#if !NETSTANDARD1_3 - if (this.m_type == null) - { - // Get the plugin object type from the string type name - pluginType = SystemInfo.GetTypeFromString(this.m_typeName, true, true); - } -#endif + /// + /// Gets or sets the type for the plugin. + /// + /// + /// The type for the plugin. + /// + /// + /// + /// The type for the plugin. + /// + /// + public Type Type + { + get { return this.m_type; } + set { this.m_type = value ; } + } - // Check that the type is a plugin - if (!typeof(IPlugin).IsAssignableFrom(pluginType)) - { - throw new LogException("Plugin type [" + pluginType.FullName + "] does not implement the log4net.IPlugin interface"); - } - - // Create an instance of the plugin using the default constructor - IPlugin plugin = (IPlugin)Activator.CreateInstance(pluginType); - - return plugin; + /// + /// Gets or sets the type name for the plugin. + /// + /// + /// The type name for the plugin. + /// + /// + /// + /// The type name for the plugin. + /// + /// + /// Where possible use the property instead. + /// + /// + public string TypeName + { + get { return this.m_typeName; } + set { this.m_typeName = value ; } } - /// - /// Returns a representation of the properties of this object. - /// - /// - /// - /// Overrides base class method to - /// return a representation of the properties of this object. - /// - /// - /// A representation of the properties of this object. - public override string ToString() - { - if (this.m_type != null) - { - return "PluginAttribute[Type=" + this.m_type.FullName + "]"; - } + /// + /// Creates the plugin object defined by this attribute. + /// + /// + /// + /// Creates the instance of the object as + /// specified by this attribute. + /// + /// + /// The plugin object. + public IPlugin CreatePlugin() + { + Type pluginType = this.m_type; +#if !NETSTANDARD1_3 + if (this.m_type == null) + { + // Get the plugin object type from the string type name + pluginType = SystemInfo.GetTypeFromString(this.m_typeName, true, true); + } +#endif + // Check that the type is a plugin + if (!(typeof(IPlugin).IsAssignableFrom(pluginType))) + { + throw new LogException("Plugin type [" + pluginType.FullName + "] does not implement the log4net.IPlugin interface"); + } + + // Create an instance of the plugin using the default constructor + IPlugin plugin = (IPlugin)Activator.CreateInstance(pluginType); - return "PluginAttribute[Type=" + this.m_typeName + "]"; + return plugin; } - private string m_typeName = null; + /// + /// Returns a representation of the properties of this object. + /// + /// + /// + /// Overrides base class method to + /// return a representation of the properties of this object. + /// + /// + /// A representation of the properties of this object + public override string ToString() + { + if (this.m_type != null) + { + return "PluginAttribute[Type=" + this.m_type.FullName + "]"; + } + return "PluginAttribute[Type=" + this.m_typeName + "]"; + } + + private string m_typeName = null; private Type m_type = null; - } -} - -#endif // !NETCF + } +} + +#endif // !NETCF diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Config/RepositoryAttribute.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Config/RepositoryAttribute.cs index e914543c1fe..6ad79542eed 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Config/RepositoryAttribute.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Config/RepositoryAttribute.cs @@ -1,134 +1,133 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -// .NET Compact Framework 1.0 has no support for reading assembly attributes -#if !NETCF - -using System; - -namespace log4net.Config -{ - /// - /// Assembly level attribute that specifies the logging repository for the assembly. - /// - /// - /// - /// Assemblies are mapped to logging repository. This attribute specified - /// on the assembly controls - /// the configuration of the repository. The property specifies the name - /// of the repository that this assembly is a part of. The - /// specifies the type of the object - /// to create for the assembly. If this attribute is not specified or a - /// is not specified then the assembly will be part of the default shared logging repository. - /// - /// - /// This attribute can only be specified on the assembly and may only be used - /// once per assembly. - /// - /// - /// Nicko Cadell. - /// Gert Driesen. - [AttributeUsage(AttributeTargets.Assembly)] - [Serializable] - public /*sealed*/ class RepositoryAttribute : Attribute +// .NET Compact Framework 1.0 has no support for reading assembly attributes +#if !NETCF + +using System; + +namespace log4net.Config +{ + /// + /// Assembly level attribute that specifies the logging repository for the assembly. + /// + /// + /// + /// Assemblies are mapped to logging repository. This attribute specified + /// on the assembly controls + /// the configuration of the repository. The property specifies the name + /// of the repository that this assembly is a part of. The + /// specifies the type of the object + /// to create for the assembly. If this attribute is not specified or a + /// is not specified then the assembly will be part of the default shared logging repository. + /// + /// + /// This attribute can only be specified on the assembly and may only be used + /// once per assembly. + /// + /// + /// Nicko Cadell + /// Gert Driesen + [AttributeUsage(AttributeTargets.Assembly)] + [Serializable] + public /*sealed*/ class RepositoryAttribute : Attribute { - // Class is not sealed because DomainAttribute extends it while it is obsoleted // + // Class is not sealed because DomainAttribute extends it while it is obsoleted + // + + /// + /// Initializes a new instance of the class. + /// + /// + /// + /// Default constructor. + /// + /// + public RepositoryAttribute() + { + } - /// - /// Initializes a new instance of the class. - /// - /// - /// - /// Default constructor. - /// - /// - public RepositoryAttribute() - { + /// + /// Initialize a new instance of the class + /// with the name of the repository. + /// + /// The name of the repository. + /// + /// + /// Initialize the attribute with the name for the assembly's repository. + /// + /// + public RepositoryAttribute(string name) + { + this.m_name = name; } /// - /// Initializes a new instance of the class. - /// Initialize a new instance of the class - /// with the name of the repository. - /// - /// The name of the repository. - /// - /// - /// Initialize the attribute with the name for the assembly's repository. - /// - /// - public RepositoryAttribute(string name) - { - this.m_name = name; + /// Gets or sets the name of the logging repository. + /// + /// + /// The string name to use as the name of the repository associated with this + /// assembly. + /// + /// + /// + /// This value does not have to be unique. Several assemblies can share the + /// same repository. They will share the logging configuration of the repository. + /// + /// + public string Name + { + get { return this.m_name; } + set { this.m_name = value ; } } - /// - /// Gets or sets the name of the logging repository. - /// - /// - /// The string name to use as the name of the repository associated with this - /// assembly. - /// - /// - /// - /// This value does not have to be unique. Several assemblies can share the - /// same repository. They will share the logging configuration of the repository. - /// - /// - public string Name - { - get { return this.m_name; } - set { this.m_name = value; } - } - - /// - /// Gets or sets the type of repository to create for this assembly. - /// - /// - /// The type of repository to create for this assembly. - /// - /// - /// - /// The type of the repository to create for the assembly. - /// The type must implement the - /// interface. - /// - /// - /// This will be the type of repository created when - /// the repository is created. If multiple assemblies reference the - /// same repository then the repository is only created once using the - /// of the first assembly to call into the - /// repository. - /// - /// - public Type RepositoryType - { - get { return this.m_repositoryType; } - set { this.m_repositoryType = value; } + /// + /// Gets or sets the type of repository to create for this assembly. + /// + /// + /// The type of repository to create for this assembly. + /// + /// + /// + /// The type of the repository to create for the assembly. + /// The type must implement the + /// interface. + /// + /// + /// This will be the type of repository created when + /// the repository is created. If multiple assemblies reference the + /// same repository then the repository is only created once using the + /// of the first assembly to call into the + /// repository. + /// + /// + public Type RepositoryType + { + get { return this.m_repositoryType; } + set { this.m_repositoryType = value ; } } - private string m_name = null; + private string m_name = null; private Type m_repositoryType = null; - } -} - -#endif // !NETCF + } +} + +#endif // !NETCF diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Config/SecurityContextProviderAttribute.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Config/SecurityContextProviderAttribute.cs index 33e2fb30e56..89f7689c7c3 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Config/SecurityContextProviderAttribute.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Config/SecurityContextProviderAttribute.cs @@ -1,135 +1,132 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -// .NET Compact Framework 1.0 has no support for reading assembly attributes -#if !NETCF - -using System; -using System.Reflection; +// .NET Compact Framework 1.0 has no support for reading assembly attributes +#if !NETCF -using log4net.Core; -using log4net.Repository; -using log4net.Util; - -namespace log4net.Config -{ - /// - /// Assembly level attribute to configure the . - /// - /// - /// - /// This attribute may only be used at the assembly scope and can only - /// be used once per assembly. - /// - /// - /// Use this attribute to configure the - /// without calling one of the - /// methods. - /// - /// - /// Nicko Cadell. - [AttributeUsage(AttributeTargets.Assembly)] - [Serializable] - public sealed class SecurityContextProviderAttribute : ConfiguratorAttribute +using System; +using System.Reflection; + +using log4net.Util; +using log4net.Repository; +using log4net.Core; + +namespace log4net.Config +{ + /// + /// Assembly level attribute to configure the . + /// + /// + /// + /// This attribute may only be used at the assembly scope and can only + /// be used once per assembly. + /// + /// + /// Use this attribute to configure the + /// without calling one of the + /// methods. + /// + /// + /// Nicko Cadell + [AttributeUsage(AttributeTargets.Assembly)] + [Serializable] + public sealed class SecurityContextProviderAttribute : ConfiguratorAttribute { /// - /// Initializes a new instance of the class. - /// Construct provider attribute with type specified. - /// - /// the type of the provider to use. - /// - /// - /// The provider specified must subclass the - /// class. - /// - /// - public SecurityContextProviderAttribute(Type providerType) - : base(100) /* configurator priority 100 to execute before the XmlConfigurator */ - { - this.m_providerType = providerType; + /// Construct provider attribute with type specified + /// + /// the type of the provider to use + /// + /// + /// The provider specified must subclass the + /// class. + /// + /// + public SecurityContextProviderAttribute(Type providerType) : base(100) /* configurator priority 100 to execute before the XmlConfigurator */ + { + this.m_providerType = providerType; } - /// - /// Gets or sets the type of the provider to use. - /// - /// - /// the type of the provider to use. - /// - /// - /// - /// The provider specified must subclass the - /// class. - /// - /// - public Type ProviderType - { - get { return this.m_providerType; } - set { this.m_providerType = value; } + /// + /// Gets or sets the type of the provider to use. + /// + /// + /// the type of the provider to use. + /// + /// + /// + /// The provider specified must subclass the + /// class. + /// + /// + public Type ProviderType + { + get { return this.m_providerType; } + set { this.m_providerType = value; } } - /// - /// Configures the SecurityContextProvider. - /// - /// The assembly that this attribute was defined on. - /// The repository to configure. - /// - /// - /// Creates a provider instance from the specified. - /// Sets this as the default security context provider . - /// - /// - public override void Configure(Assembly sourceAssembly, ILoggerRepository targetRepository) - { - if (this.m_providerType == null) - { - LogLog.Error(declaringType, "Attribute specified on assembly [" + sourceAssembly.FullName + "] with null ProviderType."); - } - else - { - LogLog.Debug(declaringType, "Creating provider of type [" + this.m_providerType.FullName + "]"); - - SecurityContextProvider provider = Activator.CreateInstance(this.m_providerType) as SecurityContextProvider; - - if (provider == null) - { - LogLog.Error(declaringType, "Failed to create SecurityContextProvider instance of type [" + this.m_providerType.Name + "]."); - } - else - { - SecurityContextProvider.DefaultProvider = provider; - } - } + /// + /// Configures the SecurityContextProvider + /// + /// The assembly that this attribute was defined on. + /// The repository to configure. + /// + /// + /// Creates a provider instance from the specified. + /// Sets this as the default security context provider . + /// + /// + public override void Configure(Assembly sourceAssembly, ILoggerRepository targetRepository) + { + if (this.m_providerType == null) + { + LogLog.Error(declaringType, "Attribute specified on assembly ["+sourceAssembly.FullName+"] with null ProviderType."); + } + else + { + LogLog.Debug(declaringType, "Creating provider of type ["+ this.m_providerType.FullName +"]"); + + SecurityContextProvider provider = Activator.CreateInstance(this.m_providerType) as SecurityContextProvider; + + if (provider == null) + { + LogLog.Error(declaringType, "Failed to create SecurityContextProvider instance of type ["+ this.m_providerType.Name+"]."); + } + else + { + SecurityContextProvider.DefaultProvider = provider; + } + } } private Type m_providerType = null; - /// - /// The fully qualified type of the SecurityContextProviderAttribute class. - /// - /// - /// Used by the internal logger to record the Type of the - /// log message. - /// + /// + /// The fully qualified type of the SecurityContextProviderAttribute class. + /// + /// + /// Used by the internal logger to record the Type of the + /// log message. + /// private static readonly Type declaringType = typeof(SecurityContextProviderAttribute); - } -} - -#endif // !NETCF + } +} + +#endif // !NETCF diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Config/XmlConfigurator.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Config/XmlConfigurator.cs index 5c9dc3015ce..b7bdad47875 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Config/XmlConfigurator.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Config/XmlConfigurator.cs @@ -1,1131 +1,1121 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.Config -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; - using System.Collections; - using System.IO; - using System.Net; - using System.Reflection; - using System.Threading; - using System.Xml; - - using log4net.Appender; - using log4net.Repository; - using log4net.Util; - - /// - /// Use this class to initialize the log4net environment using an Xml tree. - /// - /// - /// - /// Configures a using an Xml tree. - /// - /// - /// Nicko Cadell. - /// Gert Driesen. - public sealed class XmlConfigurator +using System; +using System.Xml; +using System.Collections; +using System.IO; +#if !NETCF && !NETSTANDARD1_3 +using System.Reflection; +#endif +using System.Threading; +using System.Net; + +using log4net.Util; +using log4net.Repository; + +namespace log4net.Config +{ + /// + /// Use this class to initialize the log4net environment using an Xml tree. + /// + /// + /// + /// Configures a using an Xml tree. + /// + /// + /// Nicko Cadell + /// Gert Driesen + public sealed class XmlConfigurator { /// - /// Initializes a new instance of the class. - /// Private constructor. - /// - private XmlConfigurator() - { + /// Private constructor + /// + private XmlConfigurator() + { } -#if !NETCF - /// - /// Automatically configures the using settings - /// stored in the application's configuration file. - /// - /// - /// - /// Each application has a configuration file. This has the - /// same name as the application with '.config' appended. - /// This file is XML and calling this function prompts the - /// configurator to look in that file for a section called - /// log4net that contains the configuration data. - /// - /// - /// To use this method to configure log4net you must specify - /// the section - /// handler for the log4net configuration section. See the - /// for an example. - /// - /// +#if !NETCF + /// + /// Automatically configures the using settings + /// stored in the application's configuration file. + /// + /// + /// + /// Each application has a configuration file. This has the + /// same name as the application with '.config' appended. + /// This file is XML and calling this function prompts the + /// configurator to look in that file for a section called + /// log4net that contains the configuration data. + /// + /// + /// To use this method to configure log4net you must specify + /// the section + /// handler for the log4net configuration section. See the + /// for an example. + /// + /// /// The repository to configure. - /// -#else - /// - /// Automatically configures the using settings - /// stored in the application's configuration file. - /// - /// - /// - /// Each application has a configuration file. This has the - /// same name as the application with '.config' appended. - /// This file is XML and calling this function prompts the - /// configurator to look in that file for a section called - /// log4net that contains the configuration data. - /// - /// - /// The repository to configure. -#endif - public static ICollection Configure(ILoggerRepository repository) - { - ArrayList configurationMessages = new ArrayList(); - - using (new LogLog.LogReceivedAdapter(configurationMessages)) - { - InternalConfigure(repository); - } - - repository.ConfigurationMessages = configurationMessages; - - return configurationMessages; - } - - private static void InternalConfigure(ILoggerRepository repository) - { - LogLog.Debug(declaringType, "configuring repository [" + repository.Name + "] using .config file section"); - - try - { - LogLog.Debug(declaringType, "Application config file is [" + SystemInfo.ConfigurationFileLocation + "]"); - } - catch - { - // ignore error - LogLog.Debug(declaringType, "Application config file location unknown"); - } - -#if NETCF || NETSTANDARD1_3 - // No config file reading stuff. Just go straight for the file - Configure(repository, new FileInfo(SystemInfo.ConfigurationFileLocation)); -#else - try - { - XmlElement configElement = null; -#if NET_2_0 - configElement = System.Configuration.ConfigurationManager.GetSection("log4net") as XmlElement; -#else - configElement = System.Configuration.ConfigurationSettings.GetConfig("log4net") as XmlElement; -#endif - if (configElement == null) - { - // Failed to load the xml config using configuration settings handler - LogLog.Error(declaringType, "Failed to find configuration section 'log4net' in the application's .config file. Check your .config file for the and elements. The configuration section should look like:
"); - } - else - { - // Configure using the xml loaded from the config file - InternalConfigureFromXml(repository, configElement); - } - } - catch (System.Configuration.ConfigurationException confEx) - { - if (confEx.BareMessage.IndexOf("Unrecognized element") >= 0) - { - // Looks like the XML file is not valid - LogLog.Error(declaringType, "Failed to parse config file. Check your .config file is well formed XML.", confEx); - } - else - { - // This exception is typically due to the assembly name not being correctly specified in the section type. - string configSectionStr = "
"; - LogLog.Error(declaringType, "Failed to parse config file. Is the specified as: " + configSectionStr, confEx); - } - } -#endif +#else + /// + /// Automatically configures the using settings + /// stored in the application's configuration file. + /// + /// + /// + /// Each application has a configuration file. This has the + /// same name as the application with '.config' appended. + /// This file is XML and calling this function prompts the + /// configurator to look in that file for a section called + /// log4net that contains the configuration data. + /// + /// + /// The repository to configure. +#endif + public static ICollection Configure(ILoggerRepository repository) + { + ArrayList configurationMessages = new ArrayList(); + + using (new LogLog.LogReceivedAdapter(configurationMessages)) + { + InternalConfigure(repository); + } + + repository.ConfigurationMessages = configurationMessages; + + return configurationMessages; } -#if !NETSTANDARD1_3 // Excluded because GetCallingAssembly() is not available in CoreFX (https://github.com/dotnet/corefx/issues/2221). -#if !NETCF - /// - /// Automatically configures the log4net system based on the - /// application's configuration settings. - /// - /// - /// - /// Each application has a configuration file. This has the - /// same name as the application with '.config' appended. - /// This file is XML and calling this function prompts the - /// configurator to look in that file for a section called - /// log4net that contains the configuration data. - /// - /// - /// To use this method to configure log4net you must specify - /// the section - /// handler for the log4net configuration section. See the - /// for an example. - /// - /// + private static void InternalConfigure(ILoggerRepository repository) + { + LogLog.Debug(declaringType, "configuring repository [" + repository.Name + "] using .config file section"); + + try + { + LogLog.Debug(declaringType, "Application config file is [" + SystemInfo.ConfigurationFileLocation + "]"); + } + catch + { + // ignore error + LogLog.Debug(declaringType, "Application config file location unknown"); + } + +#if NETCF || NETSTANDARD1_3 + // No config file reading stuff. Just go straight for the file + Configure(repository, new FileInfo(SystemInfo.ConfigurationFileLocation)); +#else + try + { + XmlElement configElement = System.Configuration.ConfigurationManager.GetSection("log4net") as XmlElement; + if (configElement == null) + { + // Failed to load the xml config using configuration settings handler + LogLog.Error(declaringType, "Failed to find configuration section 'log4net' in the application's .config file. Check your .config file for the and elements. The configuration section should look like:
"); + } + else + { + // Configure using the xml loaded from the config file + InternalConfigureFromXml(repository, configElement); + } + } + catch(System.Configuration.ConfigurationException confEx) + { + if (confEx.BareMessage.IndexOf("Unrecognized element") >= 0) + { + // Looks like the XML file is not valid + LogLog.Error(declaringType, "Failed to parse config file. Check your .config file is well formed XML.", confEx); + } + else + { + // This exception is typically due to the assembly name not being correctly specified in the section type. + string configSectionStr = "
"; + LogLog.Error(declaringType, "Failed to parse config file. Is the specified as: " + configSectionStr, confEx); + } + } +#endif + } + +#if !NETSTANDARD1_3 // Excluded because GetCallingAssembly() is not available in CoreFX (https://github.com/dotnet/corefx/issues/2221). +#if !NETCF + /// + /// Automatically configures the log4net system based on the + /// application's configuration settings. + /// + /// + /// + /// Each application has a configuration file. This has the + /// same name as the application with '.config' appended. + /// This file is XML and calling this function prompts the + /// configurator to look in that file for a section called + /// log4net that contains the configuration data. + /// + /// + /// To use this method to configure log4net you must specify + /// the section + /// handler for the log4net configuration section. See the + /// for an example. + /// + /// /// - /// -#else - /// - /// Automatically configures the log4net system based on the - /// application's configuration settings. - /// - /// - /// - /// Each application has a configuration file. This has the - /// same name as the application with '.config' appended. - /// This file is XML and calling this function prompts the - /// configurator to look in that file for a section called - /// log4net that contains the configuration data. - /// - /// -#endif - public static ICollection Configure() - { - return Configure(LogManager.GetRepository(Assembly.GetCallingAssembly())); - } - - /// - /// Configures log4net using a log4net element. - /// - /// - /// - /// Loads the log4net configuration from the XML element - /// supplied as . - /// - /// +#else + /// + /// Automatically configures the log4net system based on the + /// application's configuration settings. + /// + /// + /// + /// Each application has a configuration file. This has the + /// same name as the application with '.config' appended. + /// This file is XML and calling this function prompts the + /// configurator to look in that file for a section called + /// log4net that contains the configuration data. + /// + /// +#endif + public static ICollection Configure() + { + return Configure(LogManager.GetRepository(Assembly.GetCallingAssembly())); + } + + /// + /// Configures log4net using a log4net element + /// + /// + /// + /// Loads the log4net configuration from the XML element + /// supplied as . + /// + /// /// The element to parse. - /// - public static ICollection Configure(XmlElement element) - { - ArrayList configurationMessages = new ArrayList(); - - ILoggerRepository repository = LogManager.GetRepository(Assembly.GetCallingAssembly()); - - using (new LogLog.LogReceivedAdapter(configurationMessages)) - { - InternalConfigureFromXml(repository, element); - } - - repository.ConfigurationMessages = configurationMessages; - - return configurationMessages; + public static ICollection Configure(XmlElement element) + { + ArrayList configurationMessages = new ArrayList(); + + ILoggerRepository repository = LogManager.GetRepository(Assembly.GetCallingAssembly()); + + using (new LogLog.LogReceivedAdapter(configurationMessages)) + { + InternalConfigureFromXml(repository, element); + } + + repository.ConfigurationMessages = configurationMessages; + + return configurationMessages; } -#if !NETCF - /// - /// Configures log4net using the specified configuration file. - /// - /// The XML file to load the configuration from. - /// - /// - /// The configuration file must be valid XML. It must contain - /// at least one element called log4net that holds - /// the log4net configuration data. - /// - /// - /// The log4net configuration file can possible be specified in the application's - /// configuration file (either MyAppName.exe.config for a - /// normal application on Web.config for an ASP.NET application). - /// - /// - /// The first element matching <configuration> will be read as the - /// configuration. If this file is also a .NET .config file then you must specify - /// a configuration section for the log4net element otherwise .NET will - /// complain. Set the type for the section handler to , for example: - /// - /// - ///
- /// - /// - /// - /// - /// The following example configures log4net using a configuration file, of which the - /// location is stored in the application's configuration file : - /// - /// - /// using log4net.Config; - /// using System.IO; - /// using System.Configuration; - /// - /// ... - /// - /// XmlConfigurator.Configure(new FileInfo(ConfigurationSettings.AppSettings["log4net-config-file"])); - /// - /// - /// In the .config file, the path to the log4net can be specified like this : - /// - /// - /// - /// - /// - /// - /// - /// +#if !NETCF + /// + /// Configures log4net using the specified configuration file. + /// + /// The XML file to load the configuration from. + /// + /// + /// The configuration file must be valid XML. It must contain + /// at least one element called log4net that holds + /// the log4net configuration data. + /// + /// + /// The log4net configuration file can possible be specified in the application's + /// configuration file (either MyAppName.exe.config for a + /// normal application on Web.config for an ASP.NET application). + /// + /// + /// The first element matching <configuration> will be read as the + /// configuration. If this file is also a .NET .config file then you must specify + /// a configuration section for the log4net element otherwise .NET will + /// complain. Set the type for the section handler to , for example: + /// + /// + ///
+ /// + /// + /// + /// + /// The following example configures log4net using a configuration file, of which the + /// location is stored in the application's configuration file : + /// + /// + /// using log4net.Config; + /// using System.IO; + /// using System.Configuration; + /// + /// ... + /// + /// XmlConfigurator.Configure(new FileInfo(ConfigurationSettings.AppSettings["log4net-config-file"])); + /// + /// + /// In the .config file, the path to the log4net can be specified like this : + /// + /// + /// + /// + /// + /// + /// + /// /// - /// -#else - /// - /// Configures log4net using the specified configuration file. - /// - /// The XML file to load the configuration from. - /// - /// - /// The configuration file must be valid XML. It must contain - /// at least one element called log4net that holds - /// the log4net configuration data. - /// - /// - /// The following example configures log4net using a configuration file, of which the - /// location is stored in the application's configuration file : - /// - /// - /// using log4net.Config; - /// using System.IO; - /// using System.Configuration; - /// - /// ... - /// - /// XmlConfigurator.Configure(new FileInfo(ConfigurationSettings.AppSettings["log4net-config-file"])); - /// - /// - /// In the .config file, the path to the log4net can be specified like this : - /// - /// - /// - /// - /// - /// - /// - /// - /// -#endif - public static ICollection Configure(FileInfo configFile) - { - ArrayList configurationMessages = new ArrayList(); - - using (new LogLog.LogReceivedAdapter(configurationMessages)) - { - InternalConfigure(LogManager.GetRepository(Assembly.GetCallingAssembly()), configFile); - } - - return configurationMessages; - } - - /// - /// Configures log4net using the specified configuration URI. - /// - /// A URI to load the XML configuration from. - /// - /// - /// The configuration data must be valid XML. It must contain - /// at least one element called log4net that holds - /// the log4net configuration data. - /// - /// - /// The must support the URI scheme specified. - /// +#else + /// + /// Configures log4net using the specified configuration file. + /// + /// The XML file to load the configuration from. + /// + /// + /// The configuration file must be valid XML. It must contain + /// at least one element called log4net that holds + /// the log4net configuration data. + /// + /// + /// The following example configures log4net using a configuration file, of which the + /// location is stored in the application's configuration file : + /// + /// + /// using log4net.Config; + /// using System.IO; + /// using System.Configuration; + /// + /// ... + /// + /// XmlConfigurator.Configure(new FileInfo(ConfigurationSettings.AppSettings["log4net-config-file"])); + /// + /// + /// In the .config file, the path to the log4net can be specified like this : + /// + /// + /// + /// + /// + /// + /// + /// /// - /// - public static ICollection Configure(Uri configUri) - { - ArrayList configurationMessages = new ArrayList(); - - ILoggerRepository repository = LogManager.GetRepository(Assembly.GetCallingAssembly()); - using (new LogLog.LogReceivedAdapter(configurationMessages)) - { - InternalConfigure(repository, configUri); - } - - repository.ConfigurationMessages = configurationMessages; - - return configurationMessages; - } - - /// - /// Configures log4net using the specified configuration data stream. - /// - /// A stream to load the XML configuration from. - /// - /// - /// The configuration data must be valid XML. It must contain - /// at least one element called log4net that holds - /// the log4net configuration data. - /// - /// - /// Note that this method will NOT close the stream parameter. - /// +#endif + public static ICollection Configure(FileInfo configFile) + { + ArrayList configurationMessages = new ArrayList(); + + using (new LogLog.LogReceivedAdapter(configurationMessages)) + { + InternalConfigure(LogManager.GetRepository(Assembly.GetCallingAssembly()), configFile); + } + + return configurationMessages; + } + + /// + /// Configures log4net using the specified configuration URI. + /// + /// A URI to load the XML configuration from. + /// + /// + /// The configuration data must be valid XML. It must contain + /// at least one element called log4net that holds + /// the log4net configuration data. + /// + /// + /// The must support the URI scheme specified. + /// /// - /// - public static ICollection Configure(Stream configStream) - { - ArrayList configurationMessages = new ArrayList(); - - ILoggerRepository repository = LogManager.GetRepository(Assembly.GetCallingAssembly()); - using (new LogLog.LogReceivedAdapter(configurationMessages)) - { - InternalConfigure(repository, configStream); - } - - repository.ConfigurationMessages = configurationMessages; - - return configurationMessages; - } -#endif // !NETSTANDARD1_3 - - /// - /// Configures the using the specified XML - /// element. - /// - /// - /// Loads the log4net configuration from the XML element - /// supplied as . - /// - /// The repository to configure. + public static ICollection Configure(Uri configUri) + { + ArrayList configurationMessages = new ArrayList(); + + ILoggerRepository repository = LogManager.GetRepository(Assembly.GetCallingAssembly()); + using (new LogLog.LogReceivedAdapter(configurationMessages)) + { + InternalConfigure(repository, configUri); + } + + repository.ConfigurationMessages = configurationMessages; + + return configurationMessages; + } + + /// + /// Configures log4net using the specified configuration data stream. + /// + /// A stream to load the XML configuration from. + /// + /// + /// The configuration data must be valid XML. It must contain + /// at least one element called log4net that holds + /// the log4net configuration data. + /// + /// + /// Note that this method will NOT close the stream parameter. + /// + /// + public static ICollection Configure(Stream configStream) + { + ArrayList configurationMessages = new ArrayList(); + + ILoggerRepository repository = LogManager.GetRepository(Assembly.GetCallingAssembly()); + using (new LogLog.LogReceivedAdapter(configurationMessages)) + { + InternalConfigure(repository, configStream); + } + + repository.ConfigurationMessages = configurationMessages; + + return configurationMessages; + } +#endif // !NETSTANDARD1_3 + + /// + /// Configures the using the specified XML + /// element. + /// + /// + /// Loads the log4net configuration from the XML element + /// supplied as . + /// + /// The repository to configure. /// The element to parse. - /// - public static ICollection Configure(ILoggerRepository repository, XmlElement element) - { - ArrayList configurationMessages = new ArrayList(); - - using (new LogLog.LogReceivedAdapter(configurationMessages)) - { - LogLog.Debug(declaringType, "configuring repository [" + repository.Name + "] using XML element"); - - InternalConfigureFromXml(repository, element); - } - - repository.ConfigurationMessages = configurationMessages; - - return configurationMessages; + public static ICollection Configure(ILoggerRepository repository, XmlElement element) + { + ArrayList configurationMessages = new ArrayList(); + + using (new LogLog.LogReceivedAdapter(configurationMessages)) + { + LogLog.Debug(declaringType, "configuring repository [" + repository.Name + "] using XML element"); + + InternalConfigureFromXml(repository, element); + } + + repository.ConfigurationMessages = configurationMessages; + + return configurationMessages; } -#if !NETCF - /// - /// Configures the using the specified configuration - /// file. - /// - /// The repository to configure. - /// The XML file to load the configuration from. - /// - /// - /// The configuration file must be valid XML. It must contain - /// at least one element called log4net that holds - /// the configuration data. - /// - /// - /// The log4net configuration file can possible be specified in the application's - /// configuration file (either MyAppName.exe.config for a - /// normal application on Web.config for an ASP.NET application). - /// - /// - /// The first element matching <configuration> will be read as the - /// configuration. If this file is also a .NET .config file then you must specify - /// a configuration section for the log4net element otherwise .NET will - /// complain. Set the type for the section handler to , for example: - /// - /// - ///
- /// - /// - /// - /// - /// The following example configures log4net using a configuration file, of which the - /// location is stored in the application's configuration file : - /// - /// - /// using log4net.Config; - /// using System.IO; - /// using System.Configuration; - /// - /// ... - /// - /// XmlConfigurator.Configure(new FileInfo(ConfigurationSettings.AppSettings["log4net-config-file"])); - /// - /// - /// In the .config file, the path to the log4net can be specified like this : - /// - /// - /// - /// - /// - /// - /// - /// +#if !NETCF + /// + /// Configures the using the specified configuration + /// file. + /// + /// The repository to configure. + /// The XML file to load the configuration from. + /// + /// + /// The configuration file must be valid XML. It must contain + /// at least one element called log4net that holds + /// the configuration data. + /// + /// + /// The log4net configuration file can possible be specified in the application's + /// configuration file (either MyAppName.exe.config for a + /// normal application on Web.config for an ASP.NET application). + /// + /// + /// The first element matching <configuration> will be read as the + /// configuration. If this file is also a .NET .config file then you must specify + /// a configuration section for the log4net element otherwise .NET will + /// complain. Set the type for the section handler to , for example: + /// + /// + ///
+ /// + /// + /// + /// + /// The following example configures log4net using a configuration file, of which the + /// location is stored in the application's configuration file : + /// + /// + /// using log4net.Config; + /// using System.IO; + /// using System.Configuration; + /// + /// ... + /// + /// XmlConfigurator.Configure(new FileInfo(ConfigurationSettings.AppSettings["log4net-config-file"])); + /// + /// + /// In the .config file, the path to the log4net can be specified like this : + /// + /// + /// + /// + /// + /// + /// + /// /// - /// -#else - /// - /// Configures the using the specified configuration - /// file. - /// - /// The repository to configure. - /// The XML file to load the configuration from. - /// - /// - /// The configuration file must be valid XML. It must contain - /// at least one element called log4net that holds - /// the configuration data. - /// - /// - /// The following example configures log4net using a configuration file, of which the - /// location is stored in the application's configuration file : - /// - /// - /// using log4net.Config; - /// using System.IO; - /// using System.Configuration; - /// - /// ... - /// - /// XmlConfigurator.Configure(new FileInfo(ConfigurationSettings.AppSettings["log4net-config-file"])); - /// - /// - /// In the .config file, the path to the log4net can be specified like this : - /// - /// - /// - /// - /// - /// - /// - /// - /// -#endif - public static ICollection Configure(ILoggerRepository repository, FileInfo configFile) - { - ArrayList configurationMessages = new ArrayList(); - - using (new LogLog.LogReceivedAdapter(configurationMessages)) - { - InternalConfigure(repository, configFile); - } - - repository.ConfigurationMessages = configurationMessages; - - return configurationMessages; - } - - private static void InternalConfigure(ILoggerRepository repository, FileInfo configFile) - { - LogLog.Debug(declaringType, "configuring repository [" + repository.Name + "] using file [" + configFile + "]"); - - if (configFile == null) - { - LogLog.Error(declaringType, "Configure called with null 'configFile' parameter"); - } - else - { - // Have to use File.Exists() rather than configFile.Exists() - // because configFile.Exists() caches the value, not what we want. - if (File.Exists(configFile.FullName)) - { - // Open the file for reading - FileStream fs = null; - - // Try hard to open the file - for (int retry = 5; --retry >= 0;) - { - try - { - fs = configFile.Open(FileMode.Open, FileAccess.Read, FileShare.Read); - break; - } - catch (IOException ex) - { - if (retry == 0) - { - LogLog.Error(declaringType, "Failed to open XML config file [" + configFile.Name + "]", ex); - - // The stream cannot be valid - fs = null; - } - - System.Threading.Thread.Sleep(250); - } - } - - if (fs != null) - { - try - { - // Load the configuration from the stream - InternalConfigure(repository, fs); - } - finally - { - // Force the file closed whatever happens - fs.Close(); - } - } - } - else - { - LogLog.Debug(declaringType, "config file [" + configFile.FullName + "] not found. Configuration unchanged."); - } - } - } - - /// - /// Configures the using the specified configuration - /// URI. - /// - /// The repository to configure. - /// A URI to load the XML configuration from. - /// - /// - /// The configuration data must be valid XML. It must contain - /// at least one element called log4net that holds - /// the configuration data. - /// - /// - /// The must support the URI scheme specified. - /// +#else + /// + /// Configures the using the specified configuration + /// file. + /// + /// The repository to configure. + /// The XML file to load the configuration from. + /// + /// + /// The configuration file must be valid XML. It must contain + /// at least one element called log4net that holds + /// the configuration data. + /// + /// + /// The following example configures log4net using a configuration file, of which the + /// location is stored in the application's configuration file : + /// + /// + /// using log4net.Config; + /// using System.IO; + /// using System.Configuration; + /// + /// ... + /// + /// XmlConfigurator.Configure(new FileInfo(ConfigurationSettings.AppSettings["log4net-config-file"])); + /// + /// + /// In the .config file, the path to the log4net can be specified like this : + /// + /// + /// + /// + /// + /// + /// + /// /// - /// - public static ICollection Configure(ILoggerRepository repository, Uri configUri) - { - ArrayList configurationMessages = new ArrayList(); - - using (new LogLog.LogReceivedAdapter(configurationMessages)) - { - InternalConfigure(repository, configUri); - } - - repository.ConfigurationMessages = configurationMessages; - - return configurationMessages; - } - - private static void InternalConfigure(ILoggerRepository repository, Uri configUri) - { - LogLog.Debug(declaringType, "configuring repository [" + repository.Name + "] using URI [" + configUri + "]"); - - if (configUri == null) - { - LogLog.Error(declaringType, "Configure called with null 'configUri' parameter"); - } - else - { - if (configUri.IsFile) - { - // If URI is local file then call Configure with FileInfo - InternalConfigure(repository, new FileInfo(configUri.LocalPath)); - } - else - { - // NETCF dose not support WebClient - WebRequest configRequest = null; - - try - { - configRequest = WebRequest.Create(configUri); - } - catch (Exception ex) - { - LogLog.Error(declaringType, "Failed to create WebRequest for URI [" + configUri + "]", ex); - } - - if (configRequest != null) - { -#if !NETCF_1_0 - // authentication may be required, set client to use default credentials - try - { - configRequest.Credentials = CredentialCache.DefaultCredentials; - } - catch - { - // ignore security exception - } -#endif - try - { -#if NETSTANDARD1_3 - WebResponse response = configRequest.GetResponseAsync().GetAwaiter().GetResult(); -#else - WebResponse response = configRequest.GetResponse(); -#endif - if (response != null) - { - try - { - // Open stream on config URI - using (Stream configStream = response.GetResponseStream()) - { - InternalConfigure(repository, configStream); - } - } - finally - { - response.Close(); - } - } - } - catch (Exception ex) - { - LogLog.Error(declaringType, "Failed to request config from URI [" + configUri + "]", ex); - } - } - } - } - } - - /// - /// Configures the using the specified configuration - /// file. - /// - /// The repository to configure. - /// The stream to load the XML configuration from. - /// - /// - /// The configuration data must be valid XML. It must contain - /// at least one element called log4net that holds - /// the configuration data. - /// - /// - /// Note that this method will NOT close the stream parameter. - /// +#endif + public static ICollection Configure(ILoggerRepository repository, FileInfo configFile) + { + ArrayList configurationMessages = new ArrayList(); + + using (new LogLog.LogReceivedAdapter(configurationMessages)) + { + InternalConfigure(repository, configFile); + } + + repository.ConfigurationMessages = configurationMessages; + + return configurationMessages; + } + + private static void InternalConfigure(ILoggerRepository repository, FileInfo configFile) + { + LogLog.Debug(declaringType, "configuring repository [" + repository.Name + "] using file [" + configFile + "]"); + + if (configFile == null) + { + LogLog.Error(declaringType, "Configure called with null 'configFile' parameter"); + } + else + { + // Have to use File.Exists() rather than configFile.Exists() + // because configFile.Exists() caches the value, not what we want. + if (File.Exists(configFile.FullName)) + { + // Open the file for reading + FileStream fs = null; + + // Try hard to open the file + for(int retry = 5; --retry >= 0; ) + { + try + { + fs = configFile.Open(FileMode.Open, FileAccess.Read, FileShare.Read); + break; + } + catch(IOException ex) + { + if (retry == 0) + { + LogLog.Error(declaringType, "Failed to open XML config file [" + configFile.Name + "]", ex); + + // The stream cannot be valid + fs = null; + } + Thread.Sleep(250); + } + } + + if (fs != null) + { + try + { + // Load the configuration from the stream + InternalConfigure(repository, fs); + } + finally + { + // Force the file closed whatever happens + fs.Dispose(); + } + } + } + else + { + LogLog.Debug(declaringType, "config file [" + configFile.FullName + "] not found. Configuration unchanged."); + } + } + } + + /// + /// Configures the using the specified configuration + /// URI. + /// + /// The repository to configure. + /// A URI to load the XML configuration from. + /// + /// + /// The configuration data must be valid XML. It must contain + /// at least one element called log4net that holds + /// the configuration data. + /// + /// + /// The must support the URI scheme specified. + /// /// - /// - public static ICollection Configure(ILoggerRepository repository, Stream configStream) - { - ArrayList configurationMessages = new ArrayList(); - - using (new LogLog.LogReceivedAdapter(configurationMessages)) - { - InternalConfigure(repository, configStream); - } - - repository.ConfigurationMessages = configurationMessages; - - return configurationMessages; - } - - private static void InternalConfigure(ILoggerRepository repository, Stream configStream) - { - LogLog.Debug(declaringType, "configuring repository [" + repository.Name + "] using stream"); - - if (configStream == null) - { - LogLog.Error(declaringType, "Configure called with null 'configStream' parameter"); - } - else - { - // Load the config file into a document - XmlDocument doc = new XmlDocument() { XmlResolver = null }; - try - { -#if NETCF - // Create a text reader for the file stream - XmlTextReader xmlReader = new XmlTextReader(configStream); -#elif NET_2_0 || NETSTANDARD1_3 - // Allow the DTD to specify entity includes - XmlReaderSettings settings = new XmlReaderSettings(); - - // .NET 4.0 warning CS0618: 'System.Xml.XmlReaderSettings.ProhibitDtd' - // is obsolete: 'Use XmlReaderSettings.DtdProcessing property instead.' -#if NETSTANDARD1_3 // TODO DtdProcessing.Parse not yet available (https://github.com/dotnet/corefx/issues/4376) - settings.DtdProcessing = DtdProcessing.Ignore; -#elif !NET_4_0 && !MONO_4_0 - settings.ProhibitDtd = true; -#else - settings.XmlResolver = null; - settings.DtdProcessing = DtdProcessing.Prohibit; -#endif - - // Create a reader over the input stream - XmlReader xmlReader = XmlReader.Create(configStream, settings); -#else - // Create a validating reader around a text reader for the file stream - XmlValidatingReader xmlReader = new XmlValidatingReader(new XmlTextReader(configStream)); - - // Specify that the reader should not perform validation, but that it should - // expand entity refs. - xmlReader.ValidationType = ValidationType.None; - xmlReader.EntityHandling = EntityHandling.ExpandEntities; -#endif - - // load the data into the document - doc.Load(xmlReader); - } - catch (Exception ex) - { - LogLog.Error(declaringType, "Error while loading XML configuration", ex); - - // The document is invalid - doc = null; - } - - if (doc != null) - { - LogLog.Debug(declaringType, "loading XML configuration"); - - // Configure using the 'log4net' element - XmlNodeList configNodeList = doc.GetElementsByTagName("log4net"); - if (configNodeList.Count == 0) - { - LogLog.Debug(declaringType, "XML configuration does not contain a element. Configuration Aborted."); - } - else if (configNodeList.Count > 1) - { - LogLog.Error(declaringType, "XML configuration contains [" + configNodeList.Count + "] elements. Only one is allowed. Configuration Aborted."); - } - else - { - InternalConfigureFromXml(repository, configNodeList[0] as XmlElement); - } - } - } + public static ICollection Configure(ILoggerRepository repository, Uri configUri) + { + ArrayList configurationMessages = new ArrayList(); + + using (new LogLog.LogReceivedAdapter(configurationMessages)) + { + InternalConfigure(repository, configUri); + } + + repository.ConfigurationMessages = configurationMessages; + + return configurationMessages; } -#if !NETCF && !SSCLI -#if !NETSTANDARD1_3 // Excluded because GetCallingAssembly() is not available in CoreFX (https://github.com/dotnet/corefx/issues/2221). - /// - /// Configures log4net using the file specified, monitors the file for changes - /// and reloads the configuration if a change is detected. - /// - /// The XML file to load the configuration from. - /// - /// - /// The configuration file must be valid XML. It must contain - /// at least one element called log4net that holds - /// the configuration data. - /// - /// - /// The configuration file will be monitored using a - /// and depends on the behavior of that class. - /// - /// - /// For more information on how to configure log4net using - /// a separate configuration file, see . - /// - /// + private static void InternalConfigure(ILoggerRepository repository, Uri configUri) + { + LogLog.Debug(declaringType, "configuring repository [" + repository.Name + "] using URI [" + configUri + "]"); + + if (configUri == null) + { + LogLog.Error(declaringType, "Configure called with null 'configUri' parameter"); + } + else + { + if (configUri.IsFile) + { + // If URI is local file then call Configure with FileInfo + InternalConfigure(repository, new FileInfo(configUri.LocalPath)); + } + else + { + // NETCF dose not support WebClient + WebRequest configRequest = null; + + try + { + configRequest = WebRequest.Create(configUri); + } + catch(Exception ex) + { + LogLog.Error(declaringType, "Failed to create WebRequest for URI [" + configUri + "]", ex); + } + + if (configRequest != null) + { +#if !NETCF_1_0 + // authentication may be required, set client to use default credentials + try + { + configRequest.Credentials = CredentialCache.DefaultCredentials; + } + catch + { + // ignore security exception + } +#endif + try + { +#if NETSTANDARD + using(var response = configRequest.GetResponseAsync().GetAwaiter().GetResult()) + { +#else + using (var response = configRequest.GetResponse()) + { + if (response != null) + { + using (var configStream = response.GetResponseStream()) + { + InternalConfigure(repository, configStream); + } + } + } +#endif + } + catch(Exception ex) + { + LogLog.Error(declaringType, "Failed to request config from URI ["+configUri+"]", ex); + } + } + } + } + } + + /// + /// Configures the using the specified configuration + /// file. + /// + /// The repository to configure. + /// The stream to load the XML configuration from. + /// + /// + /// The configuration data must be valid XML. It must contain + /// at least one element called log4net that holds + /// the configuration data. + /// + /// + /// Note that this method will NOT close the stream parameter. + /// + /// + public static ICollection Configure(ILoggerRepository repository, Stream configStream) + { + ArrayList configurationMessages = new ArrayList(); + + using (new LogLog.LogReceivedAdapter(configurationMessages)) + { + InternalConfigure(repository, configStream); + } + + repository.ConfigurationMessages = configurationMessages; + + return configurationMessages; + } + + private static void InternalConfigure(ILoggerRepository repository, Stream configStream) + { + LogLog.Debug(declaringType, "configuring repository [" + repository.Name + "] using stream"); + + if (configStream == null) + { + LogLog.Error(declaringType, "Configure called with null 'configStream' parameter"); + } + else + { + // Load the config file into a document +#if NETSTANDARD1_3 + XmlDocument doc = new XmlDocument(); +#else + XmlDocument doc = new XmlDocument { XmlResolver = null }; +#endif + try + { +#if (NETCF) + // Create a text reader for the file stream + XmlTextReader xmlReader = new XmlTextReader(configStream); +#elif NET_2_0 || NETSTANDARD + // Allow the DTD to specify entity includes + XmlReaderSettings settings = new XmlReaderSettings(); + // .NET 4.0 warning CS0618: 'System.Xml.XmlReaderSettings.ProhibitDtd' + // is obsolete: 'Use XmlReaderSettings.DtdProcessing property instead.' +#if NETSTANDARD1_3 // TODO DtdProcessing.Parse not yet available (https://github.com/dotnet/corefx/issues/4376) + settings.DtdProcessing = DtdProcessing.Ignore; +#elif !NET_4_0 && !MONO_4_0 && !NETSTANDARD2_0 + settings.ProhibitDtd = true; +#else + settings.XmlResolver = null; + settings.DtdProcessing = DtdProcessing.Ignore; +#endif + + // Create a reader over the input stream + using (var xmlReader = XmlReader.Create(configStream, settings)) + { +#else + // Create a validating reader around a text reader for the file stream + using(var xmlReader = new XmlValidatingReader(new XmlTextReader(configStream))) + { + // Specify that the reader should not perform validation, but that it should + // expand entity refs. + xmlReader.ValidationType = ValidationType.None; + xmlReader.EntityHandling = EntityHandling.ExpandEntities; +#endif + + // load the data into the document + doc.Load(xmlReader); +#if !NETCF + } +#endif + } + + catch (Exception ex) + { + LogLog.Error(declaringType, "Error while loading XML configuration", ex); + + // The document is invalid + doc = null; + } + + if (doc != null) + { + LogLog.Debug(declaringType, "loading XML configuration"); + + // Configure using the 'log4net' element + XmlNodeList configNodeList = doc.GetElementsByTagName("log4net"); + if (configNodeList.Count == 0) + { + LogLog.Debug(declaringType, "XML configuration does not contain a element. Configuration Aborted."); + } + else if (configNodeList.Count > 1) + { + LogLog.Error(declaringType, "XML configuration contains [" + configNodeList.Count + "] elements. Only one is allowed. Configuration Aborted."); + } + else + { + InternalConfigureFromXml(repository, configNodeList[0] as XmlElement); + } + } + } + } + +#if (!NETCF && !SSCLI) +#if !NETSTANDARD1_3 // Excluded because GetCallingAssembly() is not available in CoreFX (https://github.com/dotnet/corefx/issues/2221). + /// + /// Configures log4net using the file specified, monitors the file for changes + /// and reloads the configuration if a change is detected. + /// + /// The XML file to load the configuration from. + /// + /// + /// The configuration file must be valid XML. It must contain + /// at least one element called log4net that holds + /// the configuration data. + /// + /// + /// The configuration file will be monitored using a + /// and depends on the behavior of that class. + /// + /// + /// For more information on how to configure log4net using + /// a separate configuration file, see . + /// + /// /// - /// - public static ICollection ConfigureAndWatch(FileInfo configFile) - { - ArrayList configurationMessages = new ArrayList(); - - ILoggerRepository repository = LogManager.GetRepository(Assembly.GetCallingAssembly()); - - using (new LogLog.LogReceivedAdapter(configurationMessages)) - { - InternalConfigureAndWatch(repository, configFile); - } - - repository.ConfigurationMessages = configurationMessages; - - return configurationMessages; - } -#endif // !NETSTANDARD1_3 - - /// - /// Configures the using the file specified, - /// monitors the file for changes and reloads the configuration if a change - /// is detected. - /// - /// The repository to configure. - /// The XML file to load the configuration from. - /// - /// - /// The configuration file must be valid XML. It must contain - /// at least one element called log4net that holds - /// the configuration data. - /// - /// - /// The configuration file will be monitored using a - /// and depends on the behavior of that class. - /// - /// - /// For more information on how to configure log4net using - /// a separate configuration file, see . - /// - /// + public static ICollection ConfigureAndWatch(FileInfo configFile) + { + ArrayList configurationMessages = new ArrayList(); + + ILoggerRepository repository = LogManager.GetRepository(Assembly.GetCallingAssembly()); + + using (new LogLog.LogReceivedAdapter(configurationMessages)) + { + InternalConfigureAndWatch(repository, configFile); + } + + repository.ConfigurationMessages = configurationMessages; + + return configurationMessages; + } +#endif // !NETSTANDARD1_3 + + /// + /// Configures the using the file specified, + /// monitors the file for changes and reloads the configuration if a change + /// is detected. + /// + /// The repository to configure. + /// The XML file to load the configuration from. + /// + /// + /// The configuration file must be valid XML. It must contain + /// at least one element called log4net that holds + /// the configuration data. + /// + /// + /// The configuration file will be monitored using a + /// and depends on the behavior of that class. + /// + /// + /// For more information on how to configure log4net using + /// a separate configuration file, see . + /// + /// /// - /// - public static ICollection ConfigureAndWatch(ILoggerRepository repository, FileInfo configFile) - { - ArrayList configurationMessages = new ArrayList(); - - using (new LogLog.LogReceivedAdapter(configurationMessages)) - { - InternalConfigureAndWatch(repository, configFile); - } - - repository.ConfigurationMessages = configurationMessages; - - return configurationMessages; - } - - private static void InternalConfigureAndWatch(ILoggerRepository repository, FileInfo configFile) - { - LogLog.Debug(declaringType, "configuring repository [" + repository.Name + "] using file [" + configFile + "] watching for file updates"); - - if (configFile == null) - { - LogLog.Error(declaringType, "ConfigureAndWatch called with null 'configFile' parameter"); - } - else - { - // Configure log4net now - InternalConfigure(repository, configFile); - - try - { - lock (m_repositoryName2ConfigAndWatchHandler) - { - // support multiple repositories each having their own watcher - ConfigureAndWatchHandler handler = - (ConfigureAndWatchHandler)m_repositoryName2ConfigAndWatchHandler[configFile.FullName]; - - if (handler != null) - { - m_repositoryName2ConfigAndWatchHandler.Remove(configFile.FullName); - handler.Dispose(); - } - - // Create and start a watch handler that will reload the - // configuration whenever the config file is modified. - handler = new ConfigureAndWatchHandler(repository, configFile); - m_repositoryName2ConfigAndWatchHandler[configFile.FullName] = handler; - } - } - catch (Exception ex) - { - LogLog.Error(declaringType, "Failed to initialize configuration file watcher for file [" + configFile.FullName + "]", ex); - } - } + public static ICollection ConfigureAndWatch(ILoggerRepository repository, FileInfo configFile) + { + ArrayList configurationMessages = new ArrayList(); + + using (new LogLog.LogReceivedAdapter(configurationMessages)) + { + InternalConfigureAndWatch(repository, configFile); + } + + repository.ConfigurationMessages = configurationMessages; + + return configurationMessages; + } + + private static void InternalConfigureAndWatch(ILoggerRepository repository, FileInfo configFile) + { + LogLog.Debug(declaringType, "configuring repository [" + repository.Name + "] using file [" + configFile + "] watching for file updates"); + + if (configFile == null) + { + LogLog.Error(declaringType, "ConfigureAndWatch called with null 'configFile' parameter"); + } + else + { + // Configure log4net now + InternalConfigure(repository, configFile); + + try + { + lock (m_repositoryName2ConfigAndWatchHandler) + { + // support multiple repositories each having their own watcher + ConfigureAndWatchHandler handler = + (ConfigureAndWatchHandler)m_repositoryName2ConfigAndWatchHandler[configFile.FullName]; + + if (handler != null) + { + m_repositoryName2ConfigAndWatchHandler.Remove(configFile.FullName); + handler.Dispose(); + } + + // Create and start a watch handler that will reload the + // configuration whenever the config file is modified. + handler = new ConfigureAndWatchHandler(repository, configFile); + m_repositoryName2ConfigAndWatchHandler[configFile.FullName] = handler; + } + } + catch(Exception ex) + { + LogLog.Error(declaringType, "Failed to initialize configuration file watcher for file [" + configFile.FullName + "]", ex); + } + } } -#endif - -#if !NETCF && !SSCLI - /// - /// Class used to watch config files. - /// - /// - /// - /// Uses the to monitor - /// changes to a specified file. Because multiple change notifications - /// may be raised when the file is modified, a timer is used to - /// compress the notifications into a single event. The timer - /// waits for time before delivering - /// the event notification. If any further - /// change notifications arrive while the timer is waiting it - /// is reset and waits again for to - /// elapse. - /// - /// - private sealed class ConfigureAndWatchHandler : IDisposable - { - /// - /// Holds the FileInfo used to configure the XmlConfigurator. - /// - private FileInfo m_configFile; - - /// - /// Holds the repository being configured. - /// - private ILoggerRepository m_repository; - - /// - /// The timer used to compress the notification events. - /// - private Timer m_timer; - - /// - /// The default amount of time to wait after receiving notification - /// before reloading the config file. - /// - private const int TimeoutMillis = 500; - - /// - /// Watches file for changes. This object should be disposed when no longer - /// needed to free system handles on the watched resources. - /// +#endif + +#if (!NETCF && !SSCLI) + /// + /// Class used to watch config files. + /// + /// + /// + /// Uses the to monitor + /// changes to a specified file. Because multiple change notifications + /// may be raised when the file is modified, a timer is used to + /// compress the notifications into a single event. The timer + /// waits for time before delivering + /// the event notification. If any further + /// change notifications arrive while the timer is waiting it + /// is reset and waits again for to + /// elapse. + /// + /// + private sealed class ConfigureAndWatchHandler : IDisposable + { + /// + /// Holds the FileInfo used to configure the XmlConfigurator + /// + private FileInfo m_configFile; + + /// + /// Holds the repository being configured. + /// + private ILoggerRepository m_repository; + + /// + /// The timer used to compress the notification events. + /// + private Timer m_timer; + + /// + /// The default amount of time to wait after receiving notification + /// before reloading the config file. + /// + private const int TimeoutMillis = 500; + + /// + /// Watches file for changes. This object should be disposed when no longer + /// needed to free system handles on the watched resources. + /// private FileSystemWatcher m_watcher; - /// - /// Initializes a new instance of the class to - /// watch a specified config file used to configure a repository. - /// - /// The repository to configure. - /// The configuration file to watch. - /// - /// - /// Initializes a new instance of the class. - /// - /// -#if NET_4_0 || MONO_4_0 || NETSTANDARD1_3 - [System.Security.SecuritySafeCritical] -#endif - public ConfigureAndWatchHandler(ILoggerRepository repository, FileInfo configFile) - { - this.m_repository = repository; - this.m_configFile = configFile; - - // Create a new FileSystemWatcher and set its properties. - this.m_watcher = new FileSystemWatcher(); - - this.m_watcher.Path = this.m_configFile.DirectoryName; - this.m_watcher.Filter = this.m_configFile.Name; - - // Set the notification filters - this.m_watcher.NotifyFilter = NotifyFilters.CreationTime | NotifyFilters.LastWrite | NotifyFilters.FileName; - - // Add event handlers. OnChanged will do for all event handlers that fire a FileSystemEventArgs - this.m_watcher.Changed += new FileSystemEventHandler(this.ConfigureAndWatchHandler_OnChanged); - this.m_watcher.Created += new FileSystemEventHandler(this.ConfigureAndWatchHandler_OnChanged); - this.m_watcher.Deleted += new FileSystemEventHandler(this.ConfigureAndWatchHandler_OnChanged); - this.m_watcher.Renamed += new RenamedEventHandler(this.ConfigureAndWatchHandler_OnRenamed); - - // Begin watching. - this.m_watcher.EnableRaisingEvents = true; - - // Create the timer that will be used to deliver events. Set as disabled - this.m_timer = new Timer(new TimerCallback(this.OnWatchedFileChange), null, Timeout.Infinite, Timeout.Infinite); - } - - /// - /// Event handler used by . - /// - /// The firing the event. - /// The argument indicates the file that caused the event to be fired. - /// - /// - /// This handler reloads the configuration from the file when the event is fired. - /// - /// - private void ConfigureAndWatchHandler_OnChanged(object source, FileSystemEventArgs e) - { - LogLog.Debug(declaringType, "ConfigureAndWatchHandler: " + e.ChangeType + " [" + this.m_configFile.FullName + "]"); - - // Deliver the event in TimeoutMillis time - // timer will fire only once - this.m_timer.Change(TimeoutMillis, Timeout.Infinite); - } - - /// - /// Event handler used by . - /// - /// The firing the event. - /// The argument indicates the file that caused the event to be fired. - /// - /// - /// This handler reloads the configuration from the file when the event is fired. - /// - /// - private void ConfigureAndWatchHandler_OnRenamed(object source, RenamedEventArgs e) - { - LogLog.Debug(declaringType, "ConfigureAndWatchHandler: " + e.ChangeType + " [" + this.m_configFile.FullName + "]"); - - // Deliver the event in TimeoutMillis time - // timer will fire only once - this.m_timer.Change(TimeoutMillis, Timeout.Infinite); - } - - /// - /// Called by the timer when the configuration has been updated. - /// - /// null. - private void OnWatchedFileChange(object state) - { - XmlConfigurator.InternalConfigure(this.m_repository, this.m_configFile); + /// + /// Initializes a new instance of the class to + /// watch a specified config file used to configure a repository. + /// + /// The repository to configure. + /// The configuration file to watch. + /// + /// + /// Initializes a new instance of the class. + /// + /// +#if NET_4_0 || MONO_4_0 || NETSTANDARD + [System.Security.SecuritySafeCritical] +#endif + public ConfigureAndWatchHandler(ILoggerRepository repository, FileInfo configFile) + { + this.m_repository = repository; + this.m_configFile = configFile; + + // Create a new FileSystemWatcher and set its properties. + this.m_watcher = new FileSystemWatcher(); + + this.m_watcher.Path = this.m_configFile.DirectoryName; + this.m_watcher.Filter = this.m_configFile.Name; + + // Set the notification filters + this.m_watcher.NotifyFilter = NotifyFilters.CreationTime | NotifyFilters.LastWrite | NotifyFilters.FileName; + + // Add event handlers. OnChanged will do for all event handlers that fire a FileSystemEventArgs + this.m_watcher.Changed += new FileSystemEventHandler(this.ConfigureAndWatchHandler_OnChanged); + this.m_watcher.Created += new FileSystemEventHandler(this.ConfigureAndWatchHandler_OnChanged); + this.m_watcher.Deleted += new FileSystemEventHandler(this.ConfigureAndWatchHandler_OnChanged); + this.m_watcher.Renamed += new RenamedEventHandler(this.ConfigureAndWatchHandler_OnRenamed); + + // Begin watching. + this.m_watcher.EnableRaisingEvents = true; + + // Create the timer that will be used to deliver events. Set as disabled + this.m_timer = new Timer(new TimerCallback(this.OnWatchedFileChange), null, Timeout.Infinite, Timeout.Infinite); } - /// - /// Release the handles held by the watcher and timer. - /// -#if NET_4_0 || MONO_4_0 || NETSTANDARD1_3 - [System.Security.SecuritySafeCritical] -#endif - public void Dispose() - { - this.m_watcher.EnableRaisingEvents = false; - this.m_watcher.Dispose(); - this.m_timer.Dispose(); - } + /// + /// Event handler used by . + /// + /// The firing the event. + /// The argument indicates the file that caused the event to be fired. + /// + /// + /// This handler reloads the configuration from the file when the event is fired. + /// + /// + private void ConfigureAndWatchHandler_OnChanged(object source, FileSystemEventArgs e) + { + LogLog.Debug(declaringType, "ConfigureAndWatchHandler: " + e.ChangeType + " [" + this.m_configFile.FullName + "]"); + + // Deliver the event in TimeoutMillis time + // timer will fire only once + this.m_timer.Change(TimeoutMillis, Timeout.Infinite); + } + + /// + /// Event handler used by . + /// + /// The firing the event. + /// The argument indicates the file that caused the event to be fired. + /// + /// + /// This handler reloads the configuration from the file when the event is fired. + /// + /// + private void ConfigureAndWatchHandler_OnRenamed(object source, RenamedEventArgs e) + { + LogLog.Debug(declaringType, "ConfigureAndWatchHandler: " + e.ChangeType + " [" + this.m_configFile.FullName + "]"); + + // Deliver the event in TimeoutMillis time + // timer will fire only once + this.m_timer.Change(TimeoutMillis, Timeout.Infinite); + } + + /// + /// Called by the timer when the configuration has been updated. + /// + /// null + private void OnWatchedFileChange(object state) + { + InternalConfigure(this.m_repository, this.m_configFile); + } + + /// + /// Release the handles held by the watcher and timer. + /// +#if NET_4_0 || MONO_4_0 || NETSTANDARD + [System.Security.SecuritySafeCritical] +#endif + public void Dispose() + { + this.m_watcher.EnableRaisingEvents = false; + this.m_watcher.Dispose(); + this.m_timer.Dispose(); + } } -#endif - - /// - /// Configures the specified repository using a log4net element. - /// - /// The hierarchy to configure. - /// The element to parse. - /// - /// - /// Loads the log4net configuration from the XML element - /// supplied as . - /// - /// - /// This method is ultimately called by one of the Configure methods - /// to load the configuration from an . - /// - /// - private static void InternalConfigureFromXml(ILoggerRepository repository, XmlElement element) - { - if (element == null) - { - LogLog.Error(declaringType, "ConfigureFromXml called with null 'element' parameter"); - } - else if (repository == null) - { - LogLog.Error(declaringType, "ConfigureFromXml called with null 'repository' parameter"); - } - else - { - LogLog.Debug(declaringType, "Configuring Repository [" + repository.Name + "]"); - - IXmlRepositoryConfigurator configurableRepository = repository as IXmlRepositoryConfigurator; - if (configurableRepository == null) - { - LogLog.Warn(declaringType, "Repository [" + repository + "] does not support the XmlConfigurator"); - } - else - { - // Copy the xml data into the root of a new document - // this isolates the xml config data from the rest of - // the document - XmlDocument newDoc = new XmlDocument() { XmlResolver = null }; - XmlElement newElement = (XmlElement)newDoc.AppendChild(newDoc.ImportNode(element, true)); - - // Pass the configurator the config element - configurableRepository.Configure(newElement); - } - } +#endif + + /// + /// Configures the specified repository using a log4net element. + /// + /// The hierarchy to configure. + /// The element to parse. + /// + /// + /// Loads the log4net configuration from the XML element + /// supplied as . + /// + /// + /// This method is ultimately called by one of the Configure methods + /// to load the configuration from an . + /// + /// + private static void InternalConfigureFromXml(ILoggerRepository repository, XmlElement element) + { + if (element == null) + { + LogLog.Error(declaringType, "ConfigureFromXml called with null 'element' parameter"); + } + else if (repository == null) + { + LogLog.Error(declaringType, "ConfigureFromXml called with null 'repository' parameter"); + } + else + { + LogLog.Debug(declaringType, "Configuring Repository [" + repository.Name + "]"); + + IXmlRepositoryConfigurator configurableRepository = repository as IXmlRepositoryConfigurator; + if (configurableRepository == null) + { + LogLog.Warn(declaringType, "Repository [" + repository + "] does not support the XmlConfigurator"); + } + else + { + // Copy the xml data into the root of a new document + // this isolates the xml config data from the rest of + // the document +#if NETSTANDARD1_3 + XmlDocument newDoc = new XmlDocument(); +#else + XmlDocument newDoc = new XmlDocument { XmlResolver = null }; +#endif + XmlElement newElement = (XmlElement)newDoc.AppendChild(newDoc.ImportNode(element, true)); + + // Pass the configurator the config element + configurableRepository.Configure(newElement); + } + } } - /// - /// Maps repository names to ConfigAndWatchHandler instances to allow a particular - /// ConfigAndWatchHandler to dispose of its FileSystemWatcher when a repository is - /// reconfigured. - /// - private static readonly Hashtable m_repositoryName2ConfigAndWatchHandler = new Hashtable(); - - /// - /// The fully qualified type of the XmlConfigurator class. - /// - /// - /// Used by the internal logger to record the Type of the - /// log message. - /// + /// + /// Maps repository names to ConfigAndWatchHandler instances to allow a particular + /// ConfigAndWatchHandler to dispose of its FileSystemWatcher when a repository is + /// reconfigured. + /// + private static readonly Hashtable m_repositoryName2ConfigAndWatchHandler = new Hashtable(); + + /// + /// The fully qualified type of the XmlConfigurator class. + /// + /// + /// Used by the internal logger to record the Type of the + /// log message. + /// private static readonly Type declaringType = typeof(XmlConfigurator); - } + } } + diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Config/XmlConfiguratorAttribute.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Config/XmlConfiguratorAttribute.cs index c496e853690..95879881e37 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Config/XmlConfiguratorAttribute.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Config/XmlConfiguratorAttribute.cs @@ -1,458 +1,454 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -// .NET Compact Framework 1.0 has no support for reading assembly attributes -#if !NETCF - -using System; -using System.Collections; -using System.IO; -using System.Reflection; +// .NET Compact Framework 1.0 has no support for reading assembly attributes +#if !NETCF -using log4net.Repository; -using log4net.Repository.Hierarchy; -using log4net.Util; - -namespace log4net.Config -{ - /// - /// Assembly level attribute to configure the . - /// - /// - /// - /// This attribute may only be used at the assembly scope and can only - /// be used once per assembly. - /// - /// - /// Use this attribute to configure the - /// without calling one of the - /// methods. - /// - /// - /// If neither of the or - /// properties are set the configuration is loaded from the application's .config file. - /// If set the property takes priority over the - /// property. The property - /// specifies a path to a file to load the config from. The path is relative to the - /// application's base directory; . - /// The property is used as a postfix to the assembly file name. - /// The config file must be located in the application's base directory; . - /// For example in a console application setting the to - /// config has the same effect as not specifying the or - /// properties. - /// - /// - /// The property can be set to cause the - /// to watch the configuration file for changes. - /// - /// - /// - /// Log4net will only look for assembly level configuration attributes once. - /// When using the log4net assembly level attributes to control the configuration - /// of log4net you must ensure that the first call to any of the - /// methods is made from the assembly with the configuration - /// attributes. - /// - /// - /// If you cannot guarantee the order in which log4net calls will be made from - /// different assemblies you must use programmatic configuration instead, i.e. - /// call the method directly. - /// - /// - /// - /// Nicko Cadell. - /// Gert Driesen. - [AttributeUsage(AttributeTargets.Assembly)] - [Serializable] - public /*sealed*/ class XmlConfiguratorAttribute : ConfiguratorAttribute +using System; +using System.Collections; +using System.Reflection; +using System.IO; + +using log4net.Util; +using log4net.Repository; +using log4net.Repository.Hierarchy; + +namespace log4net.Config +{ + /// + /// Assembly level attribute to configure the . + /// + /// + /// + /// This attribute may only be used at the assembly scope and can only + /// be used once per assembly. + /// + /// + /// Use this attribute to configure the + /// without calling one of the + /// methods. + /// + /// + /// If neither of the or + /// properties are set the configuration is loaded from the application's .config file. + /// If set the property takes priority over the + /// property. The property + /// specifies a path to a file to load the config from. The path is relative to the + /// application's base directory; . + /// The property is used as a postfix to the assembly file name. + /// The config file must be located in the application's base directory; . + /// For example in a console application setting the to + /// config has the same effect as not specifying the or + /// properties. + /// + /// + /// The property can be set to cause the + /// to watch the configuration file for changes. + /// + /// + /// + /// Log4net will only look for assembly level configuration attributes once. + /// When using the log4net assembly level attributes to control the configuration + /// of log4net you must ensure that the first call to any of the + /// methods is made from the assembly with the configuration + /// attributes. + /// + /// + /// If you cannot guarantee the order in which log4net calls will be made from + /// different assemblies you must use programmatic configuration instead, i.e. + /// call the method directly. + /// + /// + /// + /// Nicko Cadell + /// Gert Driesen + [AttributeUsage(AttributeTargets.Assembly)] + [Serializable] + public /*sealed*/ class XmlConfiguratorAttribute : ConfiguratorAttribute { - // Class is not sealed because DOMConfiguratorAttribute extends it while it is obsoleted // + // Class is not sealed because DOMConfiguratorAttribute extends it while it is obsoleted + // /// - /// Initializes a new instance of the class. - /// Default constructor. - /// - /// - /// - /// Default constructor. - /// - /// - public XmlConfiguratorAttribute() - : base(0) /* configurator priority 0 */ - { + /// Default constructor + /// + /// + /// + /// Default constructor + /// + /// + public XmlConfiguratorAttribute() : base(0) /* configurator priority 0 */ + { + } + + /// + /// Gets or sets the filename of the configuration file. + /// + /// + /// The filename of the configuration file. + /// + /// + /// + /// If specified, this is the name of the configuration file to use with + /// the . This file path is relative to the + /// application base directory (). + /// + /// + /// The takes priority over the . + /// + /// + public string ConfigFile + { + get { return this.m_configFile; } + set { this.m_configFile = value; } + } + + /// + /// Gets or sets the extension of the configuration file. + /// + /// + /// The extension of the configuration file. + /// + /// + /// + /// If specified this is the extension for the configuration file. + /// The path to the config file is built by using the application + /// base directory (), + /// the assembly file name and the config file extension. + /// + /// + /// If the is set to MyExt then + /// possible config file names would be: MyConsoleApp.exe.MyExt or + /// MyClassLibrary.dll.MyExt. + /// + /// + /// The takes priority over the . + /// + /// + public string ConfigFileExtension + { + get { return this.m_configFileExtension; } + set { this.m_configFileExtension = value; } + } + + /// + /// Gets or sets a value indicating whether to watch the configuration file. + /// + /// + /// true if the configuration should be watched, false otherwise. + /// + /// + /// + /// If this flag is specified and set to true then the framework + /// will watch the configuration file and will reload the config each time + /// the file is modified. + /// + /// + /// The config file can only be watched if it is loaded from local disk. + /// In a No-Touch (Smart Client) deployment where the application is downloaded + /// from a web server the config file may not reside on the local disk + /// and therefore it may not be able to watch it. + /// + /// + /// Watching configuration is not supported on the SSCLI. + /// + /// + public bool Watch + { + get { return this.m_configureAndWatch; } + set { this.m_configureAndWatch = value; } + } + + /// + /// Configures the for the specified assembly. + /// + /// The assembly that this attribute was defined on. + /// The repository to configure. + /// + /// + /// Configure the repository using the . + /// The specified must extend the + /// class otherwise the will not be able to + /// configure it. + /// + /// + /// The does not extend . + public override void Configure(Assembly sourceAssembly, ILoggerRepository targetRepository) + { + IList configurationMessages = new ArrayList(); + + using (new LogLog.LogReceivedAdapter(configurationMessages)) + { + string applicationBaseDirectory = null; + try + { + applicationBaseDirectory = SystemInfo.ApplicationBaseDirectory; + } + catch + { + // Ignore this exception because it is only thrown when ApplicationBaseDirectory is a file + // and the application does not have PathDiscovery permission + } + + if (applicationBaseDirectory == null || (new Uri(applicationBaseDirectory)).IsFile) + { + this.ConfigureFromFile(sourceAssembly, targetRepository); + } + else + { + this.ConfigureFromUri(sourceAssembly, targetRepository); + } + } + + targetRepository.ConfigurationMessages = configurationMessages; } - /// - /// Gets or sets the filename of the configuration file. - /// - /// - /// The filename of the configuration file. - /// - /// - /// - /// If specified, this is the name of the configuration file to use with - /// the . This file path is relative to the - /// application base directory (). - /// - /// - /// The takes priority over the . - /// - /// - public string ConfigFile - { - get { return this.m_configFile; } - set { this.m_configFile = value; } - } - - /// - /// Gets or sets the extension of the configuration file. - /// - /// - /// The extension of the configuration file. - /// - /// - /// - /// If specified this is the extension for the configuration file. - /// The path to the config file is built by using the application - /// base directory (), - /// the assembly file name and the config file extension. - /// - /// - /// If the is set to MyExt then - /// possible config file names would be: MyConsoleApp.exe.MyExt or - /// MyClassLibrary.dll.MyExt. - /// - /// - /// The takes priority over the . - /// - /// - public string ConfigFileExtension - { - get { return this.m_configFileExtension; } - set { this.m_configFileExtension = value; } - } - - /// - /// Gets or sets a value indicating whether to watch the configuration file. - /// - /// - /// true if the configuration should be watched, false otherwise. - /// - /// - /// - /// If this flag is specified and set to true then the framework - /// will watch the configuration file and will reload the config each time - /// the file is modified. - /// - /// - /// The config file can only be watched if it is loaded from local disk. - /// In a No-Touch (Smart Client) deployment where the application is downloaded - /// from a web server the config file may not reside on the local disk - /// and therefore it may not be able to watch it. - /// - /// - /// Watching configuration is not supported on the SSCLI. - /// - /// - public bool Watch - { - get { return this.m_configureAndWatch; } - set { this.m_configureAndWatch = value; } + /// + /// Attempt to load configuration from the local file system + /// + /// The assembly that this attribute was defined on. + /// The repository to configure. + private void ConfigureFromFile(Assembly sourceAssembly, ILoggerRepository targetRepository) + { + // Work out the full path to the config file + string fullPath2ConfigFile = null; + + // Select the config file + if (this.m_configFile == null || this.m_configFile.Length == 0) + { + if (this.m_configFileExtension == null || this.m_configFileExtension.Length == 0) + { + // Use the default .config file for the AppDomain + try + { + fullPath2ConfigFile = SystemInfo.ConfigurationFileLocation; + } + catch(Exception ex) + { + LogLog.Error(declaringType, "XmlConfiguratorAttribute: Exception getting ConfigurationFileLocation. Must be able to resolve ConfigurationFileLocation when ConfigFile and ConfigFileExtension properties are not set.", ex); + } + } + else + { + // Force the extension to start with a '.' + if (this.m_configFileExtension[0] != '.') + { + this.m_configFileExtension = "." + this.m_configFileExtension; + } + + string applicationBaseDirectory = null; + try + { + applicationBaseDirectory = SystemInfo.ApplicationBaseDirectory; + } + catch(Exception ex) + { + LogLog.Error(declaringType, "Exception getting ApplicationBaseDirectory. Must be able to resolve ApplicationBaseDirectory and AssemblyFileName when ConfigFileExtension property is set.", ex); + } + + if (applicationBaseDirectory != null) + { + fullPath2ConfigFile = Path.Combine(applicationBaseDirectory, SystemInfo.AssemblyFileName(sourceAssembly) + this.m_configFileExtension); + } + } + } + else + { + string applicationBaseDirectory = null; + try + { + applicationBaseDirectory = SystemInfo.ApplicationBaseDirectory; + } + catch(Exception ex) + { + LogLog.Warn(declaringType, "Exception getting ApplicationBaseDirectory. ConfigFile property path ["+ this.m_configFile+"] will be treated as an absolute path.", ex); + } + + if (applicationBaseDirectory != null) + { + // Just the base dir + the config file + fullPath2ConfigFile = Path.Combine(applicationBaseDirectory, this.m_configFile); + } + else + { + fullPath2ConfigFile = this.m_configFile; + } + } + + if (fullPath2ConfigFile != null) + { + this.ConfigureFromFile(targetRepository, new FileInfo(fullPath2ConfigFile)); + } } - /// - /// Configures the for the specified assembly. - /// - /// The assembly that this attribute was defined on. - /// The repository to configure. - /// - /// - /// Configure the repository using the . - /// The specified must extend the - /// class otherwise the will not be able to - /// configure it. - /// - /// - /// The does not extend . - public override void Configure(Assembly sourceAssembly, ILoggerRepository targetRepository) - { - IList configurationMessages = new ArrayList(); - - using (new LogLog.LogReceivedAdapter(configurationMessages)) - { - string applicationBaseDirectory = null; - try - { - applicationBaseDirectory = SystemInfo.ApplicationBaseDirectory; - } - catch - { - // Ignore this exception because it is only thrown when ApplicationBaseDirectory is a file - // and the application does not have PathDiscovery permission - } - - if (applicationBaseDirectory == null || new Uri(applicationBaseDirectory).IsFile) - { - this.ConfigureFromFile(sourceAssembly, targetRepository); - } - else - { - this.ConfigureFromUri(sourceAssembly, targetRepository); - } - } - - targetRepository.ConfigurationMessages = configurationMessages; + /// + /// Configure the specified repository using a + /// + /// The repository to configure. + /// the FileInfo pointing to the config file + private void ConfigureFromFile(ILoggerRepository targetRepository, FileInfo configFile) + { +#if (SSCLI) + if (m_configureAndWatch) + { + LogLog.Warn(declaringType, "XmlConfiguratorAttribute: Unable to watch config file not supported on SSCLI"); + } + XmlConfigurator.Configure(targetRepository, configFile); +#else + // Do we configure just once or do we configure and then watch? + if (this.m_configureAndWatch) + { + XmlConfigurator.ConfigureAndWatch(targetRepository, configFile); + } + else + { + XmlConfigurator.Configure(targetRepository, configFile); + } +#endif } - /// - /// Attempt to load configuration from the local file system. - /// - /// The assembly that this attribute was defined on. - /// The repository to configure. - private void ConfigureFromFile(Assembly sourceAssembly, ILoggerRepository targetRepository) - { - // Work out the full path to the config file - string fullPath2ConfigFile = null; - - // Select the config file - if (this.m_configFile == null || this.m_configFile.Length == 0) - { - if (this.m_configFileExtension == null || this.m_configFileExtension.Length == 0) - { - // Use the default .config file for the AppDomain - try - { - fullPath2ConfigFile = SystemInfo.ConfigurationFileLocation; - } - catch (Exception ex) - { - LogLog.Error(declaringType, "XmlConfiguratorAttribute: Exception getting ConfigurationFileLocation. Must be able to resolve ConfigurationFileLocation when ConfigFile and ConfigFileExtension properties are not set.", ex); - } - } - else - { - // Force the extension to start with a '.' - if (this.m_configFileExtension[0] != '.') - { - this.m_configFileExtension = "." + this.m_configFileExtension; - } - - string applicationBaseDirectory = null; - try - { - applicationBaseDirectory = SystemInfo.ApplicationBaseDirectory; - } - catch (Exception ex) - { - LogLog.Error(declaringType, "Exception getting ApplicationBaseDirectory. Must be able to resolve ApplicationBaseDirectory and AssemblyFileName when ConfigFileExtension property is set.", ex); - } - - if (applicationBaseDirectory != null) - { - fullPath2ConfigFile = Path.Combine(applicationBaseDirectory, SystemInfo.AssemblyFileName(sourceAssembly) + this.m_configFileExtension); - } - } - } - else - { - string applicationBaseDirectory = null; - try - { - applicationBaseDirectory = SystemInfo.ApplicationBaseDirectory; - } - catch (Exception ex) - { - LogLog.Warn(declaringType, "Exception getting ApplicationBaseDirectory. ConfigFile property path [" + this.m_configFile + "] will be treated as an absolute path.", ex); - } - - if (applicationBaseDirectory != null) - { - // Just the base dir + the config file - fullPath2ConfigFile = Path.Combine(applicationBaseDirectory, this.m_configFile); - } - else - { - fullPath2ConfigFile = this.m_configFile; - } - } - - if (fullPath2ConfigFile != null) - { - this.ConfigureFromFile(targetRepository, new FileInfo(fullPath2ConfigFile)); - } - } - - /// - /// Configure the specified repository using a . - /// - /// The repository to configure. - /// the FileInfo pointing to the config file. - private void ConfigureFromFile(ILoggerRepository targetRepository, FileInfo configFile) - { -#if SSCLI - if (m_configureAndWatch) - { - LogLog.Warn(declaringType, "XmlConfiguratorAttribute: Unable to watch config file not supported on SSCLI"); - } - XmlConfigurator.Configure(targetRepository, configFile); -#else - // Do we configure just once or do we configure and then watch? - if (this.m_configureAndWatch) - { - XmlConfigurator.ConfigureAndWatch(targetRepository, configFile); - } - else - { - XmlConfigurator.Configure(targetRepository, configFile); - } -#endif - } - - /// - /// Attempt to load configuration from a URI. - /// - /// The assembly that this attribute was defined on. - /// The repository to configure. - private void ConfigureFromUri(Assembly sourceAssembly, ILoggerRepository targetRepository) - { - // Work out the full path to the config file - Uri fullPath2ConfigFile = null; - - // Select the config file - if (this.m_configFile == null || this.m_configFile.Length == 0) - { - if (this.m_configFileExtension == null || this.m_configFileExtension.Length == 0) - { - string systemConfigFilePath = null; - try - { - systemConfigFilePath = SystemInfo.ConfigurationFileLocation; - } - catch (Exception ex) - { - LogLog.Error(declaringType, "XmlConfiguratorAttribute: Exception getting ConfigurationFileLocation. Must be able to resolve ConfigurationFileLocation when ConfigFile and ConfigFileExtension properties are not set.", ex); - } - - if (systemConfigFilePath != null) - { - Uri systemConfigFileUri = new Uri(systemConfigFilePath); - - // Use the default .config file for the AppDomain - fullPath2ConfigFile = systemConfigFileUri; - } - } - else - { - // Force the extension to start with a '.' - if (this.m_configFileExtension[0] != '.') - { - this.m_configFileExtension = "." + this.m_configFileExtension; - } - - string systemConfigFilePath = null; - try - { - systemConfigFilePath = SystemInfo.ConfigurationFileLocation; - } - catch (Exception ex) - { - LogLog.Error(declaringType, "XmlConfiguratorAttribute: Exception getting ConfigurationFileLocation. Must be able to resolve ConfigurationFileLocation when the ConfigFile property are not set.", ex); - } - - if (systemConfigFilePath != null) - { - UriBuilder builder = new UriBuilder(new Uri(systemConfigFilePath)); - - // Remove the current extension from the systemConfigFileUri path - string path = builder.Path; - int startOfExtension = path.LastIndexOf("."); - if (startOfExtension >= 0) - { - path = path.Substring(0, startOfExtension); - } + /// + /// Attempt to load configuration from a URI + /// + /// The assembly that this attribute was defined on. + /// The repository to configure. + private void ConfigureFromUri(Assembly sourceAssembly, ILoggerRepository targetRepository) + { + // Work out the full path to the config file + Uri fullPath2ConfigFile = null; + + // Select the config file + if (this.m_configFile == null || this.m_configFile.Length == 0) + { + if (this.m_configFileExtension == null || this.m_configFileExtension.Length == 0) + { + string systemConfigFilePath = null; + try + { + systemConfigFilePath = SystemInfo.ConfigurationFileLocation; + } + catch(Exception ex) + { + LogLog.Error(declaringType, "XmlConfiguratorAttribute: Exception getting ConfigurationFileLocation. Must be able to resolve ConfigurationFileLocation when ConfigFile and ConfigFileExtension properties are not set.", ex); + } - path += this.m_configFileExtension; - - builder.Path = path; - fullPath2ConfigFile = builder.Uri; - } - } - } - else - { - string applicationBaseDirectory = null; - try - { - applicationBaseDirectory = SystemInfo.ApplicationBaseDirectory; - } - catch (Exception ex) - { - LogLog.Warn(declaringType, "Exception getting ApplicationBaseDirectory. ConfigFile property path [" + this.m_configFile + "] will be treated as an absolute URI.", ex); - } - - if (applicationBaseDirectory != null) - { - // Just the base dir + the config file - fullPath2ConfigFile = new Uri(new Uri(applicationBaseDirectory), this.m_configFile); - } - else - { - fullPath2ConfigFile = new Uri(this.m_configFile); - } - } - - if (fullPath2ConfigFile != null) - { - if (fullPath2ConfigFile.IsFile) - { - // The m_configFile could be an absolute local path, therefore we have to be - // prepared to switch back to using FileInfos here - this.ConfigureFromFile(targetRepository, new FileInfo(fullPath2ConfigFile.LocalPath)); - } - else - { - if (this.m_configureAndWatch) - { - LogLog.Warn(declaringType, "XmlConfiguratorAttribute: Unable to watch config file loaded from a URI"); - } + if (systemConfigFilePath != null) + { + Uri systemConfigFileUri = new Uri(systemConfigFilePath); - XmlConfigurator.Configure(targetRepository, fullPath2ConfigFile); - } - } + // Use the default .config file for the AppDomain + fullPath2ConfigFile = systemConfigFileUri; + } + } + else + { + // Force the extension to start with a '.' + if (this.m_configFileExtension[0] != '.') + { + this.m_configFileExtension = "." + this.m_configFileExtension; + } + + string systemConfigFilePath = null; + try + { + systemConfigFilePath = SystemInfo.ConfigurationFileLocation; + } + catch(Exception ex) + { + LogLog.Error(declaringType, "XmlConfiguratorAttribute: Exception getting ConfigurationFileLocation. Must be able to resolve ConfigurationFileLocation when the ConfigFile property are not set.", ex); + } + + if (systemConfigFilePath != null) + { + UriBuilder builder = new UriBuilder(new Uri(systemConfigFilePath)); + + // Remove the current extension from the systemConfigFileUri path + string path = builder.Path; + int startOfExtension = path.LastIndexOf("."); + if (startOfExtension >= 0) + { + path = path.Substring(0, startOfExtension); + } + path += this.m_configFileExtension; + + builder.Path = path; + fullPath2ConfigFile = builder.Uri; + } + } + } + else + { + string applicationBaseDirectory = null; + try + { + applicationBaseDirectory = SystemInfo.ApplicationBaseDirectory; + } + catch(Exception ex) + { + LogLog.Warn(declaringType, "Exception getting ApplicationBaseDirectory. ConfigFile property path ["+ this.m_configFile+"] will be treated as an absolute URI.", ex); + } + + if (applicationBaseDirectory != null) + { + // Just the base dir + the config file + fullPath2ConfigFile = new Uri(new Uri(applicationBaseDirectory), this.m_configFile); + } + else + { + fullPath2ConfigFile = new Uri(this.m_configFile); + } + } + + if (fullPath2ConfigFile != null) + { + if (fullPath2ConfigFile.IsFile) + { + // The m_configFile could be an absolute local path, therefore we have to be + // prepared to switch back to using FileInfos here + this.ConfigureFromFile(targetRepository, new FileInfo(fullPath2ConfigFile.LocalPath)); + } + else + { + if (this.m_configureAndWatch) + { + LogLog.Warn(declaringType, "XmlConfiguratorAttribute: Unable to watch config file loaded from a URI"); + } + XmlConfigurator.Configure(targetRepository, fullPath2ConfigFile); + } + } } - private string m_configFile = null; - private string m_configFileExtension = null; + private string m_configFile = null; + private string m_configFileExtension = null; private bool m_configureAndWatch = false; - /// - /// The fully qualified type of the XmlConfiguratorAttribute class. - /// - /// - /// Used by the internal logger to record the Type of the - /// log message. - /// + /// + /// The fully qualified type of the XmlConfiguratorAttribute class. + /// + /// + /// Used by the internal logger to record the Type of the + /// log message. + /// private static readonly Type declaringType = typeof(XmlConfiguratorAttribute); - } -} - -#endif // !NETCF + } +} + +#endif // !NETCF diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Core/CompactRepositorySelector.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Core/CompactRepositorySelector.cs index 38080144f88..2a7c8736ad3 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Core/CompactRepositorySelector.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Core/CompactRepositorySelector.cs @@ -1,343 +1,342 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.Core -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; - using System.Collections; - using System.Reflection; +using System; +using System.Collections; +using System.Reflection; - using log4net.Appender; - using log4net.Repository; - using log4net.Util; +using log4net.Appender; +using log4net.Util; +using log4net.Repository; - /// - /// The implementation of the interface suitable - /// for use with the compact framework. - /// - /// - /// - /// This implementation is a simple - /// mapping between repository name and - /// object. - /// - /// - /// The .NET Compact Framework 1.0 does not support retrieving assembly - /// level attributes therefore unlike the DefaultRepositorySelector - /// this selector does not examine the calling assembly for attributes. - /// - /// - /// Nicko Cadell. - public class CompactRepositorySelector : IRepositorySelector + +namespace log4net.Core +{ + /// + /// The implementation of the interface suitable + /// for use with the compact framework + /// + /// + /// + /// This implementation is a simple + /// mapping between repository name and + /// object. + /// + /// + /// The .NET Compact Framework 1.0 does not support retrieving assembly + /// level attributes therefore unlike the DefaultRepositorySelector + /// this selector does not examine the calling assembly for attributes. + /// + /// + /// Nicko Cadell + public class CompactRepositorySelector : IRepositorySelector { - private const string DefaultRepositoryName = "log4net-default-repository"; - - private readonly Hashtable m_name2repositoryMap = new Hashtable(); - private readonly Type m_defaultRepositoryType; - + private const string DefaultRepositoryName = "log4net-default-repository"; + + private readonly Hashtable m_name2repositoryMap = new Hashtable(); + private readonly Type m_defaultRepositoryType; + private event LoggerRepositoryCreationEventHandler m_loggerRepositoryCreatedEvent; /// - /// Initializes a new instance of the class. - /// Create a new repository selector. - /// - /// the type of the repositories to create, must implement . - /// - /// - /// Create an new compact repository selector. - /// The default type for repositories must be specified, - /// an appropriate value would be . - /// - /// - /// throw if is null. - /// throw if does not implement . - public CompactRepositorySelector(Type defaultRepositoryType) - { - if (defaultRepositoryType == null) - { - throw new ArgumentNullException("defaultRepositoryType"); - } - - // Check that the type is a repository - if (!typeof(ILoggerRepository).IsAssignableFrom(defaultRepositoryType)) - { - throw log4net.Util.SystemInfo.CreateArgumentOutOfRangeException("defaultRepositoryType", (object)defaultRepositoryType, "Parameter: defaultRepositoryType, Value: [" + defaultRepositoryType + "] out of range. Argument must implement the ILoggerRepository interface"); - } - - this.m_defaultRepositoryType = defaultRepositoryType; - - LogLog.Debug(declaringType, "defaultRepositoryType [" + this.m_defaultRepositoryType + "]"); + /// Create a new repository selector + /// + /// the type of the repositories to create, must implement + /// + /// + /// Create an new compact repository selector. + /// The default type for repositories must be specified, + /// an appropriate value would be . + /// + /// + /// throw if is null + /// throw if does not implement + public CompactRepositorySelector(Type defaultRepositoryType) + { + if (defaultRepositoryType == null) + { + throw new ArgumentNullException("defaultRepositoryType"); + } + + // Check that the type is a repository + if (!(typeof(ILoggerRepository).IsAssignableFrom(defaultRepositoryType))) + { + throw SystemInfo.CreateArgumentOutOfRangeException("defaultRepositoryType", (object)defaultRepositoryType, "Parameter: defaultRepositoryType, Value: ["+defaultRepositoryType+"] out of range. Argument must implement the ILoggerRepository interface"); + } + + this.m_defaultRepositoryType = defaultRepositoryType; + + LogLog.Debug(declaringType, "defaultRepositoryType ["+ this.m_defaultRepositoryType+"]"); + } + + /// + /// Get the for the specified assembly + /// + /// not used + /// The default + /// + /// + /// The argument is not used. This selector does not create a + /// separate repository for each assembly. + /// + /// + /// As a named repository is not specified the default repository is + /// returned. The default repository is named log4net-default-repository. + /// + /// + public ILoggerRepository GetRepository(Assembly assembly) + { + return this.CreateRepository(assembly, this.m_defaultRepositoryType); + } + + /// + /// Get the named + /// + /// the name of the repository to lookup + /// The named + /// + /// + /// Get the named . The default + /// repository is log4net-default-repository. Other repositories + /// must be created using the . + /// If the named repository does not exist an exception is thrown. + /// + /// + /// throw if is null + /// throw if the does not exist + public ILoggerRepository GetRepository(string repositoryName) + { + if (repositoryName == null) + { + throw new ArgumentNullException("repositoryName"); + } + + lock(this) + { + // Lookup in map + ILoggerRepository rep = this.m_name2repositoryMap[repositoryName] as ILoggerRepository; + if (rep == null) + { + throw new LogException("Repository [" + repositoryName + "] is NOT defined."); + } + return rep; + } } - /// - /// Get the for the specified assembly. - /// - /// not used. - /// The default . - /// - /// - /// The argument is not used. This selector does not create a - /// separate repository for each assembly. - /// - /// - /// As a named repository is not specified the default repository is - /// returned. The default repository is named log4net-default-repository. - /// - /// - public ILoggerRepository GetRepository(Assembly assembly) - { - return this.CreateRepository(assembly, this.m_defaultRepositoryType); - } - - /// - /// Get the named . - /// - /// the name of the repository to lookup. - /// The named . - /// - /// - /// Get the named . The default - /// repository is log4net-default-repository. Other repositories - /// must be created using the . - /// If the named repository does not exist an exception is thrown. - /// - /// - /// throw if is null. - /// throw if the does not exist. - public ILoggerRepository GetRepository(string repositoryName) - { - if (repositoryName == null) - { - throw new ArgumentNullException("repositoryName"); - } - - lock (this) - { - // Lookup in map - ILoggerRepository rep = this.m_name2repositoryMap[repositoryName] as ILoggerRepository; - if (rep == null) - { - throw new LogException("Repository [" + repositoryName + "] is NOT defined."); - } + /// + /// Create a new repository for the assembly specified + /// + /// not used + /// the type of repository to create, must implement + /// the repository created + /// + /// + /// The argument is not used. This selector does not create a + /// separate repository for each assembly. + /// + /// + /// If the is null then the + /// default repository type specified to the constructor is used. + /// + /// + /// As a named repository is not specified the default repository is + /// returned. The default repository is named log4net-default-repository. + /// + /// + public ILoggerRepository CreateRepository(Assembly assembly, Type repositoryType) + { + // If the type is not set then use the default type + if (repositoryType == null) + { + repositoryType = this.m_defaultRepositoryType; + } + + lock(this) + { + // This method should not throw if the default repository already exists. - return rep; - } - } - - /// - /// Create a new repository for the assembly specified. - /// - /// not used. - /// the type of repository to create, must implement . - /// the repository created. - /// - /// - /// The argument is not used. This selector does not create a - /// separate repository for each assembly. - /// - /// - /// If the is null then the - /// default repository type specified to the constructor is used. - /// - /// - /// As a named repository is not specified the default repository is - /// returned. The default repository is named log4net-default-repository. - /// - /// - public ILoggerRepository CreateRepository(Assembly assembly, Type repositoryType) - { - // If the type is not set then use the default type - if (repositoryType == null) - { - repositoryType = this.m_defaultRepositoryType; - } - - lock (this) - { - // This method should not throw if the default repository already exists. - - // First check that the repository does not exist - ILoggerRepository rep = this.m_name2repositoryMap[DefaultRepositoryName] as ILoggerRepository; - if (rep == null) - { - // Must create the repository - rep = this.CreateRepository(DefaultRepositoryName, repositoryType); - } - - return rep; - } - } - - /// - /// Create a new repository for the repository specified. - /// - /// the repository to associate with the . - /// the type of repository to create, must implement . - /// If this param is null then the default repository type is used. - /// the repository created. - /// - /// - /// The created will be associated with the repository - /// specified such that a call to with the - /// same repository specified will return the same repository instance. - /// - /// - /// If the named repository already exists an exception will be thrown. - /// - /// - /// If is null then the default - /// repository type specified to the constructor is used. - /// - /// - /// throw if is null. - /// throw if the already exists. - public ILoggerRepository CreateRepository(string repositoryName, Type repositoryType) - { - if (repositoryName == null) - { - throw new ArgumentNullException("repositoryName"); - } - - // If the type is not set then use the default type - if (repositoryType == null) - { - repositoryType = this.m_defaultRepositoryType; - } - - lock (this) - { - ILoggerRepository rep = null; - - // First check that the repository does not exist - rep = this.m_name2repositoryMap[repositoryName] as ILoggerRepository; - if (rep != null) - { - throw new LogException("Repository [" + repositoryName + "] is already defined. Repositories cannot be redefined."); - } - else - { - LogLog.Debug(declaringType, "Creating repository [" + repositoryName + "] using type [" + repositoryType + "]"); - - // Call the no arg constructor for the repositoryType - rep = (ILoggerRepository)Activator.CreateInstance(repositoryType); - - // Set the name of the repository - rep.Name = repositoryName; - - // Store in map - this.m_name2repositoryMap[repositoryName] = rep; - - // Notify listeners that the repository has been created - this.OnLoggerRepositoryCreatedEvent(rep); - } - - return rep; - } - } - - /// - /// Test if a named repository exists. - /// - /// the named repository to check. - /// true if the repository exists. - /// - /// - /// Test if a named repository exists. Use - /// to create a new repository and to retrieve - /// a repository. - /// - /// - public bool ExistsRepository(string repositoryName) - { - lock (this) - { - return this.m_name2repositoryMap.ContainsKey(repositoryName); - } - } - - /// - /// Gets a list of objects. - /// - /// an array of all known objects. - /// - /// - /// Gets an array of all of the repositories created by this selector. - /// - /// - public ILoggerRepository[] GetAllRepositories() - { - lock (this) - { - ICollection reps = this.m_name2repositoryMap.Values; - ILoggerRepository[] all = new ILoggerRepository[reps.Count]; - reps.CopyTo(all, 0); - return all; - } + // First check that the repository does not exist + ILoggerRepository rep = this.m_name2repositoryMap[DefaultRepositoryName] as ILoggerRepository; + if (rep == null) + { + // Must create the repository + rep = this.CreateRepository(DefaultRepositoryName, repositoryType); + } + + return rep; + } } - /// - /// The fully qualified type of the CompactRepositorySelector class. - /// - /// - /// Used by the internal logger to record the Type of the - /// log message. - /// + /// + /// Create a new repository for the repository specified + /// + /// the repository to associate with the + /// the type of repository to create, must implement . + /// If this param is null then the default repository type is used. + /// the repository created + /// + /// + /// The created will be associated with the repository + /// specified such that a call to with the + /// same repository specified will return the same repository instance. + /// + /// + /// If the named repository already exists an exception will be thrown. + /// + /// + /// If is null then the default + /// repository type specified to the constructor is used. + /// + /// + /// throw if is null + /// throw if the already exists + public ILoggerRepository CreateRepository(string repositoryName, Type repositoryType) + { + if (repositoryName == null) + { + throw new ArgumentNullException("repositoryName"); + } + + // If the type is not set then use the default type + if (repositoryType == null) + { + repositoryType = this.m_defaultRepositoryType; + } + + lock(this) + { + ILoggerRepository rep = null; + + // First check that the repository does not exist + rep = this.m_name2repositoryMap[repositoryName] as ILoggerRepository; + if (rep != null) + { + throw new LogException("Repository [" + repositoryName + "] is already defined. Repositories cannot be redefined."); + } + else + { + LogLog.Debug(declaringType, "Creating repository [" + repositoryName + "] using type [" + repositoryType + "]"); + + // Call the no arg constructor for the repositoryType + rep = (ILoggerRepository)Activator.CreateInstance(repositoryType); + + // Set the name of the repository + rep.Name = repositoryName; + + // Store in map + this.m_name2repositoryMap[repositoryName] = rep; + + // Notify listeners that the repository has been created + this.OnLoggerRepositoryCreatedEvent(rep); + } + + return rep; + } + } + + /// + /// Test if a named repository exists + /// + /// the named repository to check + /// true if the repository exists + /// + /// + /// Test if a named repository exists. Use + /// to create a new repository and to retrieve + /// a repository. + /// + /// + public bool ExistsRepository(string repositoryName) + { + lock(this) + { + return this.m_name2repositoryMap.ContainsKey(repositoryName); + } + } + + /// + /// Gets a list of objects + /// + /// an array of all known objects + /// + /// + /// Gets an array of all of the repositories created by this selector. + /// + /// + public ILoggerRepository[] GetAllRepositories() + { + lock(this) + { + ICollection reps = this.m_name2repositoryMap.Values; + ILoggerRepository[] all = new ILoggerRepository[reps.Count]; + reps.CopyTo(all, 0); + return all; + } + } + + /// + /// The fully qualified type of the CompactRepositorySelector class. + /// + /// + /// Used by the internal logger to record the Type of the + /// log message. + /// private static readonly Type declaringType = typeof(CompactRepositorySelector); - /// - /// Event to notify that a logger repository has been created. - /// - /// - /// Event to notify that a logger repository has been created. - /// - /// - /// - /// Event raised when a new repository is created. - /// The event source will be this selector. The event args will - /// be a which - /// holds the newly created . - /// - /// - public event LoggerRepositoryCreationEventHandler LoggerRepositoryCreatedEvent - { - add { this.m_loggerRepositoryCreatedEvent += value; } - remove { this.m_loggerRepositoryCreatedEvent -= value; } - } - - /// - /// Notify the registered listeners that the repository has been created. - /// - /// The repository that has been created. - /// - /// - /// Raises the LoggerRepositoryCreatedEvent - /// event. - /// - /// - protected virtual void OnLoggerRepositoryCreatedEvent(ILoggerRepository repository) - { - LoggerRepositoryCreationEventHandler handler = this.m_loggerRepositoryCreatedEvent; - if (handler != null) - { - handler(this, new LoggerRepositoryCreationEventArgs(repository)); - } - } - } -} + /// + /// Event to notify that a logger repository has been created. + /// + /// + /// Event to notify that a logger repository has been created. + /// + /// + /// + /// Event raised when a new repository is created. + /// The event source will be this selector. The event args will + /// be a which + /// holds the newly created . + /// + /// + public event LoggerRepositoryCreationEventHandler LoggerRepositoryCreatedEvent + { + add { this.m_loggerRepositoryCreatedEvent += value; } + remove { this.m_loggerRepositoryCreatedEvent -= value; } + } + + /// + /// Notify the registered listeners that the repository has been created + /// + /// The repository that has been created + /// + /// + /// Raises the LoggerRepositoryCreatedEvent + /// event. + /// + /// + protected virtual void OnLoggerRepositoryCreatedEvent(ILoggerRepository repository) + { + LoggerRepositoryCreationEventHandler handler = this.m_loggerRepositoryCreatedEvent; + if (handler != null) + { + handler(this, new LoggerRepositoryCreationEventArgs(repository)); + } + } + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Core/DefaultRepositorySelector.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Core/DefaultRepositorySelector.cs index be3f8d6bcfe..48fc364b17f 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Core/DefaultRepositorySelector.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Core/DefaultRepositorySelector.cs @@ -1,894 +1,883 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -// .NET Compact Framework 1.0 has no support for reading assembly attributes -// and uses the CompactRepositorySelector instead -#if !NETCF - -using System; -using System.Collections; - -#if !NETSTANDARD1_3 -using System.Configuration; - -#else -using System.Linq; -#endif -using System.IO; -using System.Reflection; - -using log4net.Config; -using log4net.Repository; -using log4net.Util; - -namespace log4net.Core -{ - /// - /// The default implementation of the interface. - /// - /// - /// - /// Uses attributes defined on the calling assembly to determine how to - /// configure the hierarchy for the repository. - /// - /// - /// Nicko Cadell. - /// Gert Driesen. - public class DefaultRepositorySelector : IRepositorySelector +// .NET Compact Framework 1.0 has no support for reading assembly attributes +// and uses the CompactRepositorySelector instead +#if !NETCF + +using System; +using System.Collections; +#if !NETSTANDARD +using System.Configuration; +#else +using System.Linq; +#endif +using System.IO; +using System.Reflection; + +using log4net.Config; +using log4net.Util; +using log4net.Repository; + +namespace log4net.Core +{ + /// + /// The default implementation of the interface. + /// + /// + /// + /// Uses attributes defined on the calling assembly to determine how to + /// configure the hierarchy for the repository. + /// + /// + /// Nicko Cadell + /// Gert Driesen + public class DefaultRepositorySelector : IRepositorySelector { - /// - /// Event to notify that a logger repository has been created. - /// - /// - /// Event to notify that a logger repository has been created. - /// - /// - /// - /// Event raised when a new repository is created. - /// The event source will be this selector. The event args will - /// be a which - /// holds the newly created . - /// - /// - public event LoggerRepositoryCreationEventHandler LoggerRepositoryCreatedEvent - { - add { this.m_loggerRepositoryCreatedEvent += value; } - remove { this.m_loggerRepositoryCreatedEvent -= value; } + /// + /// Event to notify that a logger repository has been created. + /// + /// + /// Event to notify that a logger repository has been created. + /// + /// + /// + /// Event raised when a new repository is created. + /// The event source will be this selector. The event args will + /// be a which + /// holds the newly created . + /// + /// + public event LoggerRepositoryCreationEventHandler LoggerRepositoryCreatedEvent + { + add { this.m_loggerRepositoryCreatedEvent += value; } + remove { this.m_loggerRepositoryCreatedEvent -= value; } } /// - /// Initializes a new instance of the class. - /// Creates a new repository selector. - /// - /// The type of the repositories to create, must implement . - /// - /// - /// Create an new repository selector. - /// The default type for repositories must be specified, - /// an appropriate value would be . - /// - /// - /// is . - /// does not implement . - public DefaultRepositorySelector(Type defaultRepositoryType) - { - if (defaultRepositoryType == null) - { - throw new ArgumentNullException("defaultRepositoryType"); - } - - // Check that the type is a repository - if (!typeof(ILoggerRepository).IsAssignableFrom(defaultRepositoryType)) - { - throw log4net.Util.SystemInfo.CreateArgumentOutOfRangeException("defaultRepositoryType", defaultRepositoryType, "Parameter: defaultRepositoryType, Value: [" + defaultRepositoryType + "] out of range. Argument must implement the ILoggerRepository interface"); - } - - this.m_defaultRepositoryType = defaultRepositoryType; - - LogLog.Debug(declaringType, "defaultRepositoryType [" + this.m_defaultRepositoryType + "]"); + /// Creates a new repository selector. + /// + /// The type of the repositories to create, must implement + /// + /// + /// Create an new repository selector. + /// The default type for repositories must be specified, + /// an appropriate value would be . + /// + /// + /// is . + /// does not implement . + public DefaultRepositorySelector(Type defaultRepositoryType) + { + if (defaultRepositoryType == null) + { + throw new ArgumentNullException("defaultRepositoryType"); + } + + // Check that the type is a repository + if (!(typeof(ILoggerRepository).IsAssignableFrom(defaultRepositoryType))) + { + throw SystemInfo.CreateArgumentOutOfRangeException("defaultRepositoryType", defaultRepositoryType, "Parameter: defaultRepositoryType, Value: [" + defaultRepositoryType + "] out of range. Argument must implement the ILoggerRepository interface"); + } + + this.m_defaultRepositoryType = defaultRepositoryType; + + LogLog.Debug(declaringType, "defaultRepositoryType [" + this.m_defaultRepositoryType + "]"); } - /// - /// Gets the for the specified assembly. - /// - /// The assembly use to lookup the . - /// - /// - /// The type of the created and the repository - /// to create can be overridden by specifying the - /// attribute on the . - /// - /// - /// The default values are to use the - /// implementation of the interface and to use the - /// as the name of the repository. - /// - /// - /// The created will be automatically configured using - /// any attributes defined on - /// the . - /// - /// - /// The for the assembly. - /// is . - public ILoggerRepository GetRepository(Assembly repositoryAssembly) - { - if (repositoryAssembly == null) - { - throw new ArgumentNullException("repositoryAssembly"); - } - - return this.CreateRepository(repositoryAssembly, this.m_defaultRepositoryType); - } - - /// - /// Gets the for the specified repository. - /// - /// The repository to use to lookup the . - /// The for the specified repository. - /// - /// - /// Returns the named repository. If is null - /// a is thrown. If the repository - /// does not exist a is thrown. - /// - /// - /// Use to create a repository. - /// - /// - /// is . - /// does not exist. - public ILoggerRepository GetRepository(string repositoryName) - { - if (repositoryName == null) - { - throw new ArgumentNullException("repositoryName"); - } - - lock (this) - { - // Lookup in map - ILoggerRepository rep = this.m_name2repositoryMap[repositoryName] as ILoggerRepository; - if (rep == null) - { - throw new LogException("Repository [" + repositoryName + "] is NOT defined."); - } - - return rep; - } - } - - /// - /// Create a new repository for the assembly specified. - /// - /// the assembly to use to create the repository to associate with the . - /// The type of repository to create, must implement . - /// The repository created. - /// - /// - /// The created will be associated with the repository - /// specified such that a call to with the - /// same assembly specified will return the same repository instance. - /// - /// - /// The type of the created and - /// the repository to create can be overridden by specifying the - /// attribute on the - /// . The default values are to use the - /// implementation of the - /// interface and to use the - /// as the name of the repository. - /// - /// - /// The created will be automatically - /// configured using any - /// attributes defined on the . - /// - /// - /// If a repository for the already exists - /// that repository will be returned. An error will not be raised and that - /// repository may be of a different type to that specified in . - /// Also the attribute on the - /// assembly may be used to override the repository type specified in - /// . - /// - /// - /// is . - public ILoggerRepository CreateRepository(Assembly repositoryAssembly, Type repositoryType) - { - return this.CreateRepository(repositoryAssembly, repositoryType, DefaultRepositoryName, true); - } - - /// - /// Creates a new repository for the assembly specified. - /// - /// the assembly to use to create the repository to associate with the . - /// The type of repository to create, must implement . - /// The name to assign to the created repository. - /// Set to true to read and apply the assembly attributes. - /// The repository created. - /// - /// - /// The created will be associated with the repository - /// specified such that a call to with the - /// same assembly specified will return the same repository instance. - /// - /// - /// The type of the created and - /// the repository to create can be overridden by specifying the - /// attribute on the - /// . The default values are to use the - /// implementation of the - /// interface and to use the - /// as the name of the repository. - /// - /// - /// The created will be automatically - /// configured using any - /// attributes defined on the . - /// - /// - /// If a repository for the already exists - /// that repository will be returned. An error will not be raised and that - /// repository may be of a different type to that specified in . - /// Also the attribute on the - /// assembly may be used to override the repository type specified in - /// . - /// - /// - /// is . - public ILoggerRepository CreateRepository(Assembly repositoryAssembly, Type repositoryType, string repositoryName, bool readAssemblyAttributes) - { - if (repositoryAssembly == null) - { - throw new ArgumentNullException("repositoryAssembly"); - } - - // If the type is not set then use the default type - if (repositoryType == null) - { - repositoryType = this.m_defaultRepositoryType; - } - - lock (this) - { - // Lookup in map - ILoggerRepository rep = this.m_assembly2repositoryMap[repositoryAssembly] as ILoggerRepository; - if (rep == null) - { - // Not found, therefore create - LogLog.Debug(declaringType, "Creating repository for assembly [" + repositoryAssembly + "]"); - - // Must specify defaults - string actualRepositoryName = repositoryName; - Type actualRepositoryType = repositoryType; - - if (readAssemblyAttributes) - { - // Get the repository and type from the assembly attributes - this.GetInfoForAssembly(repositoryAssembly, ref actualRepositoryName, ref actualRepositoryType); - } - - LogLog.Debug(declaringType, "Assembly [" + repositoryAssembly + "] using repository [" + actualRepositoryName + "] and repository type [" + actualRepositoryType + "]"); - - // Lookup the repository in the map (as this may already be defined) - rep = this.m_name2repositoryMap[actualRepositoryName] as ILoggerRepository; - if (rep == null) - { - // Create the repository - rep = this.CreateRepository(actualRepositoryName, actualRepositoryType); - - if (readAssemblyAttributes) - { - try - { - // Look for aliasing attributes - this.LoadAliases(repositoryAssembly, rep); - - // Look for plugins defined on the assembly - this.LoadPlugins(repositoryAssembly, rep); - - // Configure the repository using the assembly attributes - this.ConfigureRepository(repositoryAssembly, rep); - } - catch (Exception ex) - { - LogLog.Error(declaringType, "Failed to configure repository [" + actualRepositoryName + "] from assembly attributes.", ex); - } - } - } - else - { - LogLog.Debug(declaringType, "repository [" + actualRepositoryName + "] already exists, using repository type [" + rep.GetType().FullName + "]"); - - if (readAssemblyAttributes) - { - try - { - // Look for plugins defined on the assembly - this.LoadPlugins(repositoryAssembly, rep); - } - catch (Exception ex) - { - LogLog.Error(declaringType, "Failed to configure repository [" + actualRepositoryName + "] from assembly attributes.", ex); - } - } - } - - this.m_assembly2repositoryMap[repositoryAssembly] = rep; - } - - return rep; - } - } - - /// - /// Creates a new repository for the specified repository. - /// - /// The repository to associate with the . - /// The type of repository to create, must implement . - /// If this param is then the default repository type is used. - /// The new repository. - /// - /// - /// The created will be associated with the repository - /// specified such that a call to with the - /// same repository specified will return the same repository instance. - /// - /// - /// is . - /// already exists. - public ILoggerRepository CreateRepository(string repositoryName, Type repositoryType) - { - if (repositoryName == null) - { - throw new ArgumentNullException("repositoryName"); - } - - // If the type is not set then use the default type - if (repositoryType == null) - { - repositoryType = this.m_defaultRepositoryType; - } - - lock (this) - { - ILoggerRepository rep = null; - - // First check that the repository does not exist - rep = this.m_name2repositoryMap[repositoryName] as ILoggerRepository; - if (rep != null) - { - throw new LogException("Repository [" + repositoryName + "] is already defined. Repositories cannot be redefined."); - } - else - { - // Lookup an alias before trying to create the new repository - ILoggerRepository aliasedRepository = this.m_alias2repositoryMap[repositoryName] as ILoggerRepository; - if (aliasedRepository != null) - { - // Found an alias - - // Check repository type - if (aliasedRepository.GetType() == repositoryType) - { - // Repository type is compatible - LogLog.Debug(declaringType, "Aliasing repository [" + repositoryName + "] to existing repository [" + aliasedRepository.Name + "]"); - rep = aliasedRepository; - - // Store in map - this.m_name2repositoryMap[repositoryName] = rep; - } - else - { - // Invalid repository type for alias - LogLog.Error(declaringType, "Failed to alias repository [" + repositoryName + "] to existing repository [" + aliasedRepository.Name + "]. Requested repository type [" + repositoryType.FullName + "] is not compatible with existing type [" + aliasedRepository.GetType().FullName + "]"); - - // We now drop through to create the repository without aliasing - } - } - - // If we could not find an alias - if (rep == null) - { - LogLog.Debug(declaringType, "Creating repository [" + repositoryName + "] using type [" + repositoryType + "]"); - - // Call the no arg constructor for the repositoryType - rep = (ILoggerRepository)Activator.CreateInstance(repositoryType); - - // Set the name of the repository - rep.Name = repositoryName; - - // Store in map - this.m_name2repositoryMap[repositoryName] = rep; - - // Notify listeners that the repository has been created - this.OnLoggerRepositoryCreatedEvent(rep); - } - } - - return rep; - } - } - - /// - /// Test if a named repository exists. - /// - /// the named repository to check. - /// true if the repository exists. - /// - /// - /// Test if a named repository exists. Use - /// to create a new repository and to retrieve - /// a repository. - /// - /// - public bool ExistsRepository(string repositoryName) - { - lock (this) - { - return this.m_name2repositoryMap.ContainsKey(repositoryName); - } - } - - /// - /// Gets a list of objects. - /// - /// an array of all known objects. - /// - /// - /// Gets an array of all of the repositories created by this selector. - /// - /// - public ILoggerRepository[] GetAllRepositories() - { - lock (this) - { - ICollection reps = this.m_name2repositoryMap.Values; - ILoggerRepository[] all = new ILoggerRepository[reps.Count]; - reps.CopyTo(all, 0); - return all; - } + /// + /// Gets the for the specified assembly. + /// + /// The assembly use to lookup the . + /// + /// + /// The type of the created and the repository + /// to create can be overridden by specifying the + /// attribute on the . + /// + /// + /// The default values are to use the + /// implementation of the interface and to use the + /// as the name of the repository. + /// + /// + /// The created will be automatically configured using + /// any attributes defined on + /// the . + /// + /// + /// The for the assembly + /// is . + public ILoggerRepository GetRepository(Assembly repositoryAssembly) + { + if (repositoryAssembly == null) + { + throw new ArgumentNullException("repositoryAssembly"); + } + return this.CreateRepository(repositoryAssembly, this.m_defaultRepositoryType); } - /// - /// Aliases a repository to an existing repository. - /// - /// The repository to alias. - /// The repository that the repository is aliased to. - /// - /// - /// The repository specified will be aliased to the repository when created. - /// The repository must not already exist. - /// - /// - /// When the repository is created it must utilize the same repository type as - /// the repository it is aliased to, otherwise the aliasing will fail. - /// - /// - /// - /// is . - /// -or- - /// is . - /// - public void AliasRepository(string repositoryAlias, ILoggerRepository repositoryTarget) - { - if (repositoryAlias == null) - { - throw new ArgumentNullException("repositoryAlias"); - } - - if (repositoryTarget == null) - { - throw new ArgumentNullException("repositoryTarget"); - } - - lock (this) - { - // Check if the alias is already set - if (this.m_alias2repositoryMap.Contains(repositoryAlias)) - { - // Check if this is a duplicate of the current alias - if (repositoryTarget != ((ILoggerRepository)this.m_alias2repositoryMap[repositoryAlias])) - { - // Cannot redefine existing alias - throw new InvalidOperationException("Repository [" + repositoryAlias + "] is already aliased to repository [" + ((ILoggerRepository)this.m_alias2repositoryMap[repositoryAlias]).Name + "]. Aliases cannot be redefined."); - } + /// + /// Gets the for the specified repository. + /// + /// The repository to use to lookup the . + /// The for the specified repository. + /// + /// + /// Returns the named repository. If is null + /// a is thrown. If the repository + /// does not exist a is thrown. + /// + /// + /// Use to create a repository. + /// + /// + /// is . + /// does not exist. + public ILoggerRepository GetRepository(string repositoryName) + { + if (repositoryName == null) + { + throw new ArgumentNullException("repositoryName"); + } + + lock(this) + { + // Lookup in map + ILoggerRepository rep = this.m_name2repositoryMap[repositoryName] as ILoggerRepository; + if (rep == null) + { + throw new LogException("Repository [" + repositoryName + "] is NOT defined."); } + return rep; + } + } - // Check if the alias is already mapped to a repository - else if (this.m_name2repositoryMap.Contains(repositoryAlias)) - { - // Check if this is a duplicate of the current mapping - if (repositoryTarget != ((ILoggerRepository)this.m_name2repositoryMap[repositoryAlias])) - { - // Cannot define alias for already mapped repository - throw new InvalidOperationException("Repository [" + repositoryAlias + "] already exists and cannot be aliased to repository [" + repositoryTarget.Name + "]."); - } - } - else - { - // Set the alias - this.m_alias2repositoryMap[repositoryAlias] = repositoryTarget; - } - } + /// + /// Create a new repository for the assembly specified + /// + /// the assembly to use to create the repository to associate with the . + /// The type of repository to create, must implement . + /// The repository created. + /// + /// + /// The created will be associated with the repository + /// specified such that a call to with the + /// same assembly specified will return the same repository instance. + /// + /// + /// The type of the created and + /// the repository to create can be overridden by specifying the + /// attribute on the + /// . The default values are to use the + /// implementation of the + /// interface and to use the + /// as the name of the repository. + /// + /// + /// The created will be automatically + /// configured using any + /// attributes defined on the . + /// + /// + /// If a repository for the already exists + /// that repository will be returned. An error will not be raised and that + /// repository may be of a different type to that specified in . + /// Also the attribute on the + /// assembly may be used to override the repository type specified in + /// . + /// + /// + /// is . + public ILoggerRepository CreateRepository(Assembly repositoryAssembly, Type repositoryType) + { + return this.CreateRepository(repositoryAssembly, repositoryType, DefaultRepositoryName, true); } - /// - /// Notifies the registered listeners that the repository has been created. - /// - /// The repository that has been created. - /// - /// - /// Raises the event. - /// - /// - protected virtual void OnLoggerRepositoryCreatedEvent(ILoggerRepository repository) - { - LoggerRepositoryCreationEventHandler handler = this.m_loggerRepositoryCreatedEvent; - if (handler != null) - { - handler(this, new LoggerRepositoryCreationEventArgs(repository)); - } + /// + /// Creates a new repository for the assembly specified. + /// + /// the assembly to use to create the repository to associate with the . + /// The type of repository to create, must implement . + /// The name to assign to the created repository + /// Set to true to read and apply the assembly attributes + /// The repository created. + /// + /// + /// The created will be associated with the repository + /// specified such that a call to with the + /// same assembly specified will return the same repository instance. + /// + /// + /// The type of the created and + /// the repository to create can be overridden by specifying the + /// attribute on the + /// . The default values are to use the + /// implementation of the + /// interface and to use the + /// as the name of the repository. + /// + /// + /// The created will be automatically + /// configured using any + /// attributes defined on the . + /// + /// + /// If a repository for the already exists + /// that repository will be returned. An error will not be raised and that + /// repository may be of a different type to that specified in . + /// Also the attribute on the + /// assembly may be used to override the repository type specified in + /// . + /// + /// + /// is . + public ILoggerRepository CreateRepository(Assembly repositoryAssembly, Type repositoryType, string repositoryName, bool readAssemblyAttributes) + { + if (repositoryAssembly == null) + { + throw new ArgumentNullException("repositoryAssembly"); + } + + // If the type is not set then use the default type + if (repositoryType == null) + { + repositoryType = this.m_defaultRepositoryType; + } + + lock(this) + { + // Lookup in map + ILoggerRepository rep = this.m_assembly2repositoryMap[repositoryAssembly] as ILoggerRepository; + if (rep == null) + { + // Not found, therefore create + LogLog.Debug(declaringType, "Creating repository for assembly [" + repositoryAssembly + "]"); + + // Must specify defaults + string actualRepositoryName = repositoryName; + Type actualRepositoryType = repositoryType; + + if (readAssemblyAttributes) + { + // Get the repository and type from the assembly attributes + this.GetInfoForAssembly(repositoryAssembly, ref actualRepositoryName, ref actualRepositoryType); + } + + LogLog.Debug(declaringType, "Assembly [" + repositoryAssembly + "] using repository [" + actualRepositoryName + "] and repository type [" + actualRepositoryType + "]"); + + // Lookup the repository in the map (as this may already be defined) + rep = this.m_name2repositoryMap[actualRepositoryName] as ILoggerRepository; + if (rep == null) + { + // Create the repository + rep = this.CreateRepository(actualRepositoryName, actualRepositoryType); + + if (readAssemblyAttributes) + { + try + { + // Look for aliasing attributes + this.LoadAliases(repositoryAssembly, rep); + + // Look for plugins defined on the assembly + this.LoadPlugins(repositoryAssembly, rep); + + // Configure the repository using the assembly attributes + this.ConfigureRepository(repositoryAssembly, rep); + } + catch (Exception ex) + { + LogLog.Error(declaringType, "Failed to configure repository [" + actualRepositoryName + "] from assembly attributes.", ex); + } + } + } + else + { + LogLog.Debug(declaringType, "repository [" + actualRepositoryName + "] already exists, using repository type [" + rep.GetType().FullName + "]"); + + if (readAssemblyAttributes) + { + try + { + // Look for plugins defined on the assembly + this.LoadPlugins(repositoryAssembly, rep); + } + catch (Exception ex) + { + LogLog.Error(declaringType, "Failed to configure repository [" + actualRepositoryName + "] from assembly attributes.", ex); + } + } + } + + this.m_assembly2repositoryMap[repositoryAssembly] = rep; + } + return rep; + } } - /// - /// Gets the repository name and repository type for the specified assembly. - /// - /// The assembly that has a . - /// in/out param to hold the repository name to use for the assembly, caller should set this to the default value before calling. - /// in/out param to hold the type of the repository to create for the assembly, caller should set this to the default value before calling. - /// is . - private void GetInfoForAssembly(Assembly assembly, ref string repositoryName, ref Type repositoryType) - { - if (assembly == null) - { - throw new ArgumentNullException("assembly"); - } - - try - { - LogLog.Debug(declaringType, "Assembly [" + assembly.FullName + "] Loaded From [" + SystemInfo.AssemblyLocationInfo(assembly) + "]"); - } - catch - { - // Ignore exception from debug call - } - - try - { - // Look for the RepositoryAttribute on the assembly -#if NETSTANDARD1_3 - object[] repositoryAttributes = assembly.GetCustomAttributes(typeof(log4net.Config.RepositoryAttribute)).ToArray(); -#else - object[] repositoryAttributes = Attribute.GetCustomAttributes(assembly, typeof(log4net.Config.RepositoryAttribute), false); -#endif - if (repositoryAttributes == null || repositoryAttributes.Length == 0) - { - // This is not a problem, but its nice to know what is going on. - LogLog.Debug(declaringType, "Assembly [" + assembly + "] does not have a RepositoryAttribute specified."); - } - else - { - if (repositoryAttributes.Length > 1) - { - LogLog.Error(declaringType, "Assembly [" + assembly + "] has multiple log4net.Config.RepositoryAttribute assembly attributes. Only using first occurrence."); - } - - log4net.Config.RepositoryAttribute domAttr = repositoryAttributes[0] as log4net.Config.RepositoryAttribute; - - if (domAttr == null) - { - LogLog.Error(declaringType, "Assembly [" + assembly + "] has a RepositoryAttribute but it does not!."); - } - else - { - // If the Name property is set then override the default - if (domAttr.Name != null) - { - repositoryName = domAttr.Name; - } - - // If the RepositoryType property is set then override the default - if (domAttr.RepositoryType != null) - { - // Check that the type is a repository - if (typeof(ILoggerRepository).IsAssignableFrom(domAttr.RepositoryType)) - { - repositoryType = domAttr.RepositoryType; - } - else - { - LogLog.Error(declaringType, "DefaultRepositorySelector: Repository Type [" + domAttr.RepositoryType + "] must implement the ILoggerRepository interface."); - } - } - } - } - } - catch (Exception ex) - { - LogLog.Error(declaringType, "Unhandled exception in GetInfoForAssembly", ex); - } - } - - /// - /// Configures the repository using information from the assembly. - /// - /// The assembly containing - /// attributes which define the configuration for the repository. - /// The repository to configure. - /// - /// is . - /// -or- - /// is . - /// - private void ConfigureRepository(Assembly assembly, ILoggerRepository repository) - { - if (assembly == null) - { - throw new ArgumentNullException("assembly"); - } - - if (repository == null) - { - throw new ArgumentNullException("repository"); - } - - // Look for the Configurator attributes (e.g. XmlConfiguratorAttribute) on the assembly -#if NETSTANDARD1_3 - object[] configAttributes = assembly.GetCustomAttributes(typeof(log4net.Config.ConfiguratorAttribute)).ToArray(); -#else - object[] configAttributes = Attribute.GetCustomAttributes(assembly, typeof(log4net.Config.ConfiguratorAttribute), false); -#endif - if (configAttributes != null && configAttributes.Length > 0) - { - // Sort the ConfiguratorAttributes in priority order - Array.Sort(configAttributes); - - // Delegate to the attribute the job of configuring the repository - foreach (log4net.Config.ConfiguratorAttribute configAttr in configAttributes) - { - if (configAttr != null) - { - try - { - configAttr.Configure(assembly, repository); - } - catch (Exception ex) - { - LogLog.Error(declaringType, "Exception calling [" + configAttr.GetType().FullName + "] .Configure method.", ex); - } - } - } - } - - if (repository.Name == DefaultRepositoryName) - { - // Try to configure the default repository using an AppSettings specified config file - // Do this even if the repository has been configured (or claims to be), this allows overriding - // of the default config files etc, if that is required. - string repositoryConfigFile = SystemInfo.GetAppSetting("log4net.Config"); - if (repositoryConfigFile != null && repositoryConfigFile.Length > 0) - { - string applicationBaseDirectory = null; - try - { - applicationBaseDirectory = SystemInfo.ApplicationBaseDirectory; - } - catch (Exception ex) - { - LogLog.Warn(declaringType, "Exception getting ApplicationBaseDirectory. appSettings log4net.Config path [" + repositoryConfigFile + "] will be treated as an absolute URI", ex); - } - - string repositoryConfigFilePath = repositoryConfigFile; - if (applicationBaseDirectory != null) - { - repositoryConfigFilePath = Path.Combine(applicationBaseDirectory, repositoryConfigFile); - } - - // Determine whether to watch the file or not based on an app setting value: - bool watchRepositoryConfigFile = false; -#if NET_2_0 || MONO_2_0 || MONO_3_5 || MONO_4_0 || NETSTANDARD1_3 - bool.TryParse(SystemInfo.GetAppSetting("log4net.Config.Watch"), out watchRepositoryConfigFile); -#else - { - string watch = SystemInfo.GetAppSetting("log4net.Config.Watch"); - if (watch != null && watch.Length > 0) - { - try - { - watchRepositoryConfigFile = Boolean.Parse(watch); - } - catch (FormatException) - { - // simply not a Boolean - } - } - } -#endif - - if (watchRepositoryConfigFile) - { - // As we are going to watch the config file it is required to resolve it as a - // physical file system path pass that in a FileInfo object to the Configurator - FileInfo repositoryConfigFileInfo = null; - try - { - repositoryConfigFileInfo = new FileInfo(repositoryConfigFilePath); - } - catch (Exception ex) - { - LogLog.Error(declaringType, "DefaultRepositorySelector: Exception while parsing log4net.Config file physical path [" + repositoryConfigFilePath + "]", ex); - } - - try - { - LogLog.Debug(declaringType, "Loading and watching configuration for default repository from AppSettings specified Config path [" + repositoryConfigFilePath + "]"); - - XmlConfigurator.ConfigureAndWatch(repository, repositoryConfigFileInfo); - } - catch (Exception ex) - { - LogLog.Error(declaringType, "DefaultRepositorySelector: Exception calling XmlConfigurator.ConfigureAndWatch method with ConfigFilePath [" + repositoryConfigFilePath + "]", ex); - } - } - else + /// + /// Creates a new repository for the specified repository. + /// + /// The repository to associate with the . + /// The type of repository to create, must implement . + /// If this param is then the default repository type is used. + /// The new repository. + /// + /// + /// The created will be associated with the repository + /// specified such that a call to with the + /// same repository specified will return the same repository instance. + /// + /// + /// is . + /// already exists. + public ILoggerRepository CreateRepository(string repositoryName, Type repositoryType) + { + if (repositoryName == null) + { + throw new ArgumentNullException("repositoryName"); + } + + // If the type is not set then use the default type + if (repositoryType == null) + { + repositoryType = this.m_defaultRepositoryType; + } + + lock(this) + { + ILoggerRepository rep = null; + + // First check that the repository does not exist + rep = this.m_name2repositoryMap[repositoryName] as ILoggerRepository; + if (rep != null) + { + throw new LogException("Repository [" + repositoryName + "] is already defined. Repositories cannot be redefined."); + } + else + { + // Lookup an alias before trying to create the new repository + ILoggerRepository aliasedRepository = this.m_alias2repositoryMap[repositoryName] as ILoggerRepository; + if (aliasedRepository != null) { - // As we are not going to watch the config file it is easiest to just resolve it as a - // URI and pass that to the Configurator - Uri repositoryConfigUri = null; - try + // Found an alias + + // Check repository type + if (aliasedRepository.GetType() == repositoryType) { - repositoryConfigUri = new Uri(repositoryConfigFilePath); + // Repository type is compatible + LogLog.Debug(declaringType, "Aliasing repository [" + repositoryName + "] to existing repository [" + aliasedRepository.Name + "]"); + rep = aliasedRepository; + + // Store in map + this.m_name2repositoryMap[repositoryName] = rep; } - catch (Exception ex) + else { - LogLog.Error(declaringType, "Exception while parsing log4net.Config file path [" + repositoryConfigFile + "]", ex); + // Invalid repository type for alias + LogLog.Error(declaringType, "Failed to alias repository [" + repositoryName + "] to existing repository [" + aliasedRepository.Name + "]. Requested repository type [" + repositoryType.FullName + "] is not compatible with existing type [" + aliasedRepository.GetType().FullName + "]"); + + // We now drop through to create the repository without aliasing } + } + + // If we could not find an alias + if (rep == null) + { + LogLog.Debug(declaringType, "Creating repository [" + repositoryName + "] using type [" + repositoryType + "]"); + + // Call the no arg constructor for the repositoryType + rep = (ILoggerRepository)Activator.CreateInstance(repositoryType); - if (repositoryConfigUri != null) + // Set the name of the repository + rep.Name = repositoryName; + + // Store in map + this.m_name2repositoryMap[repositoryName] = rep; + + // Notify listeners that the repository has been created + this.OnLoggerRepositoryCreatedEvent(rep); + } + } + + return rep; + } + } + + /// + /// Test if a named repository exists + /// + /// the named repository to check + /// true if the repository exists + /// + /// + /// Test if a named repository exists. Use + /// to create a new repository and to retrieve + /// a repository. + /// + /// + public bool ExistsRepository(string repositoryName) + { + lock(this) + { + return this.m_name2repositoryMap.ContainsKey(repositoryName); + } + } + + /// + /// Gets a list of objects + /// + /// an array of all known objects + /// + /// + /// Gets an array of all of the repositories created by this selector. + /// + /// + public ILoggerRepository[] GetAllRepositories() + { + lock(this) + { + ICollection reps = this.m_name2repositoryMap.Values; + ILoggerRepository[] all = new ILoggerRepository[reps.Count]; + reps.CopyTo(all, 0); + return all; + } + } + + /// + /// Aliases a repository to an existing repository. + /// + /// The repository to alias. + /// The repository that the repository is aliased to. + /// + /// + /// The repository specified will be aliased to the repository when created. + /// The repository must not already exist. + /// + /// + /// When the repository is created it must utilize the same repository type as + /// the repository it is aliased to, otherwise the aliasing will fail. + /// + /// + /// + /// is . + /// -or- + /// is . + /// + public void AliasRepository(string repositoryAlias, ILoggerRepository repositoryTarget) + { + if (repositoryAlias == null) + { + throw new ArgumentNullException("repositoryAlias"); + } + if (repositoryTarget == null) + { + throw new ArgumentNullException("repositoryTarget"); + } + + lock(this) + { + // Check if the alias is already set + if (this.m_alias2repositoryMap.Contains(repositoryAlias)) + { + // Check if this is a duplicate of the current alias + if (repositoryTarget != ((ILoggerRepository)this.m_alias2repositoryMap[repositoryAlias])) + { + // Cannot redefine existing alias + throw new InvalidOperationException("Repository [" + repositoryAlias + "] is already aliased to repository [" + ((ILoggerRepository)this.m_alias2repositoryMap[repositoryAlias]).Name + "]. Aliases cannot be redefined."); + } + } + // Check if the alias is already mapped to a repository + else if (this.m_name2repositoryMap.Contains(repositoryAlias)) + { + // Check if this is a duplicate of the current mapping + if ( repositoryTarget != ((ILoggerRepository)this.m_name2repositoryMap[repositoryAlias]) ) + { + // Cannot define alias for already mapped repository + throw new InvalidOperationException("Repository [" + repositoryAlias + "] already exists and cannot be aliased to repository [" + repositoryTarget.Name + "]."); + } + } + else + { + // Set the alias + this.m_alias2repositoryMap[repositoryAlias] = repositoryTarget; + } + } + } + + /// + /// Notifies the registered listeners that the repository has been created. + /// + /// The repository that has been created. + /// + /// + /// Raises the event. + /// + /// + protected virtual void OnLoggerRepositoryCreatedEvent(ILoggerRepository repository) + { + LoggerRepositoryCreationEventHandler handler = this.m_loggerRepositoryCreatedEvent; + if (handler != null) + { + handler(this, new LoggerRepositoryCreationEventArgs(repository)); + } + } + + /// + /// Gets the repository name and repository type for the specified assembly. + /// + /// The assembly that has a . + /// in/out param to hold the repository name to use for the assembly, caller should set this to the default value before calling. + /// in/out param to hold the type of the repository to create for the assembly, caller should set this to the default value before calling. + /// is . + private void GetInfoForAssembly(Assembly assembly, ref string repositoryName, ref Type repositoryType) + { + if (assembly == null) + { + throw new ArgumentNullException("assembly"); + } + + try + { + LogLog.Debug(declaringType, "Assembly [" + assembly.FullName + "] Loaded From [" + SystemInfo.AssemblyLocationInfo(assembly) + "]"); + } + catch + { + // Ignore exception from debug call + } + + try + { + // Look for the RepositoryAttribute on the assembly +#if NETSTANDARD + object[] repositoryAttributes = assembly.GetCustomAttributes(typeof(log4net.Config.RepositoryAttribute)).ToArray(); +#else + object[] repositoryAttributes = Attribute.GetCustomAttributes(assembly, typeof(RepositoryAttribute), false); +#endif + if (repositoryAttributes == null || repositoryAttributes.Length == 0) + { + // This is not a problem, but its nice to know what is going on. + LogLog.Debug(declaringType, "Assembly [" + assembly + "] does not have a RepositoryAttribute specified."); + } + else + { + if (repositoryAttributes.Length > 1) + { + LogLog.Error(declaringType, "Assembly [" + assembly + "] has multiple log4net.Config.RepositoryAttribute assembly attributes. Only using first occurrence."); + } + + RepositoryAttribute domAttr = repositoryAttributes[0] as RepositoryAttribute; + + if (domAttr == null) + { + LogLog.Error(declaringType, "Assembly [" + assembly + "] has a RepositoryAttribute but it does not!."); + } + else + { + // If the Name property is set then override the default + if (domAttr.Name != null) { - LogLog.Debug(declaringType, "Loading configuration for default repository from AppSettings specified Config URI [" + repositoryConfigUri.ToString() + "]"); + repositoryName = domAttr.Name; + } - try + // If the RepositoryType property is set then override the default + if (domAttr.RepositoryType != null) + { + // Check that the type is a repository + if (typeof(ILoggerRepository).IsAssignableFrom(domAttr.RepositoryType)) { - // TODO: Support other types of configurator - XmlConfigurator.Configure(repository, repositoryConfigUri); + repositoryType = domAttr.RepositoryType; } - catch (Exception ex) + else { - LogLog.Error(declaringType, "Exception calling XmlConfigurator.Configure method with ConfigUri [" + repositoryConfigUri + "]", ex); + LogLog.Error(declaringType, "DefaultRepositorySelector: Repository Type [" + domAttr.RepositoryType + "] must implement the ILoggerRepository interface."); } - } - } - } - } - } - - /// - /// Loads the attribute defined plugins on the assembly. - /// - /// The assembly that contains the attributes. - /// The repository to add the plugins to. - /// - /// is . - /// -or- - /// is . - /// - private void LoadPlugins(Assembly assembly, ILoggerRepository repository) - { - if (assembly == null) - { - throw new ArgumentNullException("assembly"); - } - - if (repository == null) - { - throw new ArgumentNullException("repository"); - } - - // Look for the PluginAttribute on the assembly -#if NETSTANDARD1_3 - object[] configAttributes = assembly.GetCustomAttributes(typeof(log4net.Config.PluginAttribute)).ToArray(); -#else - object[] configAttributes = Attribute.GetCustomAttributes(assembly, typeof(log4net.Config.PluginAttribute), false); -#endif - if (configAttributes != null && configAttributes.Length > 0) - { - foreach (log4net.Plugin.IPluginFactory configAttr in configAttributes) - { - try - { - // Create the plugin and add it to the repository - repository.PluginMap.Add(configAttr.CreatePlugin()); - } - catch (Exception ex) - { - LogLog.Error(declaringType, "Failed to create plugin. Attribute [" + configAttr.ToString() + "]", ex); - } - } - } - } - - /// - /// Loads the attribute defined aliases on the assembly. - /// - /// The assembly that contains the attributes. - /// The repository to alias to. - /// - /// is . - /// -or- - /// is . - /// - private void LoadAliases(Assembly assembly, ILoggerRepository repository) - { - if (assembly == null) - { - throw new ArgumentNullException("assembly"); - } - - if (repository == null) - { - throw new ArgumentNullException("repository"); - } - - // Look for the AliasRepositoryAttribute on the assembly -#if NETSTANDARD1_3 - object[] configAttributes = assembly.GetCustomAttributes(typeof(log4net.Config.AliasRepositoryAttribute)).ToArray(); -#else - object[] configAttributes = Attribute.GetCustomAttributes(assembly, typeof(log4net.Config.AliasRepositoryAttribute), false); -#endif - if (configAttributes != null && configAttributes.Length > 0) - { - foreach (log4net.Config.AliasRepositoryAttribute configAttr in configAttributes) - { - try - { - this.AliasRepository(configAttr.Name, repository); - } - catch (Exception ex) - { - LogLog.Error(declaringType, "Failed to alias repository [" + configAttr.Name + "]", ex); - } - } - } + } + } + } + } + catch (Exception ex) + { + LogLog.Error(declaringType, "Unhandled exception in GetInfoForAssembly", ex); + } } - /// - /// The fully qualified type of the DefaultRepositorySelector class. - /// - /// - /// Used by the internal logger to record the Type of the - /// log message. - /// - private static readonly Type declaringType = typeof(DefaultRepositorySelector); - + /// + /// Configures the repository using information from the assembly. + /// + /// The assembly containing + /// attributes which define the configuration for the repository. + /// The repository to configure. + /// + /// is . + /// -or- + /// is . + /// + private void ConfigureRepository(Assembly assembly, ILoggerRepository repository) + { + if (assembly == null) + { + throw new ArgumentNullException("assembly"); + } + if (repository == null) + { + throw new ArgumentNullException("repository"); + } + + // Look for the Configurator attributes (e.g. XmlConfiguratorAttribute) on the assembly +#if NETSTANDARD + object[] configAttributes = assembly.GetCustomAttributes(typeof(log4net.Config.ConfiguratorAttribute)).ToArray(); +#else + object[] configAttributes = Attribute.GetCustomAttributes(assembly, typeof(ConfiguratorAttribute), false); +#endif + if (configAttributes != null && configAttributes.Length > 0) + { + // Sort the ConfiguratorAttributes in priority order + Array.Sort(configAttributes); + + // Delegate to the attribute the job of configuring the repository + foreach(ConfiguratorAttribute configAttr in configAttributes) + { + if (configAttr != null) + { + try + { + configAttr.Configure(assembly, repository); + } + catch (Exception ex) + { + LogLog.Error(declaringType, "Exception calling ["+configAttr.GetType().FullName+"] .Configure method.", ex); + } + } + } + } + + if (repository.Name == DefaultRepositoryName) + { + // Try to configure the default repository using an AppSettings specified config file + // Do this even if the repository has been configured (or claims to be), this allows overriding + // of the default config files etc, if that is required. + + string repositoryConfigFile = SystemInfo.GetAppSetting("log4net.Config"); + if (repositoryConfigFile != null && repositoryConfigFile.Length > 0) + { + string applicationBaseDirectory = null; + try + { + applicationBaseDirectory = SystemInfo.ApplicationBaseDirectory; + } + catch(Exception ex) + { + LogLog.Warn(declaringType, "Exception getting ApplicationBaseDirectory. appSettings log4net.Config path ["+repositoryConfigFile+"] will be treated as an absolute URI", ex); + } + + string repositoryConfigFilePath = repositoryConfigFile; + if (applicationBaseDirectory != null) + { + repositoryConfigFilePath = Path.Combine(applicationBaseDirectory, repositoryConfigFile); + } + + // Determine whether to watch the file or not based on an app setting value: + bool watchRepositoryConfigFile = false; +#if NET_2_0 || MONO_2_0 || MONO_3_5 || MONO_4_0 || NETSTANDARD + Boolean.TryParse(SystemInfo.GetAppSetting("log4net.Config.Watch"), out watchRepositoryConfigFile); +#else + { + string watch = SystemInfo.GetAppSetting("log4net.Config.Watch"); + if (watch != null && watch.Length > 0) + { + try + { + watchRepositoryConfigFile = Boolean.Parse(watch); + } + catch (FormatException) + { + // simply not a Boolean + } + } + } +#endif + + if (watchRepositoryConfigFile) + { + // As we are going to watch the config file it is required to resolve it as a + // physical file system path pass that in a FileInfo object to the Configurator + FileInfo repositoryConfigFileInfo = null; + try + { + repositoryConfigFileInfo = new FileInfo(repositoryConfigFilePath); + } + catch (Exception ex) + { + LogLog.Error(declaringType, "DefaultRepositorySelector: Exception while parsing log4net.Config file physical path [" + repositoryConfigFilePath + "]", ex); + } + try + { + LogLog.Debug(declaringType, "Loading and watching configuration for default repository from AppSettings specified Config path [" + repositoryConfigFilePath + "]"); + + XmlConfigurator.ConfigureAndWatch(repository, repositoryConfigFileInfo); + } + catch (Exception ex) + { + LogLog.Error(declaringType, "DefaultRepositorySelector: Exception calling XmlConfigurator.ConfigureAndWatch method with ConfigFilePath [" + repositoryConfigFilePath + "]", ex); + } + } + else + { + // As we are not going to watch the config file it is easiest to just resolve it as a + // URI and pass that to the Configurator + Uri repositoryConfigUri = null; + try + { + repositoryConfigUri = new Uri(repositoryConfigFilePath); + } + catch(Exception ex) + { + LogLog.Error(declaringType, "Exception while parsing log4net.Config file path [" + repositoryConfigFile + "]", ex); + } + + if (repositoryConfigUri != null) + { + LogLog.Debug(declaringType, "Loading configuration for default repository from AppSettings specified Config URI [" + repositoryConfigUri.ToString() + "]"); + + try + { + // TODO: Support other types of configurator + XmlConfigurator.Configure(repository, repositoryConfigUri); + } + catch (Exception ex) + { + LogLog.Error(declaringType, "Exception calling XmlConfigurator.Configure method with ConfigUri ["+repositoryConfigUri+"]", ex); + } + } + } + } + } + } + + /// + /// Loads the attribute defined plugins on the assembly. + /// + /// The assembly that contains the attributes. + /// The repository to add the plugins to. + /// + /// is . + /// -or- + /// is . + /// + private void LoadPlugins(Assembly assembly, ILoggerRepository repository) + { + if (assembly == null) + { + throw new ArgumentNullException("assembly"); + } + if (repository == null) + { + throw new ArgumentNullException("repository"); + } + + // Look for the PluginAttribute on the assembly +#if NETSTANDARD + object[] configAttributes = assembly.GetCustomAttributes(typeof(log4net.Config.PluginAttribute)).ToArray(); +#else + object[] configAttributes = Attribute.GetCustomAttributes(assembly, typeof(PluginAttribute), false); +#endif + if (configAttributes != null && configAttributes.Length > 0) + { + foreach(Plugin.IPluginFactory configAttr in configAttributes) + { + try + { + // Create the plugin and add it to the repository + repository.PluginMap.Add(configAttr.CreatePlugin()); + } + catch(Exception ex) + { + LogLog.Error(declaringType, "Failed to create plugin. Attribute [" + configAttr.ToString() + "]", ex); + } + } + } + } + + /// + /// Loads the attribute defined aliases on the assembly. + /// + /// The assembly that contains the attributes. + /// The repository to alias to. + /// + /// is . + /// -or- + /// is . + /// + private void LoadAliases(Assembly assembly, ILoggerRepository repository) + { + if (assembly == null) + { + throw new ArgumentNullException("assembly"); + } + if (repository == null) + { + throw new ArgumentNullException("repository"); + } + + // Look for the AliasRepositoryAttribute on the assembly +#if NETSTANDARD + object[] configAttributes = assembly.GetCustomAttributes(typeof(log4net.Config.AliasRepositoryAttribute)).ToArray(); +#else + object[] configAttributes = Attribute.GetCustomAttributes(assembly, typeof(AliasRepositoryAttribute), false); +#endif + if (configAttributes != null && configAttributes.Length > 0) + { + foreach(AliasRepositoryAttribute configAttr in configAttributes) + { + try + { + this.AliasRepository(configAttr.Name, repository); + } + catch(Exception ex) + { + LogLog.Error(declaringType, "Failed to alias repository [" + configAttr.Name + "]", ex); + } + } + } + } + + /// + /// The fully qualified type of the DefaultRepositorySelector class. + /// + /// + /// Used by the internal logger to record the Type of the + /// log message. + /// + private static readonly Type declaringType = typeof(DefaultRepositorySelector); + private const string DefaultRepositoryName = "log4net-default-repository"; - private readonly Hashtable m_name2repositoryMap = new Hashtable(); - private readonly Hashtable m_assembly2repositoryMap = new Hashtable(); - private readonly Hashtable m_alias2repositoryMap = new Hashtable(); - private readonly Type m_defaultRepositoryType; - + + private readonly Hashtable m_name2repositoryMap = new Hashtable(); + private readonly Hashtable m_assembly2repositoryMap = new Hashtable(); + private readonly Hashtable m_alias2repositoryMap = new Hashtable(); + private readonly Type m_defaultRepositoryType; + private event LoggerRepositoryCreationEventHandler m_loggerRepositoryCreatedEvent; - } -} - -#endif // !NETCF + } +} + +#endif // !NETCF diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Core/ErrorCode.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Core/ErrorCode.cs index 4a6c60333c7..4c810851df5 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Core/ErrorCode.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Core/ErrorCode.cs @@ -1,71 +1,71 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.Core -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; +using System; - /// - /// Defined error codes that can be passed to the method. - /// - /// - /// - /// Values passed to the method. - /// - /// - /// Nicko Cadell. - public enum ErrorCode : int - { - /// - /// A general error - /// - GenericFailure = 0, - - /// - /// Error while writing output - /// - WriteFailure, - - /// - /// Failed to flush file - /// - FlushFailure, - - /// - /// Failed to close file - /// - CloseFailure, - - /// - /// Unable to open output file - /// - FileOpenFailure, - - /// - /// No layout specified - /// - MissingLayout, - - /// - /// Failed to parse address - /// - AddressParseFailure, - } -} +namespace log4net.Core +{ + /// + /// Defined error codes that can be passed to the method. + /// + /// + /// + /// Values passed to the method. + /// + /// + /// Nicko Cadell + public enum ErrorCode : int + { + /// + /// A general error + /// + GenericFailure = 0, + + /// + /// Error while writing output + /// + WriteFailure, + + /// + /// Failed to flush file + /// + FlushFailure, + + /// + /// Failed to close file + /// + CloseFailure, + + /// + /// Unable to open output file + /// + FileOpenFailure, + + /// + /// No layout specified + /// + MissingLayout, + + /// + /// Failed to parse address + /// + AddressParseFailure + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Core/ExceptionEvaluator.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Core/ExceptionEvaluator.cs index 3814a974643..f4700c049cf 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Core/ExceptionEvaluator.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Core/ExceptionEvaluator.cs @@ -1,133 +1,127 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -#if NETSTANDARD1_3 -using System.Reflection; -#endif - -namespace log4net.Core -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; +using System; - /// - /// An evaluator that triggers on an Exception type. - /// - /// - /// - /// This evaluator will trigger if the type of the Exception - /// passed to - /// is equal to a Type in . ///. - /// - /// - /// Drew Schaeffer. - public class ExceptionEvaluator : ITriggeringEventEvaluator - { - /// - /// The type that causes the trigger to fire. - /// - private Type m_type; - - /// - /// Causes subclasses of to cause the trigger to fire. - /// +namespace log4net.Core +{ + /// + /// An evaluator that triggers on an Exception type + /// + /// + /// + /// This evaluator will trigger if the type of the Exception + /// passed to + /// is equal to a Type in . /// + /// + /// + /// Drew Schaeffer + public class ExceptionEvaluator : ITriggeringEventEvaluator + { + /// + /// The type that causes the trigger to fire. + /// + private Type m_type; + + /// + /// Causes subclasses of to cause the trigger to fire. + /// private bool m_triggerOnSubclass; /// - /// Initializes a new instance of the class. - /// Default ctor to allow dynamic creation through a configurator. - /// - public ExceptionEvaluator() - { - // empty + /// Default ctor to allow dynamic creation through a configurator. + /// + public ExceptionEvaluator() + { + // empty + } + + /// + /// Constructs an evaluator and initializes to trigger on + /// + /// the type that triggers this evaluator. + /// If true, this evaluator will trigger on subclasses of . + public ExceptionEvaluator(Type exType, bool triggerOnSubClass) + { + if (exType == null) + { + throw new ArgumentNullException("exType"); + } + + this.m_type = exType; + this.m_triggerOnSubclass = triggerOnSubClass; + } + + /// + /// The type that triggers this evaluator. + /// + public Type ExceptionType + { + get { return this.m_type; } + set { this.m_type = value; } } /// - /// Initializes a new instance of the class. - /// Constructs an evaluator and initializes to trigger on . - /// - /// the type that triggers this evaluator. - /// If true, this evaluator will trigger on subclasses of . - public ExceptionEvaluator(Type exType, bool triggerOnSubClass) - { - if (exType == null) - { - throw new ArgumentNullException("exType"); - } - - this.m_type = exType; - this.m_triggerOnSubclass = triggerOnSubClass; - } - - /// - /// Gets or sets the type that triggers this evaluator. - /// - public Type ExceptionType - { - get { return this.m_type; } - set { this.m_type = value; } - } - - /// - /// Gets or sets a value indicating whether if true, this evaluator will trigger on subclasses of . - /// - public bool TriggerOnSubclass - { - get { return this.m_triggerOnSubclass; } - set { this.m_triggerOnSubclass = value; } + /// If true, this evaluator will trigger on subclasses of . + /// + public bool TriggerOnSubclass + { + get { return this.m_triggerOnSubclass; } + set { this.m_triggerOnSubclass = value; } } - /// - /// Is this the triggering event?. - /// - /// The event to check. - /// This method returns true, if the logging event Exception - /// Type is . - /// Otherwise it returns false. - /// - /// - /// This evaluator will trigger if the Exception Type of the event - /// passed to - /// is . - /// - /// - public bool IsTriggeringEvent(LoggingEvent loggingEvent) - { - if (loggingEvent == null) - { - throw new ArgumentNullException("loggingEvent"); - } - - if (this.m_triggerOnSubclass && loggingEvent.ExceptionObject != null) - { - // check if loggingEvent.ExceptionObject is of type ExceptionType or subclass of ExceptionType - Type exceptionObjectType = loggingEvent.ExceptionObject.GetType(); - return exceptionObjectType == this.m_type || exceptionObjectType.IsSubclassOf(this.m_type); - } - else if (!this.m_triggerOnSubclass && loggingEvent.ExceptionObject != null) - { // check if loggingEvent.ExceptionObject is of type ExceptionType - return loggingEvent.ExceptionObject.GetType() == this.m_type; - } - else - { // loggingEvent.ExceptionObject is null - return false; - } + /// + /// Is this the triggering event? + /// + /// The event to check + /// This method returns true, if the logging event Exception + /// Type is . + /// Otherwise it returns false + /// + /// + /// This evaluator will trigger if the Exception Type of the event + /// passed to + /// is . + /// + /// + public bool IsTriggeringEvent(LoggingEvent loggingEvent) + { + if (loggingEvent == null) + { + throw new ArgumentNullException("loggingEvent"); + } + + if (this.m_triggerOnSubclass && loggingEvent.ExceptionObject != null) + { + // check if loggingEvent.ExceptionObject is of type ExceptionType or subclass of ExceptionType + Type exceptionObjectType = loggingEvent.ExceptionObject.GetType(); + return exceptionObjectType == this.m_type || this.m_type.IsAssignableFrom(exceptionObjectType); + } + else if (!this.m_triggerOnSubclass && loggingEvent.ExceptionObject != null) + { // check if loggingEvent.ExceptionObject is of type ExceptionType + return loggingEvent.ExceptionObject.GetType() == this.m_type; + } + else + { // loggingEvent.ExceptionObject is null + return false; + } } - } -} + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Core/IAppenderAttachable.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Core/IAppenderAttachable.cs index 9f0017cd619..ce3d81c9b03 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Core/IAppenderAttachable.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Core/IAppenderAttachable.cs @@ -1,122 +1,122 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.Core -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; +using System; - using log4net.Appender; +using log4net.Appender; - /// - /// Interface for attaching appenders to objects. - /// - /// - /// - /// Interface for attaching, removing and retrieving appenders. - /// - /// - /// Nicko Cadell. - /// Gert Driesen. - public interface IAppenderAttachable - { - /// - /// Attaches an appender. - /// - /// The appender to add. - /// - /// - /// Add the specified appender. The implementation may - /// choose to allow or deny duplicate appenders. - /// - /// - void AddAppender(IAppender appender); - - /// - /// Gets all attached appenders. - /// - /// - /// A collection of attached appenders. - /// - /// - /// - /// Gets a collection of attached appenders. - /// If there are no attached appenders the - /// implementation should return an empty - /// collection rather than null. - /// - /// - AppenderCollection Appenders { get; } - - /// - /// Gets an attached appender with the specified name. - /// - /// The name of the appender to get. - /// - /// The appender with the name specified, or null if no appender with the - /// specified name is found. - /// - /// - /// - /// Returns an attached appender with the specified. - /// If no appender with the specified name is found null will be - /// returned. - /// - /// - IAppender GetAppender(string name); - - /// - /// Removes all attached appenders. - /// - /// - /// - /// Removes and closes all attached appenders. - /// - /// - void RemoveAllAppenders(); - - /// - /// Removes the specified appender from the list of attached appenders. - /// - /// The appender to remove. - /// The appender removed from the list. - /// - /// - /// The appender removed is not closed. - /// If you are discarding the appender you must call - /// on the appender removed. - /// - /// - IAppender RemoveAppender(IAppender appender); - - /// - /// Removes the appender with the specified name from the list of appenders. - /// - /// The name of the appender to remove. - /// The appender removed from the list. - /// - /// - /// The appender removed is not closed. - /// If you are discarding the appender you must call - /// on the appender removed. - /// - /// - IAppender RemoveAppender(string name); - } -} +namespace log4net.Core +{ + /// + /// Interface for attaching appenders to objects. + /// + /// + /// + /// Interface for attaching, removing and retrieving appenders. + /// + /// + /// Nicko Cadell + /// Gert Driesen + public interface IAppenderAttachable + { + /// + /// Attaches an appender. + /// + /// The appender to add. + /// + /// + /// Add the specified appender. The implementation may + /// choose to allow or deny duplicate appenders. + /// + /// + void AddAppender(IAppender appender); + + /// + /// Gets all attached appenders. + /// + /// + /// A collection of attached appenders. + /// + /// + /// + /// Gets a collection of attached appenders. + /// If there are no attached appenders the + /// implementation should return an empty + /// collection rather than null. + /// + /// + AppenderCollection Appenders {get;} + + /// + /// Gets an attached appender with the specified name. + /// + /// The name of the appender to get. + /// + /// The appender with the name specified, or null if no appender with the + /// specified name is found. + /// + /// + /// + /// Returns an attached appender with the specified. + /// If no appender with the specified name is found null will be + /// returned. + /// + /// + IAppender GetAppender(string name); + + /// + /// Removes all attached appenders. + /// + /// + /// + /// Removes and closes all attached appenders + /// + /// + void RemoveAllAppenders(); + + /// + /// Removes the specified appender from the list of attached appenders. + /// + /// The appender to remove. + /// The appender removed from the list + /// + /// + /// The appender removed is not closed. + /// If you are discarding the appender you must call + /// on the appender removed. + /// + /// + IAppender RemoveAppender(IAppender appender); + + /// + /// Removes the appender with the specified name from the list of appenders. + /// + /// The name of the appender to remove. + /// The appender removed from the list + /// + /// + /// The appender removed is not closed. + /// If you are discarding the appender you must call + /// on the appender removed. + /// + /// + IAppender RemoveAppender(string name); + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Core/IErrorHandler.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Core/IErrorHandler.cs index d6974241856..0572d943c11 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Core/IErrorHandler.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Core/IErrorHandler.cs @@ -1,76 +1,76 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.Core -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; +using System; - /// - /// Appenders may delegate their error handling to an . - /// - /// - /// - /// Error handling is a particularly tedious to get right because by - /// definition errors are hard to predict and to reproduce. - /// - /// - /// Nicko Cadell. - /// Gert Driesen. - public interface IErrorHandler - { - /// - /// Handles the error and information about the error condition is passed as - /// a parameter. - /// - /// The message associated with the error. - /// The that was thrown when the error occurred. - /// The error code associated with the error. - /// - /// - /// Handles the error and information about the error condition is passed as - /// a parameter. - /// - /// - void Error(string message, Exception e, ErrorCode errorCode); - - /// - /// Prints the error message passed as a parameter. - /// - /// The message associated with the error. - /// The that was thrown when the error occurred. - /// - /// - /// See . - /// - /// - void Error(string message, Exception e); - - /// - /// Prints the error message passed as a parameter. - /// - /// The message associated with the error. - /// - /// - /// See . - /// - /// - void Error(string message); - } -} +namespace log4net.Core +{ + /// + /// Appenders may delegate their error handling to an . + /// + /// + /// + /// Error handling is a particularly tedious to get right because by + /// definition errors are hard to predict and to reproduce. + /// + /// + /// Nicko Cadell + /// Gert Driesen + public interface IErrorHandler + { + /// + /// Handles the error and information about the error condition is passed as + /// a parameter. + /// + /// The message associated with the error. + /// The that was thrown when the error occurred. + /// The error code associated with the error. + /// + /// + /// Handles the error and information about the error condition is passed as + /// a parameter. + /// + /// + void Error(string message, Exception e, ErrorCode errorCode); + + /// + /// Prints the error message passed as a parameter. + /// + /// The message associated with the error. + /// The that was thrown when the error occurred. + /// + /// + /// See . + /// + /// + void Error(string message, Exception e); + + /// + /// Prints the error message passed as a parameter. + /// + /// The message associated with the error. + /// + /// + /// See . + /// + /// + void Error(string message); + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Core/IFixingRequired.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Core/IFixingRequired.cs index 401115c4c53..c6f443aba4b 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Core/IFixingRequired.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Core/IFixingRequired.cs @@ -1,59 +1,59 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.Core -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; +using System; - /// - /// Interface for objects that require fixing. - /// - /// - /// - /// Interface that indicates that the object requires fixing before it - /// can be taken outside the context of the appender's - /// method. - /// - /// - /// When objects that implement this interface are stored - /// in the context properties maps - /// and - /// are fixed - /// (see ) the - /// method will be called. - /// - /// - /// Nicko Cadell. - public interface IFixingRequired - { - /// - /// Get a portable version of this object. - /// - /// the portable instance of this object. - /// - /// - /// Get a portable instance object that represents the current - /// state of this object. The portable object can be stored - /// and logged from any thread with identical results. - /// - /// - object GetFixedObject(); - } -} +namespace log4net.Core +{ + /// + /// Interface for objects that require fixing. + /// + /// + /// + /// Interface that indicates that the object requires fixing before it + /// can be taken outside the context of the appender's + /// method. + /// + /// + /// When objects that implement this interface are stored + /// in the context properties maps + /// and + /// are fixed + /// (see ) the + /// method will be called. + /// + /// + /// Nicko Cadell + public interface IFixingRequired + { + /// + /// Get a portable version of this object + /// + /// the portable instance of this object + /// + /// + /// Get a portable instance object that represents the current + /// state of this object. The portable object can be stored + /// and logged from any thread with identical results. + /// + /// + object GetFixedObject(); + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Core/ILogger.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Core/ILogger.cs index 4d0ebb0179a..dd38bcf41d0 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Core/ILogger.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Core/ILogger.cs @@ -1,116 +1,116 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.Core -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; +using System; - using log4net.Core; - using log4net.Repository; +using log4net.Core; +using log4net.Repository; - /// - /// Interface that all loggers implement. - /// - /// - /// - /// This interface supports logging events and testing if a level - /// is enabled for logging. - /// - /// - /// These methods will not throw exceptions. Note to implementor, ensure - /// that the implementation of these methods cannot allow an exception - /// to be thrown to the caller. - /// - /// - /// Nicko Cadell. - /// Gert Driesen. - public interface ILogger - { - /// - /// Gets the name of the logger. - /// - /// - /// The name of the logger. - /// - /// - /// - /// The name of this logger. - /// - /// - string Name { get; } - - /// - /// This generic form is intended to be used by wrappers. - /// - /// The declaring type of the method that is - /// the stack boundary into the logging system for this call. - /// The level of the message to be logged. - /// The message object to log. - /// the exception to log, including its stack trace. Pass null to not log an exception. - /// - /// - /// Generates a logging event for the specified using - /// the and . - /// - /// - void Log(Type callerStackBoundaryDeclaringType, Level level, object message, Exception exception); - - /// - /// This is the most generic printing method that is intended to be used - /// by wrappers. - /// - /// The event being logged. - /// - /// - /// Logs the specified logging event through this logger. - /// - /// - void Log(LoggingEvent logEvent); - - /// - /// Checks if this logger is enabled for a given passed as parameter. - /// - /// The level to check. - /// - /// true if this logger is enabled for level, otherwise false. - /// - /// - /// - /// Test if this logger is going to log events of the specified . - /// - /// - bool IsEnabledFor(Level level); - - /// - /// Gets the where this - /// Logger instance is attached to. - /// - /// - /// The that this logger belongs to. - /// - /// - /// - /// Gets the where this - /// Logger instance is attached to. - /// - /// - ILoggerRepository Repository { get; } - } -} +namespace log4net.Core +{ + /// + /// Interface that all loggers implement + /// + /// + /// + /// This interface supports logging events and testing if a level + /// is enabled for logging. + /// + /// + /// These methods will not throw exceptions. Note to implementor, ensure + /// that the implementation of these methods cannot allow an exception + /// to be thrown to the caller. + /// + /// + /// Nicko Cadell + /// Gert Driesen + public interface ILogger + { + /// + /// Gets the name of the logger. + /// + /// + /// The name of the logger. + /// + /// + /// + /// The name of this logger + /// + /// + string Name { get; } + + /// + /// This generic form is intended to be used by wrappers. + /// + /// The declaring type of the method that is + /// the stack boundary into the logging system for this call. + /// The level of the message to be logged. + /// The message object to log. + /// the exception to log, including its stack trace. Pass null to not log an exception. + /// + /// + /// Generates a logging event for the specified using + /// the and . + /// + /// + void Log(Type callerStackBoundaryDeclaringType, Level level, object message, Exception exception); + + /// + /// This is the most generic printing method that is intended to be used + /// by wrappers. + /// + /// The event being logged. + /// + /// + /// Logs the specified logging event through this logger. + /// + /// + void Log(LoggingEvent logEvent); + + /// + /// Checks if this logger is enabled for a given passed as parameter. + /// + /// The level to check. + /// + /// true if this logger is enabled for level, otherwise false. + /// + /// + /// + /// Test if this logger is going to log events of the specified . + /// + /// + bool IsEnabledFor(Level level); + + /// + /// Gets the where this + /// Logger instance is attached to. + /// + /// + /// The that this logger belongs to. + /// + /// + /// + /// Gets the where this + /// Logger instance is attached to. + /// + /// + ILoggerRepository Repository { get; } + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Core/ILoggerWrapper.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Core/ILoggerWrapper.cs index ee6e7a0ec6e..36f17b82339 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Core/ILoggerWrapper.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Core/ILoggerWrapper.cs @@ -1,60 +1,60 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.Core -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; +using System; - using log4net; - using log4net.Core; - using log4net.Repository; +using log4net; +using log4net.Core; +using log4net.Repository; - /// - /// Base interface for all wrappers. - /// - /// - /// - /// Base interface for all wrappers. - /// - /// - /// All wrappers must implement this interface. - /// - /// - /// Nicko Cadell. - public interface ILoggerWrapper - { - /// - /// Gets get the implementation behind this wrapper object. - /// - /// - /// The object that in implementing this object. - /// - /// - /// - /// The object that in implementing this - /// object. The Logger object may not - /// be the same object as this object because of logger decorators. - /// This gets the actual underlying objects that is used to process - /// the log events. - /// - /// - ILogger Logger { get; } - } -} +namespace log4net.Core +{ + /// + /// Base interface for all wrappers + /// + /// + /// + /// Base interface for all wrappers. + /// + /// + /// All wrappers must implement this interface. + /// + /// + /// Nicko Cadell + public interface ILoggerWrapper + { + /// + /// Get the implementation behind this wrapper object. + /// + /// + /// The object that in implementing this object. + /// + /// + /// + /// The object that in implementing this + /// object. The Logger object may not + /// be the same object as this object because of logger decorators. + /// This gets the actual underlying objects that is used to process + /// the log events. + /// + /// + ILogger Logger { get; } + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Core/IOptionHandler.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Core/IOptionHandler.cs index 2f3b7718a09..d16d62261c4 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Core/IOptionHandler.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Core/IOptionHandler.cs @@ -1,59 +1,59 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.Core -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; +using System; - /// - /// Interface used to delay activate a configured object. - /// - /// - /// - /// This allows an object to defer activation of its options until all - /// options have been set. This is required for components which have - /// related options that remain ambiguous until all are set. - /// - /// - /// If a component implements this interface then the method - /// must be called by the container after its all the configured properties have been set - /// and before the component can be used. - /// - /// - /// Nicko Cadell. - public interface IOptionHandler - { - /// - /// Activate the options that were previously set with calls to properties. - /// - /// - /// - /// This allows an object to defer activation of its options until all - /// options have been set. This is required for components which have - /// related options that remain ambiguous until all are set. - /// - /// - /// If a component implements this interface then this method must be called - /// after its properties have been set before the component can be used. - /// - /// - void ActivateOptions(); - } -} +namespace log4net.Core +{ + /// + /// Interface used to delay activate a configured object. + /// + /// + /// + /// This allows an object to defer activation of its options until all + /// options have been set. This is required for components which have + /// related options that remain ambiguous until all are set. + /// + /// + /// If a component implements this interface then the method + /// must be called by the container after its all the configured properties have been set + /// and before the component can be used. + /// + /// + /// Nicko Cadell + public interface IOptionHandler + { + /// + /// Activate the options that were previously set with calls to properties. + /// + /// + /// + /// This allows an object to defer activation of its options until all + /// options have been set. This is required for components which have + /// related options that remain ambiguous until all are set. + /// + /// + /// If a component implements this interface then this method must be called + /// after its properties have been set before the component can be used. + /// + /// + void ActivateOptions(); + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Core/IRepositorySelector.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Core/IRepositorySelector.cs index 037583e6814..95130daa328 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Core/IRepositorySelector.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Core/IRepositorySelector.cs @@ -1,211 +1,210 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.Core -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; - using System.Reflection; +using System; +using System.Reflection; + +using log4net.Repository; - using log4net.Repository; +namespace log4net.Core +{ + /// + /// Delegate used to handle logger repository creation event notifications + /// + /// The which created the repository. + /// The event args + /// that holds the instance that has been created. + /// + /// + /// Delegate used to handle logger repository creation event notifications. + /// + /// + public delegate void LoggerRepositoryCreationEventHandler(object sender, LoggerRepositoryCreationEventArgs e); - /// - /// Delegate used to handle logger repository creation event notifications. - /// - /// The which created the repository. - /// The event args - /// that holds the instance that has been created. - /// - /// - /// Delegate used to handle logger repository creation event notifications. - /// - /// - public delegate void LoggerRepositoryCreationEventHandler(object sender, LoggerRepositoryCreationEventArgs e); - - /// - /// Provides data for the event. - /// - /// - /// - /// A - /// event is raised every time a is created. - /// - /// - public class LoggerRepositoryCreationEventArgs : EventArgs - { - /// - /// The created. - /// + /// + /// Provides data for the event. + /// + /// + /// + /// A + /// event is raised every time a is created. + /// + /// + public class LoggerRepositoryCreationEventArgs : EventArgs + { + /// + /// The created + /// private ILoggerRepository m_repository; /// - /// Initializes a new instance of the class. - /// Construct instance using specified. - /// - /// the that has been created. - /// - /// - /// Construct instance using specified. - /// - /// - public LoggerRepositoryCreationEventArgs(ILoggerRepository repository) - { - this.m_repository = repository; - } - - /// - /// Gets the that has been created. - /// - /// - /// The that has been created. - /// - /// - /// - /// The that has been created. - /// - /// - public ILoggerRepository LoggerRepository - { - get { return this.m_repository; } - } + /// Construct instance using specified + /// + /// the that has been created + /// + /// + /// Construct instance using specified + /// + /// + public LoggerRepositoryCreationEventArgs(ILoggerRepository repository) + { + this.m_repository = repository; + } + + /// + /// The that has been created + /// + /// + /// The that has been created + /// + /// + /// + /// The that has been created + /// + /// + public ILoggerRepository LoggerRepository + { + get { return this.m_repository; } + } } - /// - /// Interface used by the to select the . - /// - /// - /// - /// The uses a - /// to specify the policy for selecting the correct - /// to return to the caller. - /// - /// - /// Nicko Cadell. - /// Gert Driesen. - public interface IRepositorySelector - { - /// - /// Gets the for the specified assembly. - /// - /// The assembly to use to lookup to the . - /// The for the assembly. - /// - /// - /// Gets the for the specified assembly. - /// - /// - /// How the association between and - /// is made is not defined. The implementation may choose any method for - /// this association. The results of this method must be repeatable, i.e. - /// when called again with the same arguments the result must be the - /// save value. - /// - /// - ILoggerRepository GetRepository(Assembly assembly); - - /// - /// Gets the named . - /// - /// The name to use to lookup to the . - /// The named . - /// - /// Lookup a named . This is the repository created by - /// calling . - /// - ILoggerRepository GetRepository(string repositoryName); - - /// - /// Creates a new repository for the assembly specified. - /// - /// The assembly to use to create the domain to associate with the . - /// The type of repository to create, must implement . - /// The repository created. - /// - /// - /// The created will be associated with the domain - /// specified such that a call to with the - /// same assembly specified will return the same repository instance. - /// - /// - /// How the association between and - /// is made is not defined. The implementation may choose any method for - /// this association. - /// - /// - ILoggerRepository CreateRepository(Assembly assembly, Type repositoryType); - - /// - /// Creates a new repository with the name specified. - /// - /// The name to associate with the . - /// The type of repository to create, must implement . - /// The repository created. - /// - /// - /// The created will be associated with the name - /// specified such that a call to with the - /// same name will return the same repository instance. - /// - /// - ILoggerRepository CreateRepository(string repositoryName, Type repositoryType); - - /// - /// Test if a named repository exists. - /// - /// the named repository to check. - /// true if the repository exists. - /// - /// - /// Test if a named repository exists. Use - /// to create a new repository and to retrieve - /// a repository. - /// - /// - bool ExistsRepository(string repositoryName); - - /// - /// Gets an array of all currently defined repositories. - /// - /// - /// An array of the instances created by - /// this . - /// - /// - /// Gets an array of all of the repositories created by this selector. - /// - /// - ILoggerRepository[] GetAllRepositories(); - - /// - /// Event to notify that a logger repository has been created. - /// - /// - /// Event to notify that a logger repository has been created. - /// - /// - /// - /// Event raised when a new repository is created. - /// The event source will be this selector. The event args will - /// be a which - /// holds the newly created . - /// - /// - event LoggerRepositoryCreationEventHandler LoggerRepositoryCreatedEvent; - } -} + /// + /// Interface used by the to select the . + /// + /// + /// + /// The uses a + /// to specify the policy for selecting the correct + /// to return to the caller. + /// + /// + /// Nicko Cadell + /// Gert Driesen + public interface IRepositorySelector + { + /// + /// Gets the for the specified assembly. + /// + /// The assembly to use to lookup to the + /// The for the assembly. + /// + /// + /// Gets the for the specified assembly. + /// + /// + /// How the association between and + /// is made is not defined. The implementation may choose any method for + /// this association. The results of this method must be repeatable, i.e. + /// when called again with the same arguments the result must be the + /// save value. + /// + /// + ILoggerRepository GetRepository(Assembly assembly); + + /// + /// Gets the named . + /// + /// The name to use to lookup to the . + /// The named + /// + /// Lookup a named . This is the repository created by + /// calling . + /// + ILoggerRepository GetRepository(string repositoryName); + + /// + /// Creates a new repository for the assembly specified. + /// + /// The assembly to use to create the domain to associate with the . + /// The type of repository to create, must implement . + /// The repository created. + /// + /// + /// The created will be associated with the domain + /// specified such that a call to with the + /// same assembly specified will return the same repository instance. + /// + /// + /// How the association between and + /// is made is not defined. The implementation may choose any method for + /// this association. + /// + /// + ILoggerRepository CreateRepository(Assembly assembly, Type repositoryType); + + /// + /// Creates a new repository with the name specified. + /// + /// The name to associate with the . + /// The type of repository to create, must implement . + /// The repository created. + /// + /// + /// The created will be associated with the name + /// specified such that a call to with the + /// same name will return the same repository instance. + /// + /// + ILoggerRepository CreateRepository(string repositoryName, Type repositoryType); + + /// + /// Test if a named repository exists + /// + /// the named repository to check + /// true if the repository exists + /// + /// + /// Test if a named repository exists. Use + /// to create a new repository and to retrieve + /// a repository. + /// + /// + bool ExistsRepository(string repositoryName); + + /// + /// Gets an array of all currently defined repositories. + /// + /// + /// An array of the instances created by + /// this . + /// + /// + /// Gets an array of all of the repositories created by this selector. + /// + /// + ILoggerRepository[] GetAllRepositories(); + + /// + /// Event to notify that a logger repository has been created. + /// + /// + /// Event to notify that a logger repository has been created. + /// + /// + /// + /// Event raised when a new repository is created. + /// The event source will be this selector. The event args will + /// be a which + /// holds the newly created . + /// + /// + event LoggerRepositoryCreationEventHandler LoggerRepositoryCreatedEvent; + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Core/ITriggeringEventEvaluator.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Core/ITriggeringEventEvaluator.cs index 80a1c7c9d15..aa1a222be36 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Core/ITriggeringEventEvaluator.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Core/ITriggeringEventEvaluator.cs @@ -1,52 +1,52 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.Core -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; +using System; - /// - /// Test if an triggers an action. - /// - /// - /// - /// Implementations of this interface allow certain appenders to decide - /// when to perform an appender specific action. - /// - /// - /// The action or behavior triggered is defined by the implementation. - /// - /// - /// Nicko Cadell. - public interface ITriggeringEventEvaluator - { - /// - /// Test if this event triggers the action. - /// - /// The event to check. - /// true if this event triggers the action, otherwise false. - /// - /// - /// Return true if this event triggers the action. - /// - /// - bool IsTriggeringEvent(LoggingEvent loggingEvent); - } -} +namespace log4net.Core +{ + /// + /// Test if an triggers an action + /// + /// + /// + /// Implementations of this interface allow certain appenders to decide + /// when to perform an appender specific action. + /// + /// + /// The action or behavior triggered is defined by the implementation. + /// + /// + /// Nicko Cadell + public interface ITriggeringEventEvaluator + { + /// + /// Test if this event triggers the action + /// + /// The event to check + /// true if this event triggers the action, otherwise false + /// + /// + /// Return true if this event triggers the action + /// + /// + bool IsTriggeringEvent(LoggingEvent loggingEvent); + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Core/Level.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Core/Level.cs index f9c87deb74f..e3d6cc4f0a9 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Core/Level.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Core/Level.cs @@ -1,590 +1,584 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.Core -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; - using System.Collections; - - /// - /// Defines the default set of levels recognized by the system. - /// - /// - /// - /// Each has an associated . - /// - /// - /// Levels have a numeric that defines the relative - /// ordering between levels. Two Levels with the same - /// are deemed to be equivalent. - /// - /// - /// The levels that are recognized by log4net are set for each - /// and each repository can have different levels defined. The levels are stored - /// in the on the repository. Levels are - /// looked up by name from the . - /// - /// - /// When logging at level INFO the actual level used is not but - /// the value of LoggerRepository.LevelMap["INFO"]. The default value for this is - /// , but this can be changed by reconfiguring the level map. - /// - /// - /// Each level has a in addition to its . The - /// is the string that is written into the output log. By default - /// the display name is the same as the level name, but this can be used to alias levels - /// or to localize the log output. - /// - /// - /// Some of the predefined levels recognized by the system are: - /// - /// - /// - /// . - /// - /// - /// . - /// - /// - /// . - /// - /// - /// . - /// - /// - /// . - /// - /// - /// . - /// - /// - /// . - /// - /// - /// - /// Nicko Cadell. - /// Gert Driesen. -#if !NETCF - [Serializable] -#endif - public sealed class Level : IComparable +using System; +using System.Collections; + +namespace log4net.Core +{ + /// + /// Defines the default set of levels recognized by the system. + /// + /// + /// + /// Each has an associated . + /// + /// + /// Levels have a numeric that defines the relative + /// ordering between levels. Two Levels with the same + /// are deemed to be equivalent. + /// + /// + /// The levels that are recognized by log4net are set for each + /// and each repository can have different levels defined. The levels are stored + /// in the on the repository. Levels are + /// looked up by name from the . + /// + /// + /// When logging at level INFO the actual level used is not but + /// the value of LoggerRepository.LevelMap["INFO"]. The default value for this is + /// , but this can be changed by reconfiguring the level map. + /// + /// + /// Each level has a in addition to its . The + /// is the string that is written into the output log. By default + /// the display name is the same as the level name, but this can be used to alias levels + /// or to localize the log output. + /// + /// + /// Some of the predefined levels recognized by the system are: + /// + /// + /// + /// . + /// + /// + /// . + /// + /// + /// . + /// + /// + /// . + /// + /// + /// . + /// + /// + /// . + /// + /// + /// . + /// + /// + /// + /// Nicko Cadell + /// Gert Driesen +#if !NETCF + [Serializable] +#endif + public sealed class Level : IComparable { /// - /// Initializes a new instance of the class. - /// Constructor. - /// - /// Integer value for this level, higher values represent more severe levels. - /// The string name of this level. - /// The display name for this level. This may be localized or otherwise different from the name. - /// - /// - /// Initializes a new instance of the class with - /// the specified level name and value. - /// - /// - public Level(int level, string levelName, string displayName) - { - if (levelName == null) - { - throw new ArgumentNullException("levelName"); - } - - if (displayName == null) - { - throw new ArgumentNullException("displayName"); - } - - this.m_levelValue = level; -#if NETSTANDARD1_3 - m_levelName = levelName; -#else - this.m_levelName = string.Intern(levelName); -#endif - this.m_levelDisplayName = displayName; + /// Constructor + /// + /// Integer value for this level, higher values represent more severe levels. + /// The string name of this level. + /// The display name for this level. This may be localized or otherwise different from the name + /// + /// + /// Initializes a new instance of the class with + /// the specified level name and value. + /// + /// + public Level(int level, string levelName, string displayName) + { + if (levelName == null) + { + throw new ArgumentNullException("levelName"); + } + if (displayName == null) + { + throw new ArgumentNullException("displayName"); + } + + this.m_levelValue = level; +#if NETSTANDARD1_3 + m_levelName = levelName; +#else + this.m_levelName = string.Intern(levelName); +#endif + this.m_levelDisplayName = displayName; + } + + /// + /// Constructor + /// + /// Integer value for this level, higher values represent more severe levels. + /// The string name of this level. + /// + /// + /// Initializes a new instance of the class with + /// the specified level name and value. + /// + /// + public Level(int level, string levelName) : this(level, levelName, levelName) + { + } + + /// + /// Gets the name of this level. + /// + /// + /// The name of this level. + /// + /// + /// + /// Gets the name of this level. + /// + /// + public string Name + { + get { return this.m_levelName; } + } + + /// + /// Gets the value of this level. + /// + /// + /// The value of this level. + /// + /// + /// + /// Gets the value of this level. + /// + /// + public int Value + { + get { return this.m_levelValue; } + } + + /// + /// Gets the display name of this level. + /// + /// + /// The display name of this level. + /// + /// + /// + /// Gets the display name of this level. + /// + /// + public string DisplayName + { + get { return this.m_levelDisplayName; } + } + + /// + /// Returns the representation of the current + /// . + /// + /// + /// A representation of the current . + /// + /// + /// + /// Returns the level . + /// + /// + public override string ToString() + { + return this.m_levelName; + } + + /// + /// Compares levels. + /// + /// The object to compare against. + /// true if the objects are equal. + /// + /// + /// Compares the levels of instances, and + /// defers to base class if the target object is not a + /// instance. + /// + /// + public override bool Equals(object o) + { + Level otherLevel = o as Level; + if (otherLevel != null) + { + return this.m_levelValue == otherLevel.m_levelValue; + } + else + { + return base.Equals(o); + } + } + + /// + /// Returns a hash code + /// + /// A hash code for the current . + /// + /// + /// Returns a hash code suitable for use in hashing algorithms and data + /// structures like a hash table. + /// + /// + /// Returns the hash code of the level . + /// + /// + public override int GetHashCode() + { + return this.m_levelValue; + } + + /// + /// Compares this instance to a specified object and returns an + /// indication of their relative values. + /// + /// A instance or to compare with this instance. + /// + /// A 32-bit signed integer that indicates the relative order of the + /// values compared. The return value has these meanings: + /// + /// + /// Value + /// Meaning + /// + /// + /// Less than zero + /// This instance is less than . + /// + /// + /// Zero + /// This instance is equal to . + /// + /// + /// Greater than zero + /// + /// This instance is greater than . + /// -or- + /// is . + /// + /// + /// + /// + /// + /// + /// must be an instance of + /// or ; otherwise, an exception is thrown. + /// + /// + /// is not a . + public int CompareTo(object r) + { + Level target = r as Level; + if (target != null) + { + return Compare(this, target); + } + throw new ArgumentException("Parameter: r, Value: [" + r + "] is not an instance of Level"); + } + + /// + /// Returns a value indicating whether a specified + /// is greater than another specified . + /// + /// A + /// A + /// + /// true if is greater than + /// ; otherwise, false. + /// + /// + /// + /// Compares two levels. + /// + /// + public static bool operator > (Level l, Level r) + { + return l.m_levelValue > r.m_levelValue; } /// - /// Initializes a new instance of the class. - /// Constructor. - /// - /// Integer value for this level, higher values represent more severe levels. - /// The string name of this level. - /// - /// - /// Initializes a new instance of the class with - /// the specified level name and value. - /// - /// - public Level(int level, string levelName) - : this(level, levelName, levelName) - { + /// Returns a value indicating whether a specified + /// is less than another specified . + /// + /// A + /// A + /// + /// true if is less than + /// ; otherwise, false. + /// + /// + /// + /// Compares two levels. + /// + /// + public static bool operator < (Level l, Level r) + { + return l.m_levelValue < r.m_levelValue; } - /// - /// Gets the name of this level. - /// - /// - /// The name of this level. - /// - /// - /// - /// Gets the name of this level. - /// - /// - public string Name - { - get { return this.m_levelName; } - } - - /// - /// Gets the value of this level. - /// - /// - /// The value of this level. - /// - /// - /// - /// Gets the value of this level. - /// - /// - public int Value - { - get { return this.m_levelValue; } - } - - /// - /// Gets the display name of this level. - /// - /// - /// The display name of this level. - /// - /// - /// - /// Gets the display name of this level. - /// - /// - public string DisplayName - { - get { return this.m_levelDisplayName; } + /// + /// Returns a value indicating whether a specified + /// is greater than or equal to another specified . + /// + /// A + /// A + /// + /// true if is greater than or equal to + /// ; otherwise, false. + /// + /// + /// + /// Compares two levels. + /// + /// + public static bool operator >= (Level l, Level r) + { + return l.m_levelValue >= r.m_levelValue; } - /// - /// Returns the representation of the current - /// . - /// - /// - /// A representation of the current . - /// - /// - /// - /// Returns the level . - /// - /// - public override string ToString() - { - return this.m_levelName; - } - - /// - /// Compares levels. - /// - /// The object to compare against. - /// true if the objects are equal. - /// - /// - /// Compares the levels of instances, and - /// defers to base class if the target object is not a - /// instance. - /// - /// - public override bool Equals(object o) - { - Level otherLevel = o as Level; - if (otherLevel != null) - { - return this.m_levelValue == otherLevel.m_levelValue; - } - else - { - return base.Equals(o); - } - } - - /// - /// Returns a hash code. - /// - /// A hash code for the current . - /// - /// - /// Returns a hash code suitable for use in hashing algorithms and data - /// structures like a hash table. - /// - /// - /// Returns the hash code of the level . - /// - /// - public override int GetHashCode() - { - return this.m_levelValue; + /// + /// Returns a value indicating whether a specified + /// is less than or equal to another specified . + /// + /// A + /// A + /// + /// true if is less than or equal to + /// ; otherwise, false. + /// + /// + /// + /// Compares two levels. + /// + /// + public static bool operator <= (Level l, Level r) + { + return l.m_levelValue <= r.m_levelValue; } - /// - /// Compares this instance to a specified object and returns an - /// indication of their relative values. - /// - /// A instance or to compare with this instance. - /// - /// A 32-bit signed integer that indicates the relative order of the - /// values compared. The return value has these meanings: - /// - /// - /// Value - /// Meaning - /// - /// - /// Less than zero - /// This instance is less than . - /// - /// - /// Zero - /// This instance is equal to . - /// - /// - /// Greater than zero - /// - /// This instance is greater than . - /// -or- - /// is . - /// - /// - /// - /// - /// - /// - /// must be an instance of - /// or ; otherwise, an exception is thrown. - /// - /// - /// is not a . - public int CompareTo(object r) - { - Level target = r as Level; - if (target != null) - { - return Compare(this, target); - } - - throw new ArgumentException("Parameter: r, Value: [" + r + "] is not an instance of Level"); + /// + /// Returns a value indicating whether two specified + /// objects have the same value. + /// + /// A or . + /// A or . + /// + /// true if the value of is the same as the + /// value of ; otherwise, false. + /// + /// + /// + /// Compares two levels. + /// + /// + public static bool operator == (Level l, Level r) + { + if (((object)l) != null && ((object)r) != null) + { + return l.m_levelValue == r.m_levelValue; + } + else + { + return ((object) l) == ((object) r); + } } - /// - /// Returns a value indicating whether a specified - /// is greater than another specified . - /// - /// A . - /// A . - /// - /// true if is greater than - /// ; otherwise, false. - /// - /// - /// - /// Compares two levels. - /// - /// - public static bool operator >(Level l, Level r) - { - return l.m_levelValue > r.m_levelValue; - } - - /// - /// Returns a value indicating whether a specified - /// is less than another specified . - /// - /// A . - /// A . - /// - /// true if is less than - /// ; otherwise, false. - /// - /// - /// - /// Compares two levels. - /// - /// - public static bool operator <(Level l, Level r) - { - return l.m_levelValue < r.m_levelValue; - } - - /// - /// Returns a value indicating whether a specified - /// is greater than or equal to another specified . - /// - /// A . - /// A . - /// - /// true if is greater than or equal to - /// ; otherwise, false. - /// - /// - /// - /// Compares two levels. - /// - /// - public static bool operator >=(Level l, Level r) - { - return l.m_levelValue >= r.m_levelValue; - } - - /// - /// Returns a value indicating whether a specified - /// is less than or equal to another specified . - /// - /// A . - /// A . - /// - /// true if is less than or equal to - /// ; otherwise, false. - /// - /// - /// - /// Compares two levels. - /// - /// - public static bool operator <=(Level l, Level r) - { - return l.m_levelValue <= r.m_levelValue; - } - - /// - /// Returns a value indicating whether two specified - /// objects have the same value. - /// - /// A or . - /// A or . - /// - /// true if the value of is the same as the - /// value of ; otherwise, false. - /// - /// - /// - /// Compares two levels. - /// - /// - public static bool operator ==(Level l, Level r) - { - if (((object)l) != null && ((object)r) != null) - { - return l.m_levelValue == r.m_levelValue; - } - else - { - return ((object)l) == ((object)r); - } - } - - /// - /// Returns a value indicating whether two specified - /// objects have different values. - /// - /// A or . - /// A or . - /// - /// true if the value of is different from - /// the value of ; otherwise, false. - /// - /// - /// - /// Compares two levels. - /// - /// - public static bool operator !=(Level l, Level r) - { - return !(l == r); + /// + /// Returns a value indicating whether two specified + /// objects have different values. + /// + /// A or . + /// A or . + /// + /// true if the value of is different from + /// the value of ; otherwise, false. + /// + /// + /// + /// Compares two levels. + /// + /// + public static bool operator != (Level l, Level r) + { + return !(l == r); } - /// - /// Compares two specified instances. - /// - /// The first to compare. - /// The second to compare. - /// - /// A 32-bit signed integer that indicates the relative order of the - /// two values compared. The return value has these meanings: - /// - /// - /// Value - /// Meaning - /// - /// - /// Less than zero - /// is less than . - /// - /// - /// Zero - /// is equal to . - /// - /// - /// Greater than zero - /// is greater than . - /// - /// - /// - /// - /// - /// Compares two levels. - /// - /// - public static int Compare(Level l, Level r) - { - // Reference equals - if ((object)l == (object)r) - { - return 0; - } - - if (l == null && r == null) - { - return 0; - } - - if (l == null) - { - return -1; - } - - if (r == null) - { - return 1; - } - - return l.m_levelValue.CompareTo(r.m_levelValue); + /// + /// Compares two specified instances. + /// + /// The first to compare. + /// The second to compare. + /// + /// A 32-bit signed integer that indicates the relative order of the + /// two values compared. The return value has these meanings: + /// + /// + /// Value + /// Meaning + /// + /// + /// Less than zero + /// is less than . + /// + /// + /// Zero + /// is equal to . + /// + /// + /// Greater than zero + /// is greater than . + /// + /// + /// + /// + /// + /// Compares two levels. + /// + /// + public static int Compare(Level l, Level r) + { + // Reference equals + if ((object)l == (object)r) + { + return 0; + } + + if (l == null && r == null) + { + return 0; + } + if (l == null) + { + return -1; + } + if (r == null) + { + return 1; + } + + return l.m_levelValue.CompareTo(r.m_levelValue); } - /// - /// The level designates a higher level than all the rest. - /// - public static readonly Level Off = new Level(int.MaxValue, "OFF"); - - /// - /// The level designates very severe error events. - /// System unusable, emergencies. - /// - public static readonly Level Log4Net_Debug = new Level(120000, "log4net:DEBUG"); - - /// - /// The level designates very severe error events. - /// System unusable, emergencies. - /// - public static readonly Level Emergency = new Level(120000, "EMERGENCY"); - - /// - /// The level designates very severe error events - /// that will presumably lead the application to abort. - /// - public static readonly Level Fatal = new Level(110000, "FATAL"); - - /// - /// The level designates very severe error events. - /// Take immediate action, alerts. - /// - public static readonly Level Alert = new Level(100000, "ALERT"); - - /// - /// The level designates very severe error events. - /// Critical condition, critical. - /// - public static readonly Level Critical = new Level(90000, "CRITICAL"); - - /// - /// The level designates very severe error events. - /// - public static readonly Level Severe = new Level(80000, "SEVERE"); - - /// - /// The level designates error events that might - /// still allow the application to continue running. - /// - public static readonly Level Error = new Level(70000, "ERROR"); - - /// - /// The level designates potentially harmful - /// situations. - /// - public static readonly Level Warn = new Level(60000, "WARN"); - - /// - /// The level designates informational messages - /// that highlight the progress of the application at the highest level. - /// - public static readonly Level Notice = new Level(50000, "NOTICE"); - - /// - /// The level designates informational messages that - /// highlight the progress of the application at coarse-grained level. - /// - public static readonly Level Info = new Level(40000, "INFO"); - - /// - /// The level designates fine-grained informational - /// events that are most useful to debug an application. - /// - public static readonly Level Debug = new Level(30000, "DEBUG"); - - /// - /// The level designates fine-grained informational - /// events that are most useful to debug an application. - /// - public static readonly Level Fine = new Level(30000, "FINE"); - - /// - /// The level designates fine-grained informational - /// events that are most useful to debug an application. - /// - public static readonly Level Trace = new Level(20000, "TRACE"); - - /// - /// The level designates fine-grained informational - /// events that are most useful to debug an application. - /// - public static readonly Level Finer = new Level(20000, "FINER"); - - /// - /// The level designates fine-grained informational - /// events that are most useful to debug an application. - /// - public static readonly Level Verbose = new Level(10000, "VERBOSE"); - - /// - /// The level designates fine-grained informational - /// events that are most useful to debug an application. - /// - public static readonly Level Finest = new Level(10000, "FINEST"); - - /// - /// The level designates the lowest level possible. - /// + /// + /// The level designates a higher level than all the rest. + /// + public static readonly Level Off = new Level(int.MaxValue, "OFF"); + + /// + /// The level designates very severe error events. + /// System unusable, emergencies. + /// + public static readonly Level Log4Net_Debug = new Level(120000, "log4net:DEBUG"); + + /// + /// The level designates very severe error events. + /// System unusable, emergencies. + /// + public static readonly Level Emergency = new Level(120000, "EMERGENCY"); + + /// + /// The level designates very severe error events + /// that will presumably lead the application to abort. + /// + public static readonly Level Fatal = new Level(110000, "FATAL"); + + /// + /// The level designates very severe error events. + /// Take immediate action, alerts. + /// + public static readonly Level Alert = new Level(100000, "ALERT"); + + /// + /// The level designates very severe error events. + /// Critical condition, critical. + /// + public static readonly Level Critical = new Level(90000, "CRITICAL"); + + /// + /// The level designates very severe error events. + /// + public static readonly Level Severe = new Level(80000, "SEVERE"); + + /// + /// The level designates error events that might + /// still allow the application to continue running. + /// + public static readonly Level Error = new Level(70000, "ERROR"); + + /// + /// The level designates potentially harmful + /// situations. + /// + public static readonly Level Warn = new Level(60000, "WARN"); + + /// + /// The level designates informational messages + /// that highlight the progress of the application at the highest level. + /// + public static readonly Level Notice = new Level(50000, "NOTICE"); + + /// + /// The level designates informational messages that + /// highlight the progress of the application at coarse-grained level. + /// + public static readonly Level Info = new Level(40000, "INFO"); + + /// + /// The level designates fine-grained informational + /// events that are most useful to debug an application. + /// + public static readonly Level Debug = new Level(30000, "DEBUG"); + + /// + /// The level designates fine-grained informational + /// events that are most useful to debug an application. + /// + public static readonly Level Fine = new Level(30000, "FINE"); + + /// + /// The level designates fine-grained informational + /// events that are most useful to debug an application. + /// + public static readonly Level Trace = new Level(20000, "TRACE"); + + /// + /// The level designates fine-grained informational + /// events that are most useful to debug an application. + /// + public static readonly Level Finer = new Level(20000, "FINER"); + + /// + /// The level designates fine-grained informational + /// events that are most useful to debug an application. + /// + public static readonly Level Verbose = new Level(10000, "VERBOSE"); + + /// + /// The level designates fine-grained informational + /// events that are most useful to debug an application. + /// + public static readonly Level Finest = new Level(10000, "FINEST"); + + /// + /// The level designates the lowest level possible. + /// public static readonly Level All = new Level(int.MinValue, "ALL"); - private readonly int m_levelValue; - private readonly string m_levelName; + + private readonly int m_levelValue; + private readonly string m_levelName; private readonly string m_levelDisplayName; - } -} + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Core/LevelCollection.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Core/LevelCollection.cs index d60a3478db0..754beb2ea9f 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Core/LevelCollection.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Core/LevelCollection.cs @@ -1,780 +1,769 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information - -namespace log4net.Core -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; - using System.Collections; - - /// - /// A strongly-typed collection of objects. - /// - /// Nicko Cadell. - public class LevelCollection : ICollection, IList, IEnumerable -#if !NETSTANDARD1_3 - , ICloneable -#endif +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +using System; +using System.Collections; + +namespace log4net.Core +{ + /// + /// A strongly-typed collection of objects. + /// + /// Nicko Cadell + public class LevelCollection : ICollection, IList, IEnumerable +#if !NETSTANDARD1_3 + , ICloneable +#endif { - /// - /// Supports type-safe iteration over a . - /// - public interface ILevelCollectionEnumerator - { - /// - /// Gets the current element in the collection. - /// - Level Current { get; } - - /// - /// Advances the enumerator to the next element in the collection. - /// - /// - /// true if the enumerator was successfully advanced to the next element; - /// false if the enumerator has passed the end of the collection. - /// - /// - /// The collection was modified after the enumerator was created. - /// - bool MoveNext(); - - /// - /// Sets the enumerator to its initial position, before the first element in the collection. - /// - void Reset(); + /// + /// Supports type-safe iteration over a . + /// + public interface ILevelCollectionEnumerator + { + /// + /// Gets the current element in the collection. + /// + Level Current { get; } + + /// + /// Advances the enumerator to the next element in the collection. + /// + /// + /// true if the enumerator was successfully advanced to the next element; + /// false if the enumerator has passed the end of the collection. + /// + /// + /// The collection was modified after the enumerator was created. + /// + bool MoveNext(); + + /// + /// Sets the enumerator to its initial position, before the first element in the collection. + /// + void Reset(); } private const int DEFAULT_CAPACITY = 16; - private Level[] m_array; - private int m_count = 0; + + private Level[] m_array; + private int m_count = 0; private int m_version = 0; - /// - /// Creates a read-only wrapper for a LevelCollection instance. - /// - /// list to create a readonly wrapper arround. - /// - /// A LevelCollection wrapper that is read-only. - /// - public static LevelCollection ReadOnly(LevelCollection list) - { - if (list == null) + /// + /// Creates a read-only wrapper for a LevelCollection instance. + /// + /// list to create a readonly wrapper arround + /// + /// A LevelCollection wrapper that is read-only. + /// + public static LevelCollection ReadOnly(LevelCollection list) + { + if(list == null) { throw new ArgumentNullException("list"); } - return new ReadOnlyLevelCollection(list); - } - - /// - /// Initializes a new instance of the class. - /// Initializes a new instance of the LevelCollection class - /// that is empty and has the default initial capacity. - /// - public LevelCollection() - { - this.m_array = new Level[DEFAULT_CAPACITY]; - } - - /// - /// Initializes a new instance of the class. - /// Initializes a new instance of the LevelCollection class - /// that has the specified initial capacity. - /// - /// - /// The number of elements that the new LevelCollection is initially capable of storing. - /// - public LevelCollection(int capacity) - { - this.m_array = new Level[capacity]; - } - - /// - /// Initializes a new instance of the class. - /// Initializes a new instance of the LevelCollection class - /// that contains elements copied from the specified LevelCollection. - /// - /// The LevelCollection whose elements are copied to the new collection. - public LevelCollection(LevelCollection c) - { - this.m_array = new Level[c.Count]; - this.AddRange(c); - } - - /// - /// Initializes a new instance of the class. - /// Initializes a new instance of the LevelCollection class - /// that contains elements copied from the specified array. - /// - /// The array whose elements are copied to the new list. - public LevelCollection(Level[] a) - { - this.m_array = new Level[a.Length]; - this.AddRange(a); - } - - /// - /// Initializes a new instance of the class. - /// Initializes a new instance of the LevelCollection class - /// that contains elements copied from the specified collection. - /// - /// The collection whose elements are copied to the new list. - public LevelCollection(ICollection col) - { - this.m_array = new Level[col.Count]; - this.AddRange(col); - } - - /// - /// Type visible only to our subclasses - /// Used to access protected constructor. - /// - protected internal enum Tag - { - /// - /// A value - /// - Default, - } - - /// - /// Initializes a new instance of the class. - /// Allow subclasses to avoid our default constructors. - /// - /// - protected internal LevelCollection(Tag tag) - { - this.m_array = null; - } - - /// - /// Gets the number of elements actually contained in the LevelCollection. - /// - public virtual int Count - { - get { return this.m_count; } - } - - /// - /// Copies the entire LevelCollection to a one-dimensional - /// array. - /// - /// The one-dimensional array to copy to. - public virtual void CopyTo(Level[] array) - { - this.CopyTo(array, 0); - } - - /// - /// Copies the entire LevelCollection to a one-dimensional - /// array, starting at the specified index of the target array. - /// - /// The one-dimensional array to copy to. - /// The zero-based index in at which copying begins. - public virtual void CopyTo(Level[] array, int start) - { - if (this.m_count > array.GetUpperBound(0) + 1 - start) - { - throw new System.ArgumentException("Destination array was not long enough."); - } - - Array.Copy(this.m_array, 0, array, start, this.m_count); - } - - /// - /// Gets a value indicating whether access to the collection is synchronized (thread-safe). - /// - /// false, because the backing type is an array, which is never thread-safe. - public virtual bool IsSynchronized - { - get { return false; } - } - - /// - /// Gets an object that can be used to synchronize access to the collection. - /// - public virtual object SyncRoot - { - get { return this.m_array; } - } - - /// - /// Gets or sets the at the specified index. - /// - /// The zero-based index of the element to get or set. - /// - /// is less than zero. - /// -or- - /// is equal to or greater than . - /// - public virtual Level this[int index] - { - get - { - this.ValidateIndex(index); // throws - return this.m_array[index]; - } - - set - { - this.ValidateIndex(index); // throws - ++this.m_version; - this.m_array[index] = value; - } - } - - /// - /// Adds a to the end of the LevelCollection. - /// - /// The to be added to the end of the LevelCollection. - /// The index at which the value has been added. - public virtual int Add(Level item) - { - if (this.m_count == this.m_array.Length) - { - this.EnsureCapacity(this.m_count + 1); - } - - this.m_array[this.m_count] = item; - this.m_version++; - - return this.m_count++; - } - - /// - /// Removes all elements from the LevelCollection. - /// - public virtual void Clear() - { - ++this.m_version; - this.m_array = new Level[DEFAULT_CAPACITY]; - this.m_count = 0; - } - - /// - /// Creates a shallow copy of the . - /// - /// A new with a shallow copy of the collection data. - public virtual object Clone() - { - LevelCollection newCol = new LevelCollection(this.m_count); - Array.Copy(this.m_array, 0, newCol.m_array, 0, this.m_count); - newCol.m_count = this.m_count; - newCol.m_version = this.m_version; - - return newCol; - } - - /// - /// Determines whether a given is in the LevelCollection. - /// - /// The to check for. - /// true if is found in the LevelCollection; otherwise, false. - public virtual bool Contains(Level item) - { - for (int i = 0; i != this.m_count; ++i) - { - if (this.m_array[i].Equals(item)) - { - return true; - } - } - - return false; - } - - /// - /// Returns the zero-based index of the first occurrence of a - /// in the LevelCollection. - /// - /// The to locate in the LevelCollection. - /// - /// The zero-based index of the first occurrence of - /// in the entire LevelCollection, if found; otherwise, -1. - /// - public virtual int IndexOf(Level item) - { - for (int i = 0; i != this.m_count; ++i) - { - if (this.m_array[i].Equals(item)) - { - return i; - } - } - - return -1; - } - - /// - /// Inserts an element into the LevelCollection at the specified index. - /// - /// The zero-based index at which should be inserted. - /// The to insert. - /// - /// is less than zero. - /// -or- - /// is equal to or greater than . - /// - public virtual void Insert(int index, Level item) - { - this.ValidateIndex(index, true); // throws - - if (this.m_count == this.m_array.Length) - { - this.EnsureCapacity(this.m_count + 1); - } - - if (index < this.m_count) - { - Array.Copy(this.m_array, index, this.m_array, index + 1, this.m_count - index); - } - - this.m_array[index] = item; - this.m_count++; - this.m_version++; - } - - /// - /// Removes the first occurrence of a specific from the LevelCollection. - /// - /// The to remove from the LevelCollection. - /// - /// The specified was not found in the LevelCollection. - /// - public virtual void Remove(Level item) - { - int i = this.IndexOf(item); - if (i < 0) - { - throw new System.ArgumentException("Cannot remove the specified item because it was not found in the specified Collection."); - } - - ++this.m_version; - this.RemoveAt(i); - } - - /// - /// Removes the element at the specified index of the LevelCollection. - /// - /// The zero-based index of the element to remove. - /// - /// is less than zero. - /// -or- - /// is equal to or greater than . - /// - public virtual void RemoveAt(int index) - { - this.ValidateIndex(index); // throws - - this.m_count--; - - if (index < this.m_count) - { - Array.Copy(this.m_array, index + 1, this.m_array, index, this.m_count - index); - } - - // We can't set the deleted entry equal to null, because it might be a value type. - // Instead, we'll create an empty single-element array of the right type and copy it - // over the entry we want to erase. - Level[] temp = new Level[1]; - Array.Copy(temp, 0, this.m_array, this.m_count, 1); - this.m_version++; - } - - /// - /// Gets a value indicating whether the collection has a fixed size. - /// - /// true if the collection has a fixed size; otherwise, false. The default is false. - public virtual bool IsFixedSize - { - get { return false; } - } - - /// - /// Gets a value indicating whether the IList is read-only. - /// - /// true if the collection is read-only; otherwise, false. The default is false. - public virtual bool IsReadOnly - { - get { return false; } - } - - /// - /// Returns an enumerator that can iterate through the LevelCollection. - /// - /// An for the entire LevelCollection. - public virtual ILevelCollectionEnumerator GetEnumerator() - { - return new Enumerator(this); - } - - /// - /// Gets or sets the number of elements the LevelCollection can contain. - /// - public virtual int Capacity - { - get - { - return this.m_array.Length; - } - - set - { - if (value < this.m_count) - { - value = this.m_count; - } - - if (value != this.m_array.Length) - { - if (value > 0) - { - Level[] temp = new Level[value]; - Array.Copy(this.m_array, 0, temp, 0, this.m_count); - this.m_array = temp; - } - else - { - this.m_array = new Level[DEFAULT_CAPACITY]; - } - } - } - } - - /// - /// Adds the elements of another LevelCollection to the current LevelCollection. - /// - /// The LevelCollection whose elements should be added to the end of the current LevelCollection. - /// The new of the LevelCollection. - public virtual int AddRange(LevelCollection x) - { - if (this.m_count + x.Count >= this.m_array.Length) - { - this.EnsureCapacity(this.m_count + x.Count); - } - - Array.Copy(x.m_array, 0, this.m_array, this.m_count, x.Count); - this.m_count += x.Count; - this.m_version++; - - return this.m_count; - } - - /// - /// Adds the elements of a array to the current LevelCollection. - /// - /// The array whose elements should be added to the end of the LevelCollection. - /// The new of the LevelCollection. - public virtual int AddRange(Level[] x) - { - if (this.m_count + x.Length >= this.m_array.Length) - { - this.EnsureCapacity(this.m_count + x.Length); - } - - Array.Copy(x, 0, this.m_array, this.m_count, x.Length); - this.m_count += x.Length; - this.m_version++; - - return this.m_count; - } - - /// - /// Adds the elements of a collection to the current LevelCollection. - /// - /// The collection whose elements should be added to the end of the LevelCollection. - /// The new of the LevelCollection. - public virtual int AddRange(ICollection col) - { - if (this.m_count + col.Count >= this.m_array.Length) - { - this.EnsureCapacity(this.m_count + col.Count); - } - - foreach (object item in col) - { - this.Add((Level)item); - } - - return this.m_count; - } - - /// - /// Sets the capacity to the actual number of elements. - /// - public virtual void TrimToSize() - { - this.Capacity = this.m_count; - } - - /// - /// is less than zero. - /// -or- - /// is equal to or greater than . - /// - private void ValidateIndex(int i) - { - this.ValidateIndex(i, false); - } - - /// - /// is less than zero. - /// -or- - /// is equal to or greater than . - /// - private void ValidateIndex(int i, bool allowEqualEnd) - { - int max = allowEqualEnd ? this.m_count : (this.m_count - 1); - if (i < 0 || i > max) - { - throw log4net.Util.SystemInfo.CreateArgumentOutOfRangeException("i", (object)i, "Index was out of range. Must be non-negative and less than the size of the collection. [" + (object)i + "] Specified argument was out of the range of valid values."); - } - } - - private void EnsureCapacity(int min) - { - int newCapacity = (this.m_array.Length == 0) ? DEFAULT_CAPACITY : this.m_array.Length * 2; - if (newCapacity < min) - { - newCapacity = min; - } - - this.Capacity = newCapacity; - } - - void ICollection.CopyTo(Array array, int start) - { - Array.Copy(this.m_array, 0, array, start, this.m_count); - } - - object IList.this[int i] - { - get { return (object)this[i]; } - set { this[i] = (Level)value; } - } - - int IList.Add(object x) - { - return this.Add((Level)x); - } - - bool IList.Contains(object x) - { - return this.Contains((Level)x); - } - - int IList.IndexOf(object x) - { - return this.IndexOf((Level)x); - } - - void IList.Insert(int pos, object x) - { - this.Insert(pos, (Level)x); - } - - void IList.Remove(object x) - { - this.Remove((Level)x); - } - - void IList.RemoveAt(int pos) - { - this.RemoveAt(pos); - } - - IEnumerator IEnumerable.GetEnumerator() - { - return (IEnumerator)this.GetEnumerator(); - } - - /// - /// Supports simple iteration over a . - /// - private sealed class Enumerator : IEnumerator, ILevelCollectionEnumerator - { - private readonly LevelCollection m_collection; - private int m_index; + return new ReadOnlyLevelCollection(list); + } + + /// + /// Initializes a new instance of the LevelCollection class + /// that is empty and has the default initial capacity. + /// + public LevelCollection() + { + this.m_array = new Level[DEFAULT_CAPACITY]; + } + + /// + /// Initializes a new instance of the LevelCollection class + /// that has the specified initial capacity. + /// + /// + /// The number of elements that the new LevelCollection is initially capable of storing. + /// + public LevelCollection(int capacity) + { + this.m_array = new Level[capacity]; + } + + /// + /// Initializes a new instance of the LevelCollection class + /// that contains elements copied from the specified LevelCollection. + /// + /// The LevelCollection whose elements are copied to the new collection. + public LevelCollection(LevelCollection c) + { + this.m_array = new Level[c.Count]; + this.AddRange(c); + } + + /// + /// Initializes a new instance of the LevelCollection class + /// that contains elements copied from the specified array. + /// + /// The array whose elements are copied to the new list. + public LevelCollection(Level[] a) + { + this.m_array = new Level[a.Length]; + this.AddRange(a); + } + + /// + /// Initializes a new instance of the LevelCollection class + /// that contains elements copied from the specified collection. + /// + /// The collection whose elements are copied to the new list. + public LevelCollection(ICollection col) + { + this.m_array = new Level[col.Count]; + this.AddRange(col); + } + + /// + /// Type visible only to our subclasses + /// Used to access protected constructor + /// + protected internal enum Tag + { + /// + /// A value + /// + Default + } + + /// + /// Allow subclasses to avoid our default constructors + /// + /// + protected internal LevelCollection(Tag tag) + { + this.m_array = null; + } + + /// + /// Gets the number of elements actually contained in the LevelCollection. + /// + public virtual int Count + { + get { return this.m_count; } + } + + /// + /// Copies the entire LevelCollection to a one-dimensional + /// array. + /// + /// The one-dimensional array to copy to. + public virtual void CopyTo(Level[] array) + { + this.CopyTo(array, 0); + } + + /// + /// Copies the entire LevelCollection to a one-dimensional + /// array, starting at the specified index of the target array. + /// + /// The one-dimensional array to copy to. + /// The zero-based index in at which copying begins. + public virtual void CopyTo(Level[] array, int start) + { + if (this.m_count > array.GetUpperBound(0) + 1 - start) + { + throw new ArgumentException("Destination array was not long enough."); + } + + Array.Copy(this.m_array, 0, array, start, this.m_count); + } + + /// + /// Gets a value indicating whether access to the collection is synchronized (thread-safe). + /// + /// false, because the backing type is an array, which is never thread-safe. + public virtual bool IsSynchronized + { + get { return false; } + } + + /// + /// Gets an object that can be used to synchronize access to the collection. + /// + public virtual object SyncRoot + { + get { return this.m_array; } + } + + /// + /// Gets or sets the at the specified index. + /// + /// The zero-based index of the element to get or set. + /// + /// is less than zero + /// -or- + /// is equal to or greater than . + /// + public virtual Level this[int index] + { + get + { + this.ValidateIndex(index); // throws + return this.m_array[index]; + } + set + { + this.ValidateIndex(index); // throws + ++this.m_version; + this.m_array[index] = value; + } + } + + /// + /// Adds a to the end of the LevelCollection. + /// + /// The to be added to the end of the LevelCollection. + /// The index at which the value has been added. + public virtual int Add(Level item) + { + if (this.m_count == this.m_array.Length) + { + this.EnsureCapacity(this.m_count + 1); + } + + this.m_array[this.m_count] = item; + this.m_version++; + + return this.m_count++; + } + + /// + /// Removes all elements from the LevelCollection. + /// + public virtual void Clear() + { + ++this.m_version; + this.m_array = new Level[DEFAULT_CAPACITY]; + this.m_count = 0; + } + + /// + /// Creates a shallow copy of the . + /// + /// A new with a shallow copy of the collection data. + public virtual object Clone() + { + LevelCollection newCol = new LevelCollection(this.m_count); + Array.Copy(this.m_array, 0, newCol.m_array, 0, this.m_count); + newCol.m_count = this.m_count; + newCol.m_version = this.m_version; + + return newCol; + } + + /// + /// Determines whether a given is in the LevelCollection. + /// + /// The to check for. + /// true if is found in the LevelCollection; otherwise, false. + public virtual bool Contains(Level item) + { + for (int i = 0; i != this.m_count; ++i) + { + if (this.m_array[i].Equals(item)) + { + return true; + } + } + return false; + } + + /// + /// Returns the zero-based index of the first occurrence of a + /// in the LevelCollection. + /// + /// The to locate in the LevelCollection. + /// + /// The zero-based index of the first occurrence of + /// in the entire LevelCollection, if found; otherwise, -1. + /// + public virtual int IndexOf(Level item) + { + for (int i = 0; i != this.m_count; ++i) + { + if (this.m_array[i].Equals(item)) + { + return i; + } + } + return -1; + } + + /// + /// Inserts an element into the LevelCollection at the specified index. + /// + /// The zero-based index at which should be inserted. + /// The to insert. + /// + /// is less than zero + /// -or- + /// is equal to or greater than . + /// + public virtual void Insert(int index, Level item) + { + this.ValidateIndex(index, true); // throws + + if (this.m_count == this.m_array.Length) + { + this.EnsureCapacity(this.m_count + 1); + } + + if (index < this.m_count) + { + Array.Copy(this.m_array, index, this.m_array, index + 1, this.m_count - index); + } + + this.m_array[index] = item; + this.m_count++; + this.m_version++; + } + + /// + /// Removes the first occurrence of a specific from the LevelCollection. + /// + /// The to remove from the LevelCollection. + /// + /// The specified was not found in the LevelCollection. + /// + public virtual void Remove(Level item) + { + int i = this.IndexOf(item); + if (i < 0) + { + throw new ArgumentException("Cannot remove the specified item because it was not found in the specified Collection."); + } + + ++this.m_version; + this.RemoveAt(i); + } + + /// + /// Removes the element at the specified index of the LevelCollection. + /// + /// The zero-based index of the element to remove. + /// + /// is less than zero + /// -or- + /// is equal to or greater than . + /// + public virtual void RemoveAt(int index) + { + this.ValidateIndex(index); // throws + + this.m_count--; + + if (index < this.m_count) + { + Array.Copy(this.m_array, index + 1, this.m_array, index, this.m_count - index); + } + + // We can't set the deleted entry equal to null, because it might be a value type. + // Instead, we'll create an empty single-element array of the right type and copy it + // over the entry we want to erase. + Level[] temp = new Level[1]; + Array.Copy(temp, 0, this.m_array, this.m_count, 1); + this.m_version++; + } + + /// + /// Gets a value indicating whether the collection has a fixed size. + /// + /// true if the collection has a fixed size; otherwise, false. The default is false + public virtual bool IsFixedSize + { + get { return false; } + } + + /// + /// Gets a value indicating whether the IList is read-only. + /// + /// true if the collection is read-only; otherwise, false. The default is false + public virtual bool IsReadOnly + { + get { return false; } + } + + /// + /// Returns an enumerator that can iterate through the LevelCollection. + /// + /// An for the entire LevelCollection. + public virtual ILevelCollectionEnumerator GetEnumerator() + { + return new Enumerator(this); + } + + /// + /// Gets or sets the number of elements the LevelCollection can contain. + /// + public virtual int Capacity + { + get + { + return this.m_array.Length; + } + set + { + if (value < this.m_count) + { + value = this.m_count; + } + + if (value != this.m_array.Length) + { + if (value > 0) + { + Level[] temp = new Level[value]; + Array.Copy(this.m_array, 0, temp, 0, this.m_count); + this.m_array = temp; + } + else + { + this.m_array = new Level[DEFAULT_CAPACITY]; + } + } + } + } + + /// + /// Adds the elements of another LevelCollection to the current LevelCollection. + /// + /// The LevelCollection whose elements should be added to the end of the current LevelCollection. + /// The new of the LevelCollection. + public virtual int AddRange(LevelCollection x) + { + if (this.m_count + x.Count >= this.m_array.Length) + { + this.EnsureCapacity(this.m_count + x.Count); + } + + Array.Copy(x.m_array, 0, this.m_array, this.m_count, x.Count); + this.m_count += x.Count; + this.m_version++; + + return this.m_count; + } + + /// + /// Adds the elements of a array to the current LevelCollection. + /// + /// The array whose elements should be added to the end of the LevelCollection. + /// The new of the LevelCollection. + public virtual int AddRange(Level[] x) + { + if (this.m_count + x.Length >= this.m_array.Length) + { + this.EnsureCapacity(this.m_count + x.Length); + } + + Array.Copy(x, 0, this.m_array, this.m_count, x.Length); + this.m_count += x.Length; + this.m_version++; + + return this.m_count; + } + + /// + /// Adds the elements of a collection to the current LevelCollection. + /// + /// The collection whose elements should be added to the end of the LevelCollection. + /// The new of the LevelCollection. + public virtual int AddRange(ICollection col) + { + if (this.m_count + col.Count >= this.m_array.Length) + { + this.EnsureCapacity(this.m_count + col.Count); + } + + foreach(object item in col) + { + this.Add((Level)item); + } + + return this.m_count; + } + + /// + /// Sets the capacity to the actual number of elements. + /// + public virtual void TrimToSize() + { + this.Capacity = this.m_count; + } + + /// + /// is less than zero + /// -or- + /// is equal to or greater than . + /// + private void ValidateIndex(int i) + { + this.ValidateIndex(i, false); + } + + /// + /// is less than zero + /// -or- + /// is equal to or greater than . + /// + private void ValidateIndex(int i, bool allowEqualEnd) + { + int max = (allowEqualEnd) ? (this.m_count) : (this.m_count-1); + if (i < 0 || i > max) + { + throw Util.SystemInfo.CreateArgumentOutOfRangeException("i", (object)i, "Index was out of range. Must be non-negative and less than the size of the collection. [" + (object)i + "] Specified argument was out of the range of valid values."); + } + } + + private void EnsureCapacity(int min) + { + int newCapacity = ((this.m_array.Length == 0) ? DEFAULT_CAPACITY : this.m_array.Length * 2); + if (newCapacity < min) + { + newCapacity = min; + } + + this.Capacity = newCapacity; + } + + void ICollection.CopyTo(Array array, int start) + { + Array.Copy(this.m_array, 0, array, start, this.m_count); + } + + object IList.this[int i] + { + get { return (object)this[i]; } + set { this[i] = (Level)value; } + } + + int IList.Add(object x) + { + return this.Add((Level)x); + } + + bool IList.Contains(object x) + { + return this.Contains((Level)x); + } + + int IList.IndexOf(object x) + { + return this.IndexOf((Level)x); + } + + void IList.Insert(int pos, object x) + { + this.Insert(pos, (Level)x); + } + + void IList.Remove(object x) + { + this.Remove((Level)x); + } + + void IList.RemoveAt(int pos) + { + this.RemoveAt(pos); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return (IEnumerator)(this.GetEnumerator()); + } + + /// + /// Supports simple iteration over a . + /// + private sealed class Enumerator : IEnumerator, ILevelCollectionEnumerator + { + private readonly LevelCollection m_collection; + private int m_index; private int m_version; /// - /// Initializes a new instance of the class. - /// Initializes a new instance of the Enumerator class. - /// - /// - internal Enumerator(LevelCollection tc) - { - this.m_collection = tc; - this.m_index = -1; - this.m_version = tc.m_version; - } - - /// - /// Gets the current element in the collection. - /// - public Level Current - { - get { return this.m_collection[this.m_index]; } - } - - /// - /// Advances the enumerator to the next element in the collection. - /// - /// - /// true if the enumerator was successfully advanced to the next element; - /// false if the enumerator has passed the end of the collection. - /// - /// - /// The collection was modified after the enumerator was created. - /// - public bool MoveNext() - { - if (this.m_version != this.m_collection.m_version) - { - throw new System.InvalidOperationException("Collection was modified; enumeration operation may not execute."); - } - - ++this.m_index; - return this.m_index < this.m_collection.Count; - } - - /// - /// Sets the enumerator to its initial position, before the first element in the collection. - /// - public void Reset() - { - this.m_index = -1; - } - - object IEnumerator.Current - { - get { return this.Current; } - } - } - - private sealed class ReadOnlyLevelCollection : LevelCollection + /// Initializes a new instance of the Enumerator class. + /// + /// + internal Enumerator(LevelCollection tc) + { + this.m_collection = tc; + this.m_index = -1; + this.m_version = tc.m_version; + } + + /// + /// Gets the current element in the collection. + /// + public Level Current + { + get { return this.m_collection[this.m_index]; } + } + + /// + /// Advances the enumerator to the next element in the collection. + /// + /// + /// true if the enumerator was successfully advanced to the next element; + /// false if the enumerator has passed the end of the collection. + /// + /// + /// The collection was modified after the enumerator was created. + /// + public bool MoveNext() + { + if (this.m_version != this.m_collection.m_version) + { + throw new InvalidOperationException("Collection was modified; enumeration operation may not execute."); + } + + ++this.m_index; + return (this.m_index < this.m_collection.Count); + } + + /// + /// Sets the enumerator to its initial position, before the first element in the collection. + /// + public void Reset() + { + this.m_index = -1; + } + + object IEnumerator.Current + { + get { return this.Current; } + } + } + + private sealed class ReadOnlyLevelCollection : LevelCollection { private readonly LevelCollection m_collection; - internal ReadOnlyLevelCollection(LevelCollection list) - : base(Tag.Default) - { - this.m_collection = list; - } - - public override void CopyTo(Level[] array) - { - this.m_collection.CopyTo(array); - } - - public override void CopyTo(Level[] array, int start) - { - this.m_collection.CopyTo(array, start); - } - - public override int Count - { - get { return this.m_collection.Count; } - } - - public override bool IsSynchronized - { - get { return this.m_collection.IsSynchronized; } - } - - public override object SyncRoot - { - get { return this.m_collection.SyncRoot; } - } - - public override Level this[int i] - { - get { return this.m_collection[i]; } - set { throw new NotSupportedException("This is a Read Only Collection and can not be modified"); } - } - - public override int Add(Level x) - { - throw new NotSupportedException("This is a Read Only Collection and can not be modified"); - } - - public override void Clear() - { - throw new NotSupportedException("This is a Read Only Collection and can not be modified"); - } - - public override bool Contains(Level x) - { - return this.m_collection.Contains(x); - } - - public override int IndexOf(Level x) - { - return this.m_collection.IndexOf(x); - } - - public override void Insert(int pos, Level x) - { - throw new NotSupportedException("This is a Read Only Collection and can not be modified"); - } - - public override void Remove(Level x) - { - throw new NotSupportedException("This is a Read Only Collection and can not be modified"); - } - - public override void RemoveAt(int pos) - { - throw new NotSupportedException("This is a Read Only Collection and can not be modified"); - } - - public override bool IsFixedSize - { - get { return true; } - } - - public override bool IsReadOnly - { - get { return true; } - } - - public override ILevelCollectionEnumerator GetEnumerator() - { - return this.m_collection.GetEnumerator(); + internal ReadOnlyLevelCollection(LevelCollection list) : base(Tag.Default) + { + this.m_collection = list; + } + + public override void CopyTo(Level[] array) + { + this.m_collection.CopyTo(array); + } + + public override void CopyTo(Level[] array, int start) + { + this.m_collection.CopyTo(array,start); + } + public override int Count + { + get { return this.m_collection.Count; } + } + + public override bool IsSynchronized + { + get { return this.m_collection.IsSynchronized; } + } + + public override object SyncRoot + { + get { return this.m_collection.SyncRoot; } + } + + public override Level this[int i] + { + get { return this.m_collection[i]; } + set { throw new NotSupportedException("This is a Read Only Collection and can not be modified"); } + } + + public override int Add(Level x) + { + throw new NotSupportedException("This is a Read Only Collection and can not be modified"); + } + + public override void Clear() + { + throw new NotSupportedException("This is a Read Only Collection and can not be modified"); + } + + public override bool Contains(Level x) + { + return this.m_collection.Contains(x); + } + + public override int IndexOf(Level x) + { + return this.m_collection.IndexOf(x); + } + + public override void Insert(int pos, Level x) + { + throw new NotSupportedException("This is a Read Only Collection and can not be modified"); + } + + public override void Remove(Level x) + { + throw new NotSupportedException("This is a Read Only Collection and can not be modified"); + } + + public override void RemoveAt(int pos) + { + throw new NotSupportedException("This is a Read Only Collection and can not be modified"); + } + + public override bool IsFixedSize + { + get { return true; } + } + + public override bool IsReadOnly + { + get { return true; } + } + + public override ILevelCollectionEnumerator GetEnumerator() + { + return this.m_collection.GetEnumerator(); } // (just to mimic some nice features of ArrayList) - public override int Capacity - { - get { return this.m_collection.Capacity; } - set { throw new NotSupportedException("This is a Read Only Collection and can not be modified"); } - } - - public override int AddRange(LevelCollection x) - { - throw new NotSupportedException("This is a Read Only Collection and can not be modified"); - } - - public override int AddRange(Level[] x) - { - throw new NotSupportedException("This is a Read Only Collection and can not be modified"); - } - } - } -} + public override int Capacity + { + get { return this.m_collection.Capacity; } + set { throw new NotSupportedException("This is a Read Only Collection and can not be modified"); } + } + + public override int AddRange(LevelCollection x) + { + throw new NotSupportedException("This is a Read Only Collection and can not be modified"); + } + + public override int AddRange(Level[] x) + { + throw new NotSupportedException("This is a Read Only Collection and can not be modified"); + } + } + } + +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Core/LevelEvaluator.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Core/LevelEvaluator.cs index f6c8f2393e0..931d43a2f4e 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Core/LevelEvaluator.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Core/LevelEvaluator.cs @@ -1,137 +1,134 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.Core -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; +using System; - using log4net; +using log4net; - /// - /// An evaluator that triggers at a threshold level. - /// - /// - /// - /// This evaluator will trigger if the level of the event - /// passed to - /// is equal to or greater than the - /// level. - /// - /// - /// Nicko Cadell. - public class LevelEvaluator : ITriggeringEventEvaluator - { - /// - /// The threshold for triggering. - /// +namespace log4net.Core +{ + /// + /// An evaluator that triggers at a threshold level + /// + /// + /// + /// This evaluator will trigger if the level of the event + /// passed to + /// is equal to or greater than the + /// level. + /// + /// + /// Nicko Cadell + public class LevelEvaluator : ITriggeringEventEvaluator + { + /// + /// The threshold for triggering + /// private Level m_threshold; /// - /// Initializes a new instance of the class. - /// Create a new evaluator using the threshold. - /// - /// - /// - /// Create a new evaluator using the threshold. - /// - /// - /// This evaluator will trigger if the level of the event - /// passed to - /// is equal to or greater than the - /// level. - /// - /// - public LevelEvaluator() - : this(Level.Off) - { + /// Create a new evaluator using the threshold. + /// + /// + /// + /// Create a new evaluator using the threshold. + /// + /// + /// This evaluator will trigger if the level of the event + /// passed to + /// is equal to or greater than the + /// level. + /// + /// + public LevelEvaluator() : this(Level.Off) + { + } + + /// + /// Create a new evaluator using the specified threshold. + /// + /// the threshold to trigger at + /// + /// + /// Create a new evaluator using the specified threshold. + /// + /// + /// This evaluator will trigger if the level of the event + /// passed to + /// is equal to or greater than the + /// level. + /// + /// + public LevelEvaluator(Level threshold) + { + if (threshold == null) + { + throw new ArgumentNullException("threshold"); + } + + this.m_threshold = threshold; + } + + /// + /// the threshold to trigger at + /// + /// + /// The that will cause this evaluator to trigger + /// + /// + /// + /// This evaluator will trigger if the level of the event + /// passed to + /// is equal to or greater than the + /// level. + /// + /// + public Level Threshold + { + get { return this.m_threshold; } + set { this.m_threshold = value; } } /// - /// Initializes a new instance of the class. - /// Create a new evaluator using the specified threshold. - /// - /// the threshold to trigger at. - /// - /// - /// Create a new evaluator using the specified threshold. - /// - /// - /// This evaluator will trigger if the level of the event - /// passed to - /// is equal to or greater than the - /// level. - /// - /// - public LevelEvaluator(Level threshold) - { - if (threshold == null) - { - throw new ArgumentNullException("threshold"); - } - - this.m_threshold = threshold; - } - - /// - /// Gets or sets the threshold to trigger at. - /// - /// - /// The that will cause this evaluator to trigger. - /// - /// - /// - /// This evaluator will trigger if the level of the event - /// passed to - /// is equal to or greater than the - /// level. - /// - /// - public Level Threshold - { - get { return this.m_threshold; } - set { this.m_threshold = value; } - } - - /// - /// Is this the triggering event?. - /// - /// The event to check. - /// This method returns true, if the event level - /// is equal or higher than the . - /// Otherwise it returns false. - /// - /// - /// This evaluator will trigger if the level of the event - /// passed to - /// is equal to or greater than the - /// level. - /// - /// - public bool IsTriggeringEvent(LoggingEvent loggingEvent) - { - if (loggingEvent == null) - { - throw new ArgumentNullException("loggingEvent"); - } - - return loggingEvent.Level >= this.m_threshold; - } - } -} + /// Is this the triggering event? + /// + /// The event to check + /// This method returns true, if the event level + /// is equal or higher than the . + /// Otherwise it returns false + /// + /// + /// This evaluator will trigger if the level of the event + /// passed to + /// is equal to or greater than the + /// level. + /// + /// + public bool IsTriggeringEvent(LoggingEvent loggingEvent) + { + if (loggingEvent == null) + { + throw new ArgumentNullException("loggingEvent"); + } + + return (loggingEvent.Level >= this.m_threshold); + } + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Core/LevelMap.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Core/LevelMap.cs index ea96ab27dae..0832ffebe51 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Core/LevelMap.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Core/LevelMap.cs @@ -1,230 +1,226 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.Core -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; - using System.Collections; - using System.Collections.Specialized; +using System; +using System.Collections; +using System.Collections.Specialized; - using log4net.Util; +using log4net.Util; - /// - /// Mapping between string name and Level object. - /// - /// - /// - /// Mapping between string name and object. - /// This mapping is held separately for each . - /// The level name is case insensitive. - /// - /// - /// Nicko Cadell. - public sealed class LevelMap +namespace log4net.Core +{ + /// + /// Mapping between string name and Level object + /// + /// + /// + /// Mapping between string name and object. + /// This mapping is held separately for each . + /// The level name is case insensitive. + /// + /// + /// Nicko Cadell + public sealed class LevelMap { - /// - /// Mapping from level name to Level object. The - /// level name is case insensitive. - /// + /// + /// Mapping from level name to Level object. The + /// level name is case insensitive + /// private Hashtable m_mapName2Level = SystemInfo.CreateCaseInsensitiveHashtable(); /// - /// Initializes a new instance of the class. - /// Construct the level map. - /// - /// - /// - /// Construct the level map. - /// - /// - public LevelMap() - { - } - - /// - /// Clear the internal maps of all levels. - /// - /// - /// - /// Clear the internal maps of all levels. - /// - /// - public void Clear() - { - // Clear all current levels - this.m_mapName2Level.Clear(); - } - - /// - /// Lookup a by name. - /// - /// The name of the Level to lookup. - /// a Level from the map with the name specified. - /// - /// - /// Returns the from the - /// map with the name specified. If the no level is - /// found then null is returned. - /// - /// - public Level this[string name] - { - get - { - if (name == null) - { - throw new ArgumentNullException("name"); - } - - lock (this) - { - return (Level)this.m_mapName2Level[name]; - } - } - } - - /// - /// Create a new Level and add it to the map. - /// - /// the string to display for the Level. - /// the level value to give to the Level. - /// - /// - /// Create a new Level and add it to the map. - /// - /// - /// - public void Add(string name, int value) - { - this.Add(name, value, null); - } - - /// - /// Create a new Level and add it to the map. - /// - /// the string to display for the Level. - /// the level value to give to the Level. - /// the display name to give to the Level. - /// - /// - /// Create a new Level and add it to the map. - /// - /// - public void Add(string name, int value, string displayName) - { - if (name == null) - { - throw new ArgumentNullException("name"); - } + /// Construct the level map + /// + /// + /// + /// Construct the level map. + /// + /// + public LevelMap() + { + } + + /// + /// Clear the internal maps of all levels + /// + /// + /// + /// Clear the internal maps of all levels + /// + /// + public void Clear() + { + // Clear all current levels + this.m_mapName2Level.Clear(); + } + + /// + /// Lookup a by name + /// + /// The name of the Level to lookup + /// a Level from the map with the name specified + /// + /// + /// Returns the from the + /// map with the name specified. If the no level is + /// found then null is returned. + /// + /// + public Level this[string name] + { + get + { + if (name == null) + { + throw new ArgumentNullException("name"); + } + + lock(this) + { + return (Level)this.m_mapName2Level[name]; + } + } + } + + /// + /// Create a new Level and add it to the map + /// + /// the string to display for the Level + /// the level value to give to the Level + /// + /// + /// Create a new Level and add it to the map + /// + /// + /// + public void Add(string name, int value) + { + this.Add(name, value, null); + } - if (name.Length == 0) - { - throw log4net.Util.SystemInfo.CreateArgumentOutOfRangeException("name", name, "Parameter: name, Value: [" + name + "] out of range. Level name must not be empty"); - } - - if (displayName == null || displayName.Length == 0) - { - displayName = name; - } - - this.Add(new Level(value, name, displayName)); - } - - /// - /// Add a Level to the map. - /// - /// the Level to add. - /// - /// - /// Add a Level to the map. - /// - /// - public void Add(Level level) - { - if (level == null) - { - throw new ArgumentNullException("level"); - } + /// + /// Create a new Level and add it to the map + /// + /// the string to display for the Level + /// the level value to give to the Level + /// the display name to give to the Level + /// + /// + /// Create a new Level and add it to the map + /// + /// + public void Add(string name, int value, string displayName) + { + if (name == null) + { + throw new ArgumentNullException("name"); + } + if (name.Length == 0) + { + throw SystemInfo.CreateArgumentOutOfRangeException("name", name, "Parameter: name, Value: ["+name+"] out of range. Level name must not be empty"); + } + + if (displayName == null || displayName.Length == 0) + { + displayName = name; + } + + this.Add(new Level(value, name, displayName)); + } + + /// + /// Add a Level to the map + /// + /// the Level to add + /// + /// + /// Add a Level to the map + /// + /// + public void Add(Level level) + { + if (level == null) + { + throw new ArgumentNullException("level"); + } + lock(this) + { + this.m_mapName2Level[level.Name] = level; + } + } + + /// + /// Return all possible levels as a list of Level objects. + /// + /// all possible levels as a list of Level objects + /// + /// + /// Return all possible levels as a list of Level objects. + /// + /// + public LevelCollection AllLevels + { + get + { + lock(this) + { + return new LevelCollection(this.m_mapName2Level.Values); + } + } + } - lock (this) - { - this.m_mapName2Level[level.Name] = level; - } - } - - /// - /// Gets return all possible levels as a list of Level objects. - /// - /// all possible levels as a list of Level objects. - /// - /// - /// Return all possible levels as a list of Level objects. - /// - /// - public LevelCollection AllLevels - { - get - { - lock (this) - { - return new LevelCollection(this.m_mapName2Level.Values); - } - } - } - - /// - /// Lookup a named level from the map. - /// - /// the name of the level to lookup is taken from this level. - /// If the level is not set on the map then this level is added. - /// the level in the map with the name specified. - /// - /// - /// Lookup a named level from the map. The name of the level to lookup is taken - /// from the property of the - /// argument. - /// - /// - /// If no level with the specified name is found then the - /// argument is added to the level map - /// and returned. - /// - /// - public Level LookupWithDefault(Level defaultLevel) - { - if (defaultLevel == null) - { - throw new ArgumentNullException("defaultLevel"); - } - - lock (this) - { - Level level = (Level)this.m_mapName2Level[defaultLevel.Name]; - if (level == null) - { - this.m_mapName2Level[defaultLevel.Name] = defaultLevel; - return defaultLevel; - } + /// + /// Lookup a named level from the map + /// + /// the name of the level to lookup is taken from this level. + /// If the level is not set on the map then this level is added + /// the level in the map with the name specified + /// + /// + /// Lookup a named level from the map. The name of the level to lookup is taken + /// from the property of the + /// argument. + /// + /// + /// If no level with the specified name is found then the + /// argument is added to the level map + /// and returned. + /// + /// + public Level LookupWithDefault(Level defaultLevel) + { + if (defaultLevel == null) + { + throw new ArgumentNullException("defaultLevel"); + } - return level; - } - } - } -} + lock(this) + { + Level level = (Level)this.m_mapName2Level[defaultLevel.Name]; + if (level == null) + { + this.m_mapName2Level[defaultLevel.Name] = defaultLevel; + return defaultLevel; + } + return level; + } + } + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Core/LocationInfo.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Core/LocationInfo.cs index a8dcbd54241..b572113751f 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Core/LocationInfo.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Core/LocationInfo.cs @@ -1,309 +1,307 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.Core -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; - using System.Collections; - using System.Diagnostics; +using System; +#if !NETCF && !NETSTANDARD1_3 +using System.Collections; +using System.Diagnostics; - using log4net.Util; +using log4net.Util; +#endif - /// - /// The internal representation of caller location information. - /// - /// - /// - /// This class uses the System.Diagnostics.StackTrace class to generate - /// a call stack. The caller's information is then extracted from this stack. - /// - /// - /// The System.Diagnostics.StackTrace class is not supported on the - /// .NET Compact Framework 1.0 therefore caller location information is not - /// available on that framework. - /// - /// - /// The System.Diagnostics.StackTrace class has this to say about Release builds: - /// - /// - /// "StackTrace information will be most informative with Debug build configurations. - /// By default, Debug builds include debug symbols, while Release builds do not. The - /// debug symbols contain most of the file, method name, line number, and column - /// information used in constructing StackFrame and StackTrace objects. StackTrace - /// might not report as many method calls as expected, due to code transformations - /// that occur during optimization.". - /// - /// - /// This means that in a Release build the caller information may be incomplete or may - /// not exist at all! Therefore caller location information cannot be relied upon in a Release build. - /// - /// - /// Nicko Cadell. - /// Gert Driesen. -#if !NETCF - [Serializable] -#endif - public class LocationInfo +namespace log4net.Core +{ + /// + /// The internal representation of caller location information. + /// + /// + /// + /// This class uses the System.Diagnostics.StackTrace class to generate + /// a call stack. The caller's information is then extracted from this stack. + /// + /// + /// The System.Diagnostics.StackTrace class is not supported on the + /// .NET Compact Framework 1.0 therefore caller location information is not + /// available on that framework. + /// + /// + /// The System.Diagnostics.StackTrace class has this to say about Release builds: + /// + /// + /// "StackTrace information will be most informative with Debug build configurations. + /// By default, Debug builds include debug symbols, while Release builds do not. The + /// debug symbols contain most of the file, method name, line number, and column + /// information used in constructing StackFrame and StackTrace objects. StackTrace + /// might not report as many method calls as expected, due to code transformations + /// that occur during optimization." + /// + /// + /// This means that in a Release build the caller information may be incomplete or may + /// not exist at all! Therefore caller location information cannot be relied upon in a Release build. + /// + /// + /// Nicko Cadell + /// Gert Driesen +#if !NETCF + [Serializable] +#endif + public class LocationInfo { /// - /// Initializes a new instance of the class. - /// Constructor. - /// - /// The declaring type of the method that is - /// the stack boundary into the logging system for this call. - /// - /// - /// Initializes a new instance of the - /// class based on the current thread. - /// - /// - public LocationInfo(Type callerStackBoundaryDeclaringType) - { - // Initialize all fields - this.m_className = NA; - this.m_fileName = NA; - this.m_lineNumber = NA; - this.m_methodName = NA; - this.m_fullInfo = NA; - -#if !(NETCF || NETSTANDARD1_3) // StackTrace isn't fully implemented for NETSTANDARD1_3 https://github.com/dotnet/corefx/issues/1797 - if (callerStackBoundaryDeclaringType != null) - { - try - { - StackTrace st = new StackTrace(true); - int frameIndex = 0; - - // skip frames not from fqnOfCallingClass - while (frameIndex < st.FrameCount) - { - StackFrame frame = st.GetFrame(frameIndex); - if (frame != null && frame.GetMethod().DeclaringType == callerStackBoundaryDeclaringType) - { - break; - } + /// Constructor + /// + /// The declaring type of the method that is + /// the stack boundary into the logging system for this call. + /// + /// + /// Initializes a new instance of the + /// class based on the current thread. + /// + /// + public LocationInfo(Type callerStackBoundaryDeclaringType) + { + // Initialize all fields + this.m_className = NA; + this.m_fileName = NA; + this.m_lineNumber = NA; + this.m_methodName = NA; + this.m_fullInfo = NA; - frameIndex++; - } - - // skip frames from fqnOfCallingClass - while (frameIndex < st.FrameCount) - { - StackFrame frame = st.GetFrame(frameIndex); - if (frame != null && frame.GetMethod().DeclaringType != callerStackBoundaryDeclaringType) - { - break; - } +#if !NETCF && !NETSTANDARD1_3 // StackTrace isn't fully implemented for NETSTANDARD1_3 https://github.com/dotnet/corefx/issues/1797 + if (callerStackBoundaryDeclaringType != null) + { + try + { + StackTrace st = new StackTrace(true); + int frameIndex = 0; + + // skip frames not from fqnOfCallingClass + while (frameIndex < st.FrameCount) + { + StackFrame frame = st.GetFrame(frameIndex); + if (frame != null && frame.GetMethod().DeclaringType == callerStackBoundaryDeclaringType) + { + break; + } + frameIndex++; + } - frameIndex++; - } - - if (frameIndex < st.FrameCount) - { - // take into account the frames we skip above - int adjustedFrameCount = st.FrameCount - frameIndex; - ArrayList stackFramesList = new ArrayList(adjustedFrameCount); - this.m_stackFrames = new StackFrameItem[adjustedFrameCount]; - for (int i = frameIndex; i < st.FrameCount; i++) - { - stackFramesList.Add(new StackFrameItem(st.GetFrame(i))); - } - - stackFramesList.CopyTo(this.m_stackFrames, 0); - - // now frameIndex is the first 'user' caller frame - StackFrame locationFrame = st.GetFrame(frameIndex); - - if (locationFrame != null) - { - System.Reflection.MethodBase method = locationFrame.GetMethod(); - - if (method != null) - { - this.m_methodName = method.Name; - if (method.DeclaringType != null) - { - this.m_className = method.DeclaringType.FullName; - } - } + // skip frames from fqnOfCallingClass + while (frameIndex < st.FrameCount) + { + StackFrame frame = st.GetFrame(frameIndex); + if (frame != null && frame.GetMethod().DeclaringType != callerStackBoundaryDeclaringType) + { + break; + } + frameIndex++; + } - this.m_fileName = locationFrame.GetFileName(); - this.m_lineNumber = locationFrame.GetFileLineNumber().ToString(System.Globalization.NumberFormatInfo.InvariantInfo); - - // Combine all location info - this.m_fullInfo = this.m_className + '.' + this.m_methodName + '(' + this.m_fileName + ':' + this.m_lineNumber + ')'; - } - } - } - catch (System.Security.SecurityException) - { - // This security exception will occur if the caller does not have - // some undefined set of SecurityPermission flags. - LogLog.Debug(declaringType, "Security exception while trying to get caller stack frame. Error Ignored. Location Information Not Available."); - } - } -#endif + if (frameIndex < st.FrameCount) + { + // take into account the frames we skip above + int adjustedFrameCount = st.FrameCount - frameIndex; + ArrayList stackFramesList = new ArrayList(adjustedFrameCount); + this.m_stackFrames = new StackFrameItem[adjustedFrameCount]; + for (int i = frameIndex; i < st.FrameCount; i++) + { + stackFramesList.Add(new StackFrameItem(st.GetFrame(i))); + } + + stackFramesList.CopyTo(this.m_stackFrames, 0); + + // now frameIndex is the first 'user' caller frame + StackFrame locationFrame = st.GetFrame(frameIndex); + + if (locationFrame != null) + { + System.Reflection.MethodBase method = locationFrame.GetMethod(); + + if (method != null) + { + this.m_methodName = method.Name; + if (method.DeclaringType != null) + { + this.m_className = method.DeclaringType.FullName; + } + } + + this.m_fileName = locationFrame.GetFileName(); + this.m_lineNumber = locationFrame.GetFileLineNumber().ToString(System.Globalization.NumberFormatInfo.InvariantInfo); + + // Combine all location info + this.m_fullInfo = this.m_className + '.' + this.m_methodName + '(' + this.m_fileName + ':' + this.m_lineNumber + ')'; + } + } + } + catch(System.Security.SecurityException) + { + // This security exception will occur if the caller does not have + // some undefined set of SecurityPermission flags. + LogLog.Debug(declaringType, "Security exception while trying to get caller stack frame. Error Ignored. Location Information Not Available."); + } + } +#endif + } + + /// + /// Constructor + /// + /// The fully qualified class name. + /// The method name. + /// The file name. + /// The line number of the method within the file. + /// + /// + /// Initializes a new instance of the + /// class with the specified data. + /// + /// + public LocationInfo(string className, string methodName, string fileName, string lineNumber) + { + this.m_className = className; + this.m_fileName = fileName; + this.m_lineNumber = lineNumber; + this.m_methodName = methodName; + this.m_fullInfo = this.m_className + '.' + this.m_methodName + '(' + this.m_fileName + + ':' + this.m_lineNumber + ')'; + } + + /// + /// Gets the fully qualified class name of the caller making the logging + /// request. + /// + /// + /// The fully qualified class name of the caller making the logging + /// request. + /// + /// + /// + /// Gets the fully qualified class name of the caller making the logging + /// request. + /// + /// + public string ClassName + { + get { return this.m_className; } + } + + /// + /// Gets the file name of the caller. + /// + /// + /// The file name of the caller. + /// + /// + /// + /// Gets the file name of the caller. + /// + /// + public string FileName + { + get { return this.m_fileName; } } /// - /// Initializes a new instance of the class. - /// Constructor. - /// - /// The fully qualified class name. - /// The method name. - /// The file name. - /// The line number of the method within the file. - /// - /// - /// Initializes a new instance of the - /// class with the specified data. - /// - /// - public LocationInfo(string className, string methodName, string fileName, string lineNumber) - { - this.m_className = className; - this.m_fileName = fileName; - this.m_lineNumber = lineNumber; - this.m_methodName = methodName; - this.m_fullInfo = this.m_className + '.' + this.m_methodName + '(' + this.m_fileName + - ':' + this.m_lineNumber + ')'; + /// Gets the line number of the caller. + /// + /// + /// The line number of the caller. + /// + /// + /// + /// Gets the line number of the caller. + /// + /// + public string LineNumber + { + get { return this.m_lineNumber; } } - /// - /// Gets the fully qualified class name of the caller making the logging - /// request. - /// - /// - /// The fully qualified class name of the caller making the logging - /// request. - /// - /// - /// - /// Gets the fully qualified class name of the caller making the logging - /// request. - /// - /// - public string ClassName - { - get { return this.m_className; } - } - - /// - /// Gets the file name of the caller. - /// - /// - /// The file name of the caller. - /// - /// - /// - /// Gets the file name of the caller. - /// - /// - public string FileName - { - get { return this.m_fileName; } - } - - /// - /// Gets the line number of the caller. - /// - /// - /// The line number of the caller. - /// - /// - /// - /// Gets the line number of the caller. - /// - /// - public string LineNumber - { - get { return this.m_lineNumber; } - } - - /// - /// Gets the method name of the caller. - /// - /// - /// The method name of the caller. - /// - /// - /// - /// Gets the method name of the caller. - /// - /// - public string MethodName - { - get { return this.m_methodName; } - } - - /// - /// Gets all available caller information. - /// - /// - /// All available caller information, in the format - /// fully.qualified.classname.of.caller.methodName(Filename:line). - /// - /// - /// - /// Gets all available caller information, in the format - /// fully.qualified.classname.of.caller.methodName(Filename:line). - /// - /// - public string FullInfo - { - get { return this.m_fullInfo; } - } - -#if !(NETCF || NETSTANDARD1_3) - /// - /// Gets the stack frames from the stack trace of the caller making the log request. - /// - public StackFrameItem[] StackFrames - { - get { return this.m_stackFrames; } + /// + /// Gets the method name of the caller. + /// + /// + /// The method name of the caller. + /// + /// + /// + /// Gets the method name of the caller. + /// + /// + public string MethodName + { + get { return this.m_methodName; } } -#endif - private readonly string m_className; - private readonly string m_fileName; - private readonly string m_lineNumber; - private readonly string m_methodName; - private readonly string m_fullInfo; -#if !(NETCF || NETSTANDARD1_3) + /// + /// Gets all available caller information + /// + /// + /// All available caller information, in the format + /// fully.qualified.classname.of.caller.methodName(Filename:line) + /// + /// + /// + /// Gets all available caller information, in the format + /// fully.qualified.classname.of.caller.methodName(Filename:line) + /// + /// + public string FullInfo + { + get { return this.m_fullInfo; } + } + +#if !NETCF && !NETSTANDARD1_3 + /// + /// Gets the stack frames from the stack trace of the caller making the log request + /// + public StackFrameItem[] StackFrames + { + get { return this.m_stackFrames; } + } +#endif + + private readonly string m_className; + private readonly string m_fileName; + private readonly string m_lineNumber; + private readonly string m_methodName; + private readonly string m_fullInfo; +#if !NETCF && !NETSTANDARD1_3 private readonly StackFrameItem[] m_stackFrames; -#endif +#endif - /// - /// The fully qualified type of the LocationInfo class. - /// - /// - /// Used by the internal logger to record the Type of the - /// log message. - /// - private static readonly Type declaringType = typeof(LocationInfo); - - /// - /// When location information is not available the constant - /// NA is returned. Current value of this string - /// constant is ?. - /// + /// + /// The fully qualified type of the LocationInfo class. + /// + /// + /// Used by the internal logger to record the Type of the + /// log message. + /// + private static readonly Type declaringType = typeof(LocationInfo); + + /// + /// When location information is not available the constant + /// NA is returned. Current value of this string + /// constant is ?. + /// private const string NA = "?"; - } -} + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Core/LogException.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Core/LogException.cs index 9434a383bf1..c4c5552e46c 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Core/LogException.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Core/LogException.cs @@ -1,117 +1,107 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -#if !NETCF -using System.Runtime.Serialization; +using System; +#if !NETCF && !NETSTANDARD1_3 +using System.Runtime.Serialization; +#endif -#endif - -namespace log4net.Core -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; - - /// - /// Exception base type for log4net. - /// - /// - /// - /// This type extends . It - /// does not add any new functionality but does differentiate the - /// type of exception being thrown. - /// - /// - /// Nicko Cadell. - /// Gert Driesen. -#if !NETCF - [Serializable] -#endif -#if NETSTANDARD1_3 - public class LogException : Exception -#else - public class LogException : ApplicationException -#endif +namespace log4net.Core +{ + /// + /// Exception base type for log4net. + /// + /// + /// + /// This type extends . It + /// does not add any new functionality but does differentiate the + /// type of exception being thrown. + /// + /// + /// Nicko Cadell + /// Gert Driesen +#if !NETCF + [Serializable] +#endif +#if NETSTANDARD1_3 + public class LogException : Exception +#else + public class LogException : ApplicationException +#endif { /// - /// Initializes a new instance of the class. - /// Constructor. - /// - /// - /// - /// Initializes a new instance of the class. - /// - /// - public LogException() - { + /// Constructor + /// + /// + /// + /// Initializes a new instance of the class. + /// + /// + public LogException() + { } /// - /// Initializes a new instance of the class. - /// Constructor. - /// - /// A message to include with the exception. - /// - /// - /// Initializes a new instance of the class with - /// the specified message. - /// - /// - public LogException(string message) - : base(message) - { + /// Constructor + /// + /// A message to include with the exception. + /// + /// + /// Initializes a new instance of the class with + /// the specified message. + /// + /// + public LogException(String message) : base(message) + { } - + /// - /// Initializes a new instance of the class. - /// Constructor. - /// - /// A message to include with the exception. - /// A nested exception to include. - /// - /// - /// Initializes a new instance of the class - /// with the specified message and inner exception. - /// - /// - public LogException(string message, Exception innerException) - : base(message, innerException) - { + /// Constructor + /// + /// A message to include with the exception. + /// A nested exception to include. + /// + /// + /// Initializes a new instance of the class + /// with the specified message and inner exception. + /// + /// + public LogException(String message, Exception innerException) : base(message, innerException) + { } -#if !(NETCF || NETSTANDARD1_3) +#if !NETCF && !NETSTANDARD1_3 /// - /// Initializes a new instance of the class. - /// Serialization constructor. - /// - /// The that holds the serialized object data about the exception being thrown. - /// The that contains contextual information about the source or destination. - /// - /// - /// Initializes a new instance of the class - /// with serialized data. - /// - /// - protected LogException(SerializationInfo info, StreamingContext context) - : base(info, context) - { + /// Serialization constructor + /// + /// The that holds the serialized object data about the exception being thrown. + /// The that contains contextual information about the source or destination. + /// + /// + /// Initializes a new instance of the class + /// with serialized data. + /// + /// + protected LogException(SerializationInfo info, StreamingContext context) : base(info, context) + { } -#endif - - } -} +#endif + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Core/LogImpl.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Core/LogImpl.cs index 948db835892..d0941adad2c 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Core/LogImpl.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Core/LogImpl.cs @@ -1,1278 +1,1277 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.Core -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; - using System.Globalization; +using System; +using System.Globalization; - using log4net.Repository; - using log4net.Util; +using log4net.Repository; +using log4net.Util; - /// - /// Implementation of wrapper interface. - /// - /// - /// - /// This implementation of the interface - /// forwards to the held by the base class. - /// - /// - /// This logger has methods to allow the caller to log at the following - /// levels: - /// - /// - /// - /// DEBUG - /// - /// The and methods log messages - /// at the DEBUG level. That is the level with that name defined in the - /// repositories . The default value - /// for this level is . The - /// property tests if this level is enabled for logging. - /// - /// - /// - /// INFO - /// - /// The and methods log messages - /// at the INFO level. That is the level with that name defined in the - /// repositories . The default value - /// for this level is . The - /// property tests if this level is enabled for logging. - /// - /// - /// - /// WARN - /// - /// The and methods log messages - /// at the WARN level. That is the level with that name defined in the - /// repositories . The default value - /// for this level is . The - /// property tests if this level is enabled for logging. - /// - /// - /// - /// ERROR - /// - /// The and methods log messages - /// at the ERROR level. That is the level with that name defined in the - /// repositories . The default value - /// for this level is . The - /// property tests if this level is enabled for logging. - /// - /// - /// - /// FATAL - /// - /// The and methods log messages - /// at the FATAL level. That is the level with that name defined in the - /// repositories . The default value - /// for this level is . The - /// property tests if this level is enabled for logging. - /// - /// - /// - /// - /// The values for these levels and their semantic meanings can be changed by - /// configuring the for the repository. - /// - /// - /// Nicko Cadell. - /// Gert Driesen. - public class LogImpl : LoggerWrapperImpl, ILog +namespace log4net.Core +{ + /// + /// Implementation of wrapper interface. + /// + /// + /// + /// This implementation of the interface + /// forwards to the held by the base class. + /// + /// + /// This logger has methods to allow the caller to log at the following + /// levels: + /// + /// + /// + /// DEBUG + /// + /// The and methods log messages + /// at the DEBUG level. That is the level with that name defined in the + /// repositories . The default value + /// for this level is . The + /// property tests if this level is enabled for logging. + /// + /// + /// + /// INFO + /// + /// The and methods log messages + /// at the INFO level. That is the level with that name defined in the + /// repositories . The default value + /// for this level is . The + /// property tests if this level is enabled for logging. + /// + /// + /// + /// WARN + /// + /// The and methods log messages + /// at the WARN level. That is the level with that name defined in the + /// repositories . The default value + /// for this level is . The + /// property tests if this level is enabled for logging. + /// + /// + /// + /// ERROR + /// + /// The and methods log messages + /// at the ERROR level. That is the level with that name defined in the + /// repositories . The default value + /// for this level is . The + /// property tests if this level is enabled for logging. + /// + /// + /// + /// FATAL + /// + /// The and methods log messages + /// at the FATAL level. That is the level with that name defined in the + /// repositories . The default value + /// for this level is . The + /// property tests if this level is enabled for logging. + /// + /// + /// + /// + /// The values for these levels and their semantic meanings can be changed by + /// configuring the for the repository. + /// + /// + /// Nicko Cadell + /// Gert Driesen + public class LogImpl : LoggerWrapperImpl, ILog { /// - /// Initializes a new instance of the class. - /// Construct a new wrapper for the specified logger. - /// - /// The logger to wrap. - /// - /// - /// Construct a new wrapper for the specified logger. - /// - /// - public LogImpl(ILogger logger) - : base(logger) - { - // Listen for changes to the repository - logger.Repository.ConfigurationChanged += new LoggerRepositoryConfigurationChangedEventHandler(this.LoggerRepositoryConfigurationChanged); - - // load the current levels - this.ReloadLevels(logger.Repository); + /// Construct a new wrapper for the specified logger. + /// + /// The logger to wrap. + /// + /// + /// Construct a new wrapper for the specified logger. + /// + /// + public LogImpl(ILogger logger) : base(logger) + { + // Listen for changes to the repository + logger.Repository.ConfigurationChanged += new LoggerRepositoryConfigurationChangedEventHandler(this.LoggerRepositoryConfigurationChanged); + + // load the current levels + this.ReloadLevels(logger.Repository); + } + + /// + /// Virtual method called when the configuration of the repository changes + /// + /// the repository holding the levels + /// + /// + /// Virtual method called when the configuration of the repository changes + /// + /// + protected virtual void ReloadLevels(ILoggerRepository repository) + { + LevelMap levelMap = repository.LevelMap; + + this.m_levelDebug = levelMap.LookupWithDefault(Level.Debug); + this.m_levelInfo = levelMap.LookupWithDefault(Level.Info); + this.m_levelWarn = levelMap.LookupWithDefault(Level.Warn); + this.m_levelError = levelMap.LookupWithDefault(Level.Error); + this.m_levelFatal = levelMap.LookupWithDefault(Level.Fatal); + } + + /// + /// Logs a message object with the DEBUG level. + /// + /// The message object to log. + /// + /// + /// This method first checks if this logger is DEBUG + /// enabled by comparing the level of this logger with the + /// DEBUG level. If this logger is + /// DEBUG enabled, then it converts the message object + /// (passed as parameter) to a string by invoking the appropriate + /// . It then + /// proceeds to call all the registered appenders in this logger + /// and also higher in the hierarchy depending on the value of the + /// additivity flag. + /// + /// + /// WARNING Note that passing an + /// to this method will print the name of the + /// but no stack trace. To print a stack trace use the + /// form instead. + /// + /// + public virtual void Debug(object message) + { + this.Logger.Log(ThisDeclaringType, this.m_levelDebug, message, null); + } + + /// + /// Logs a message object with the DEBUG level + /// + /// The message object to log. + /// The exception to log, including its stack trace. + /// + /// + /// Logs a message object with the DEBUG level including + /// the stack trace of the passed + /// as a parameter. + /// + /// + /// See the form for more detailed information. + /// + /// + /// + public virtual void Debug(object message, Exception exception) + { + this.Logger.Log(ThisDeclaringType, this.m_levelDebug, message, exception); + } + + /// + /// Logs a formatted message string with the DEBUG level. + /// + /// A String containing zero or more format items + /// An Object array containing zero or more objects to format + /// + /// + /// The message is formatted using the method. See + /// String.Format for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// The string is formatted using the + /// format provider. To specify a localized provider use the + /// method. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + public virtual void DebugFormat(string format, params object[] args) + { + if (this.IsDebugEnabled) + { + this.Logger.Log(ThisDeclaringType, this.m_levelDebug, new SystemStringFormat(CultureInfo.InvariantCulture, format, args), null); + } + } + + /// + /// Logs a formatted message string with the DEBUG level. + /// + /// A String containing zero or more format items + /// An Object to format + /// + /// + /// The message is formatted using the method. See + /// String.Format for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// The string is formatted using the + /// format provider. To specify a localized provider use the + /// method. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + public virtual void DebugFormat(string format, object arg0) + { + if (this.IsDebugEnabled) + { + this.Logger.Log(ThisDeclaringType, this.m_levelDebug, new SystemStringFormat(CultureInfo.InvariantCulture, format, new object[] { arg0 }), null); + } + } + + /// + /// Logs a formatted message string with the DEBUG level. + /// + /// A String containing zero or more format items + /// An Object to format + /// An Object to format + /// + /// + /// The message is formatted using the method. See + /// String.Format for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// The string is formatted using the + /// format provider. To specify a localized provider use the + /// method. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + public virtual void DebugFormat(string format, object arg0, object arg1) + { + if (this.IsDebugEnabled) + { + this.Logger.Log(ThisDeclaringType, this.m_levelDebug, new SystemStringFormat(CultureInfo.InvariantCulture, format, new object[] { arg0, arg1 }), null); + } + } + + /// + /// Logs a formatted message string with the DEBUG level. + /// + /// A String containing zero or more format items + /// An Object to format + /// An Object to format + /// An Object to format + /// + /// + /// The message is formatted using the method. See + /// String.Format for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// The string is formatted using the + /// format provider. To specify a localized provider use the + /// method. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + public virtual void DebugFormat(string format, object arg0, object arg1, object arg2) + { + if (this.IsDebugEnabled) + { + this.Logger.Log(ThisDeclaringType, this.m_levelDebug, new SystemStringFormat(CultureInfo.InvariantCulture, format, new object[] { arg0, arg1, arg2 }), null); + } + } + + /// + /// Logs a formatted message string with the DEBUG level. + /// + /// An that supplies culture-specific formatting information + /// A String containing zero or more format items + /// An Object array containing zero or more objects to format + /// + /// + /// The message is formatted using the method. See + /// String.Format for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + public virtual void DebugFormat(IFormatProvider provider, string format, params object[] args) + { + if (this.IsDebugEnabled) + { + this.Logger.Log(ThisDeclaringType, this.m_levelDebug, new SystemStringFormat(provider, format, args), null); + } + } + + /// + /// Logs a message object with the INFO level. + /// + /// The message object to log. + /// + /// + /// This method first checks if this logger is INFO + /// enabled by comparing the level of this logger with the + /// INFO level. If this logger is + /// INFO enabled, then it converts the message object + /// (passed as parameter) to a string by invoking the appropriate + /// . It then + /// proceeds to call all the registered appenders in this logger + /// and also higher in the hierarchy depending on the value of + /// the additivity flag. + /// + /// + /// WARNING Note that passing an + /// to this method will print the name of the + /// but no stack trace. To print a stack trace use the + /// form instead. + /// + /// + public virtual void Info(object message) + { + this.Logger.Log(ThisDeclaringType, this.m_levelInfo, message, null); + } + + /// + /// Logs a message object with the INFO level. + /// + /// The message object to log. + /// The exception to log, including its stack trace. + /// + /// + /// Logs a message object with the INFO level including + /// the stack trace of the + /// passed as a parameter. + /// + /// + /// See the form for more detailed information. + /// + /// + /// + public virtual void Info(object message, Exception exception) + { + this.Logger.Log(ThisDeclaringType, this.m_levelInfo, message, exception); + } + + /// + /// Logs a formatted message string with the INFO level. + /// + /// A String containing zero or more format items + /// An Object array containing zero or more objects to format + /// + /// + /// The message is formatted using the method. See + /// String.Format for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// The string is formatted using the + /// format provider. To specify a localized provider use the + /// method. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + public virtual void InfoFormat(string format, params object[] args) + { + if (this.IsInfoEnabled) + { + this.Logger.Log(ThisDeclaringType, this.m_levelInfo, new SystemStringFormat(CultureInfo.InvariantCulture, format, args), null); + } + } + + /// + /// Logs a formatted message string with the INFO level. + /// + /// A String containing zero or more format items + /// An Object to format + /// + /// + /// The message is formatted using the method. See + /// String.Format for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// The string is formatted using the + /// format provider. To specify a localized provider use the + /// method. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + public virtual void InfoFormat(string format, object arg0) + { + if (this.IsInfoEnabled) + { + this.Logger.Log(ThisDeclaringType, this.m_levelInfo, new SystemStringFormat(CultureInfo.InvariantCulture, format, new object[] { arg0 }), null); + } + } + + /// + /// Logs a formatted message string with the INFO level. + /// + /// A String containing zero or more format items + /// An Object to format + /// An Object to format + /// + /// + /// The message is formatted using the method. See + /// String.Format for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// The string is formatted using the + /// format provider. To specify a localized provider use the + /// method. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + public virtual void InfoFormat(string format, object arg0, object arg1) + { + if (this.IsInfoEnabled) + { + this.Logger.Log(ThisDeclaringType, this.m_levelInfo, new SystemStringFormat(CultureInfo.InvariantCulture, format, new object[] { arg0, arg1 }), null); + } + } + + /// + /// Logs a formatted message string with the INFO level. + /// + /// A String containing zero or more format items + /// An Object to format + /// An Object to format + /// An Object to format + /// + /// + /// The message is formatted using the method. See + /// String.Format for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// The string is formatted using the + /// format provider. To specify a localized provider use the + /// method. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + public virtual void InfoFormat(string format, object arg0, object arg1, object arg2) + { + if (this.IsInfoEnabled) + { + this.Logger.Log(ThisDeclaringType, this.m_levelInfo, new SystemStringFormat(CultureInfo.InvariantCulture, format, new object[] { arg0, arg1, arg2 }), null); + } + } + + /// + /// Logs a formatted message string with the INFO level. + /// + /// An that supplies culture-specific formatting information + /// A String containing zero or more format items + /// An Object array containing zero or more objects to format + /// + /// + /// The message is formatted using the method. See + /// String.Format for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + public virtual void InfoFormat(IFormatProvider provider, string format, params object[] args) + { + if (this.IsInfoEnabled) + { + this.Logger.Log(ThisDeclaringType, this.m_levelInfo, new SystemStringFormat(provider, format, args), null); + } + } + + /// + /// Logs a message object with the WARN level. + /// + /// the message object to log + /// + /// + /// This method first checks if this logger is WARN + /// enabled by comparing the level of this logger with the + /// WARN level. If this logger is + /// WARN enabled, then it converts the message object + /// (passed as parameter) to a string by invoking the appropriate + /// . It then + /// proceeds to call all the registered appenders in this logger and + /// also higher in the hierarchy depending on the value of the + /// additivity flag. + /// + /// + /// WARNING Note that passing an to this + /// method will print the name of the but no + /// stack trace. To print a stack trace use the + /// form instead. + /// + /// + public virtual void Warn(object message) + { + this.Logger.Log(ThisDeclaringType, this.m_levelWarn, message, null); + } + + /// + /// Logs a message object with the WARN level + /// + /// The message object to log. + /// The exception to log, including its stack trace. + /// + /// + /// Logs a message object with the WARN level including + /// the stack trace of the + /// passed as a parameter. + /// + /// + /// See the form for more detailed information. + /// + /// + /// + public virtual void Warn(object message, Exception exception) + { + this.Logger.Log(ThisDeclaringType, this.m_levelWarn, message, exception); + } + + /// + /// Logs a formatted message string with the WARN level. + /// + /// A String containing zero or more format items + /// An Object array containing zero or more objects to format + /// + /// + /// The message is formatted using the method. See + /// String.Format for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// The string is formatted using the + /// format provider. To specify a localized provider use the + /// method. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + public virtual void WarnFormat(string format, params object[] args) + { + if (this.IsWarnEnabled) + { + this.Logger.Log(ThisDeclaringType, this.m_levelWarn, new SystemStringFormat(CultureInfo.InvariantCulture, format, args), null); + } + } + + /// + /// Logs a formatted message string with the WARN level. + /// + /// A String containing zero or more format items + /// An Object to format + /// + /// + /// The message is formatted using the method. See + /// String.Format for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// The string is formatted using the + /// format provider. To specify a localized provider use the + /// method. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + public virtual void WarnFormat(string format, object arg0) + { + if (this.IsWarnEnabled) + { + this.Logger.Log(ThisDeclaringType, this.m_levelWarn, new SystemStringFormat(CultureInfo.InvariantCulture, format, new object[] { arg0 }), null); + } + } + + /// + /// Logs a formatted message string with the WARN level. + /// + /// A String containing zero or more format items + /// An Object to format + /// An Object to format + /// + /// + /// The message is formatted using the method. See + /// String.Format for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// The string is formatted using the + /// format provider. To specify a localized provider use the + /// method. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + public virtual void WarnFormat(string format, object arg0, object arg1) + { + if (this.IsWarnEnabled) + { + this.Logger.Log(ThisDeclaringType, this.m_levelWarn, new SystemStringFormat(CultureInfo.InvariantCulture, format, new object[] { arg0, arg1 }), null); + } } - /// - /// Virtual method called when the configuration of the repository changes. - /// - /// the repository holding the levels. - /// - /// - /// Virtual method called when the configuration of the repository changes. - /// - /// - protected virtual void ReloadLevels(ILoggerRepository repository) - { - LevelMap levelMap = repository.LevelMap; - - this.m_levelDebug = levelMap.LookupWithDefault(Level.Debug); - this.m_levelInfo = levelMap.LookupWithDefault(Level.Info); - this.m_levelWarn = levelMap.LookupWithDefault(Level.Warn); - this.m_levelError = levelMap.LookupWithDefault(Level.Error); - this.m_levelFatal = levelMap.LookupWithDefault(Level.Fatal); + /// + /// Logs a formatted message string with the WARN level. + /// + /// A String containing zero or more format items + /// An Object to format + /// An Object to format + /// An Object to format + /// + /// + /// The message is formatted using the method. See + /// String.Format for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// The string is formatted using the + /// format provider. To specify a localized provider use the + /// method. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + public virtual void WarnFormat(string format, object arg0, object arg1, object arg2) + { + if (this.IsWarnEnabled) + { + this.Logger.Log(ThisDeclaringType, this.m_levelWarn, new SystemStringFormat(CultureInfo.InvariantCulture, format, new object[] { arg0, arg1, arg2 }), null); + } + } + + /// + /// Logs a formatted message string with the WARN level. + /// + /// An that supplies culture-specific formatting information + /// A String containing zero or more format items + /// An Object array containing zero or more objects to format + /// + /// + /// The message is formatted using the method. See + /// String.Format for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + public virtual void WarnFormat(IFormatProvider provider, string format, params object[] args) + { + if (this.IsWarnEnabled) + { + this.Logger.Log(ThisDeclaringType, this.m_levelWarn, new SystemStringFormat(provider, format, args), null); + } + } + + /// + /// Logs a message object with the ERROR level. + /// + /// The message object to log. + /// + /// + /// This method first checks if this logger is ERROR + /// enabled by comparing the level of this logger with the + /// ERROR level. If this logger is + /// ERROR enabled, then it converts the message object + /// (passed as parameter) to a string by invoking the appropriate + /// . It then + /// proceeds to call all the registered appenders in this logger and + /// also higher in the hierarchy depending on the value of the + /// additivity flag. + /// + /// + /// WARNING Note that passing an to this + /// method will print the name of the but no + /// stack trace. To print a stack trace use the + /// form instead. + /// + /// + public virtual void Error(object message) + { + this.Logger.Log(ThisDeclaringType, this.m_levelError, message, null); + } + + /// + /// Logs a message object with the ERROR level + /// + /// The message object to log. + /// The exception to log, including its stack trace. + /// + /// + /// Logs a message object with the ERROR level including + /// the stack trace of the + /// passed as a parameter. + /// + /// + /// See the form for more detailed information. + /// + /// + /// + public virtual void Error(object message, Exception exception) + { + this.Logger.Log(ThisDeclaringType, this.m_levelError, message, exception); + } + + /// + /// Logs a formatted message string with the ERROR level. + /// + /// A String containing zero or more format items + /// An Object array containing zero or more objects to format + /// + /// + /// The message is formatted using the method. See + /// String.Format for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// The string is formatted using the + /// format provider. To specify a localized provider use the + /// method. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + public virtual void ErrorFormat(string format, params object[] args) + { + if (this.IsErrorEnabled) + { + this.Logger.Log(ThisDeclaringType, this.m_levelError, new SystemStringFormat(CultureInfo.InvariantCulture, format, args), null); + } + } + + /// + /// Logs a formatted message string with the ERROR level. + /// + /// A String containing zero or more format items + /// An Object to format + /// + /// + /// The message is formatted using the method. See + /// String.Format for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// The string is formatted using the + /// format provider. To specify a localized provider use the + /// method. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + public virtual void ErrorFormat(string format, object arg0) + { + if (this.IsErrorEnabled) + { + this.Logger.Log(ThisDeclaringType, this.m_levelError, new SystemStringFormat(CultureInfo.InvariantCulture, format, new object[] { arg0 }), null); + } + } + + /// + /// Logs a formatted message string with the ERROR level. + /// + /// A String containing zero or more format items + /// An Object to format + /// An Object to format + /// + /// + /// The message is formatted using the method. See + /// String.Format for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// The string is formatted using the + /// format provider. To specify a localized provider use the + /// method. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + public virtual void ErrorFormat(string format, object arg0, object arg1) + { + if (this.IsErrorEnabled) + { + this.Logger.Log(ThisDeclaringType, this.m_levelError, new SystemStringFormat(CultureInfo.InvariantCulture, format, new object[] { arg0, arg1 }), null); + } + } + + /// + /// Logs a formatted message string with the ERROR level. + /// + /// A String containing zero or more format items + /// An Object to format + /// An Object to format + /// An Object to format + /// + /// + /// The message is formatted using the method. See + /// String.Format for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// The string is formatted using the + /// format provider. To specify a localized provider use the + /// method. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + public virtual void ErrorFormat(string format, object arg0, object arg1, object arg2) + { + if (this.IsErrorEnabled) + { + this.Logger.Log(ThisDeclaringType, this.m_levelError, new SystemStringFormat(CultureInfo.InvariantCulture, format, new object[] { arg0, arg1, arg2 }), null); + } + } + + /// + /// Logs a formatted message string with the ERROR level. + /// + /// An that supplies culture-specific formatting information + /// A String containing zero or more format items + /// An Object array containing zero or more objects to format + /// + /// + /// The message is formatted using the method. See + /// String.Format for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + public virtual void ErrorFormat(IFormatProvider provider, string format, params object[] args) + { + if (this.IsErrorEnabled) + { + this.Logger.Log(ThisDeclaringType, this.m_levelError, new SystemStringFormat(provider, format, args), null); + } + } + + /// + /// Logs a message object with the FATAL level. + /// + /// The message object to log. + /// + /// + /// This method first checks if this logger is FATAL + /// enabled by comparing the level of this logger with the + /// FATAL level. If this logger is + /// FATAL enabled, then it converts the message object + /// (passed as parameter) to a string by invoking the appropriate + /// . It then + /// proceeds to call all the registered appenders in this logger and + /// also higher in the hierarchy depending on the value of the + /// additivity flag. + /// + /// + /// WARNING Note that passing an to this + /// method will print the name of the but no + /// stack trace. To print a stack trace use the + /// form instead. + /// + /// + public virtual void Fatal(object message) + { + this.Logger.Log(ThisDeclaringType, this.m_levelFatal, message, null); + } + + /// + /// Logs a message object with the FATAL level + /// + /// The message object to log. + /// The exception to log, including its stack trace. + /// + /// + /// Logs a message object with the FATAL level including + /// the stack trace of the + /// passed as a parameter. + /// + /// + /// See the form for more detailed information. + /// + /// + /// + public virtual void Fatal(object message, Exception exception) + { + this.Logger.Log(ThisDeclaringType, this.m_levelFatal, message, exception); } - /// - /// Logs a message object with the DEBUG level. - /// - /// The message object to log. - /// - /// - /// This method first checks if this logger is DEBUG - /// enabled by comparing the level of this logger with the - /// DEBUG level. If this logger is - /// DEBUG enabled, then it converts the message object - /// (passed as parameter) to a string by invoking the appropriate - /// . It then - /// proceeds to call all the registered appenders in this logger - /// and also higher in the hierarchy depending on the value of the - /// additivity flag. - /// - /// - /// WARNING Note that passing an - /// to this method will print the name of the - /// but no stack trace. To print a stack trace use the - /// form instead. - /// - /// - public virtual void Debug(object message) - { - this.Logger.Log(ThisDeclaringType, this.m_levelDebug, message, null); - } - - /// - /// Logs a message object with the DEBUG level. - /// - /// The message object to log. - /// The exception to log, including its stack trace. - /// - /// - /// Logs a message object with the DEBUG level including - /// the stack trace of the passed - /// as a parameter. - /// - /// - /// See the form for more detailed information. - /// - /// - /// - public virtual void Debug(object message, Exception exception) - { - this.Logger.Log(ThisDeclaringType, this.m_levelDebug, message, exception); - } - - /// - /// Logs a formatted message string with the DEBUG level. - /// - /// A String containing zero or more format items. - /// An Object array containing zero or more objects to format. - /// - /// - /// The message is formatted using the method. See - /// String.Format for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// The string is formatted using the - /// format provider. To specify a localized provider use the - /// method. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - public virtual void DebugFormat(string format, params object[] args) - { - if (this.IsDebugEnabled) - { - this.Logger.Log(ThisDeclaringType, this.m_levelDebug, new SystemStringFormat(CultureInfo.InvariantCulture, format, args), null); - } - } - - /// - /// Logs a formatted message string with the DEBUG level. - /// - /// A String containing zero or more format items. - /// An Object to format. - /// - /// - /// The message is formatted using the method. See - /// String.Format for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// The string is formatted using the - /// format provider. To specify a localized provider use the - /// method. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - public virtual void DebugFormat(string format, object arg0) - { - if (this.IsDebugEnabled) - { - this.Logger.Log(ThisDeclaringType, this.m_levelDebug, new SystemStringFormat(CultureInfo.InvariantCulture, format, new object[] { arg0 }), null); - } - } - - /// - /// Logs a formatted message string with the DEBUG level. - /// - /// A String containing zero or more format items. - /// An Object to format. - /// An Object to format. - /// - /// - /// The message is formatted using the method. See - /// String.Format for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// The string is formatted using the - /// format provider. To specify a localized provider use the - /// method. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - public virtual void DebugFormat(string format, object arg0, object arg1) - { - if (this.IsDebugEnabled) - { - this.Logger.Log(ThisDeclaringType, this.m_levelDebug, new SystemStringFormat(CultureInfo.InvariantCulture, format, new object[] { arg0, arg1 }), null); - } - } - - /// - /// Logs a formatted message string with the DEBUG level. - /// - /// A String containing zero or more format items. - /// An Object to format. - /// An Object to format. - /// An Object to format. - /// - /// - /// The message is formatted using the method. See - /// String.Format for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// The string is formatted using the - /// format provider. To specify a localized provider use the - /// method. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - public virtual void DebugFormat(string format, object arg0, object arg1, object arg2) - { - if (this.IsDebugEnabled) - { - this.Logger.Log(ThisDeclaringType, this.m_levelDebug, new SystemStringFormat(CultureInfo.InvariantCulture, format, new object[] { arg0, arg1, arg2 }), null); - } - } - - /// - /// Logs a formatted message string with the DEBUG level. - /// - /// An that supplies culture-specific formatting information. - /// A String containing zero or more format items. - /// An Object array containing zero or more objects to format. - /// - /// - /// The message is formatted using the method. See - /// String.Format for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - public virtual void DebugFormat(IFormatProvider provider, string format, params object[] args) - { - if (this.IsDebugEnabled) - { - this.Logger.Log(ThisDeclaringType, this.m_levelDebug, new SystemStringFormat(provider, format, args), null); - } - } - - /// - /// Logs a message object with the INFO level. - /// - /// The message object to log. - /// - /// - /// This method first checks if this logger is INFO - /// enabled by comparing the level of this logger with the - /// INFO level. If this logger is - /// INFO enabled, then it converts the message object - /// (passed as parameter) to a string by invoking the appropriate - /// . It then - /// proceeds to call all the registered appenders in this logger - /// and also higher in the hierarchy depending on the value of - /// the additivity flag. - /// - /// - /// WARNING Note that passing an - /// to this method will print the name of the - /// but no stack trace. To print a stack trace use the - /// form instead. - /// - /// - public virtual void Info(object message) - { - this.Logger.Log(ThisDeclaringType, this.m_levelInfo, message, null); - } - - /// - /// Logs a message object with the INFO level. - /// - /// The message object to log. - /// The exception to log, including its stack trace. - /// - /// - /// Logs a message object with the INFO level including - /// the stack trace of the - /// passed as a parameter. - /// - /// - /// See the form for more detailed information. - /// - /// - /// - public virtual void Info(object message, Exception exception) - { - this.Logger.Log(ThisDeclaringType, this.m_levelInfo, message, exception); - } - - /// - /// Logs a formatted message string with the INFO level. - /// - /// A String containing zero or more format items. - /// An Object array containing zero or more objects to format. - /// - /// - /// The message is formatted using the method. See - /// String.Format for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// The string is formatted using the - /// format provider. To specify a localized provider use the - /// method. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - public virtual void InfoFormat(string format, params object[] args) - { - if (this.IsInfoEnabled) - { - this.Logger.Log(ThisDeclaringType, this.m_levelInfo, new SystemStringFormat(CultureInfo.InvariantCulture, format, args), null); - } - } - - /// - /// Logs a formatted message string with the INFO level. - /// - /// A String containing zero or more format items. - /// An Object to format. - /// - /// - /// The message is formatted using the method. See - /// String.Format for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// The string is formatted using the - /// format provider. To specify a localized provider use the - /// method. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - public virtual void InfoFormat(string format, object arg0) - { - if (this.IsInfoEnabled) - { - this.Logger.Log(ThisDeclaringType, this.m_levelInfo, new SystemStringFormat(CultureInfo.InvariantCulture, format, new object[] { arg0 }), null); - } - } - - /// - /// Logs a formatted message string with the INFO level. - /// - /// A String containing zero or more format items. - /// An Object to format. - /// An Object to format. - /// - /// - /// The message is formatted using the method. See - /// String.Format for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// The string is formatted using the - /// format provider. To specify a localized provider use the - /// method. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - public virtual void InfoFormat(string format, object arg0, object arg1) - { - if (this.IsInfoEnabled) - { - this.Logger.Log(ThisDeclaringType, this.m_levelInfo, new SystemStringFormat(CultureInfo.InvariantCulture, format, new object[] { arg0, arg1 }), null); - } - } - - /// - /// Logs a formatted message string with the INFO level. - /// - /// A String containing zero or more format items. - /// An Object to format. - /// An Object to format. - /// An Object to format. - /// - /// - /// The message is formatted using the method. See - /// String.Format for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// The string is formatted using the - /// format provider. To specify a localized provider use the - /// method. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - public virtual void InfoFormat(string format, object arg0, object arg1, object arg2) - { - if (this.IsInfoEnabled) - { - this.Logger.Log(ThisDeclaringType, this.m_levelInfo, new SystemStringFormat(CultureInfo.InvariantCulture, format, new object[] { arg0, arg1, arg2 }), null); - } - } - - /// - /// Logs a formatted message string with the INFO level. - /// - /// An that supplies culture-specific formatting information. - /// A String containing zero or more format items. - /// An Object array containing zero or more objects to format. - /// - /// - /// The message is formatted using the method. See - /// String.Format for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - public virtual void InfoFormat(IFormatProvider provider, string format, params object[] args) - { - if (this.IsInfoEnabled) - { - this.Logger.Log(ThisDeclaringType, this.m_levelInfo, new SystemStringFormat(provider, format, args), null); - } - } - - /// - /// Logs a message object with the WARN level. - /// - /// the message object to log. - /// - /// - /// This method first checks if this logger is WARN - /// enabled by comparing the level of this logger with the - /// WARN level. If this logger is - /// WARN enabled, then it converts the message object - /// (passed as parameter) to a string by invoking the appropriate - /// . It then - /// proceeds to call all the registered appenders in this logger and - /// also higher in the hierarchy depending on the value of the - /// additivity flag. - /// - /// - /// WARNING Note that passing an to this - /// method will print the name of the but no - /// stack trace. To print a stack trace use the - /// form instead. - /// - /// - public virtual void Warn(object message) - { - this.Logger.Log(ThisDeclaringType, this.m_levelWarn, message, null); - } - - /// - /// Logs a message object with the WARN level. - /// - /// The message object to log. - /// The exception to log, including its stack trace. - /// - /// - /// Logs a message object with the WARN level including - /// the stack trace of the - /// passed as a parameter. - /// - /// - /// See the form for more detailed information. - /// - /// - /// - public virtual void Warn(object message, Exception exception) - { - this.Logger.Log(ThisDeclaringType, this.m_levelWarn, message, exception); - } - - /// - /// Logs a formatted message string with the WARN level. - /// - /// A String containing zero or more format items. - /// An Object array containing zero or more objects to format. - /// - /// - /// The message is formatted using the method. See - /// String.Format for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// The string is formatted using the - /// format provider. To specify a localized provider use the - /// method. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - public virtual void WarnFormat(string format, params object[] args) - { - if (this.IsWarnEnabled) - { - this.Logger.Log(ThisDeclaringType, this.m_levelWarn, new SystemStringFormat(CultureInfo.InvariantCulture, format, args), null); - } - } - - /// - /// Logs a formatted message string with the WARN level. - /// - /// A String containing zero or more format items. - /// An Object to format. - /// - /// - /// The message is formatted using the method. See - /// String.Format for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// The string is formatted using the - /// format provider. To specify a localized provider use the - /// method. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - public virtual void WarnFormat(string format, object arg0) - { - if (this.IsWarnEnabled) - { - this.Logger.Log(ThisDeclaringType, this.m_levelWarn, new SystemStringFormat(CultureInfo.InvariantCulture, format, new object[] { arg0 }), null); - } - } - - /// - /// Logs a formatted message string with the WARN level. - /// - /// A String containing zero or more format items. - /// An Object to format. - /// An Object to format. - /// - /// - /// The message is formatted using the method. See - /// String.Format for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// The string is formatted using the - /// format provider. To specify a localized provider use the - /// method. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - public virtual void WarnFormat(string format, object arg0, object arg1) - { - if (this.IsWarnEnabled) - { - this.Logger.Log(ThisDeclaringType, this.m_levelWarn, new SystemStringFormat(CultureInfo.InvariantCulture, format, new object[] { arg0, arg1 }), null); - } - } - - /// - /// Logs a formatted message string with the WARN level. - /// - /// A String containing zero or more format items. - /// An Object to format. - /// An Object to format. - /// An Object to format. - /// - /// - /// The message is formatted using the method. See - /// String.Format for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// The string is formatted using the - /// format provider. To specify a localized provider use the - /// method. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - public virtual void WarnFormat(string format, object arg0, object arg1, object arg2) - { - if (this.IsWarnEnabled) - { - this.Logger.Log(ThisDeclaringType, this.m_levelWarn, new SystemStringFormat(CultureInfo.InvariantCulture, format, new object[] { arg0, arg1, arg2 }), null); - } - } - - /// - /// Logs a formatted message string with the WARN level. - /// - /// An that supplies culture-specific formatting information. - /// A String containing zero or more format items. - /// An Object array containing zero or more objects to format. - /// - /// - /// The message is formatted using the method. See - /// String.Format for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - public virtual void WarnFormat(IFormatProvider provider, string format, params object[] args) - { - if (this.IsWarnEnabled) - { - this.Logger.Log(ThisDeclaringType, this.m_levelWarn, new SystemStringFormat(provider, format, args), null); - } - } - - /// - /// Logs a message object with the ERROR level. - /// - /// The message object to log. - /// - /// - /// This method first checks if this logger is ERROR - /// enabled by comparing the level of this logger with the - /// ERROR level. If this logger is - /// ERROR enabled, then it converts the message object - /// (passed as parameter) to a string by invoking the appropriate - /// . It then - /// proceeds to call all the registered appenders in this logger and - /// also higher in the hierarchy depending on the value of the - /// additivity flag. - /// - /// - /// WARNING Note that passing an to this - /// method will print the name of the but no - /// stack trace. To print a stack trace use the - /// form instead. - /// - /// - public virtual void Error(object message) - { - this.Logger.Log(ThisDeclaringType, this.m_levelError, message, null); - } - - /// - /// Logs a message object with the ERROR level. - /// - /// The message object to log. - /// The exception to log, including its stack trace. - /// - /// - /// Logs a message object with the ERROR level including - /// the stack trace of the - /// passed as a parameter. - /// - /// - /// See the form for more detailed information. - /// - /// - /// - public virtual void Error(object message, Exception exception) - { - this.Logger.Log(ThisDeclaringType, this.m_levelError, message, exception); - } - - /// - /// Logs a formatted message string with the ERROR level. - /// - /// A String containing zero or more format items. - /// An Object array containing zero or more objects to format. - /// - /// - /// The message is formatted using the method. See - /// String.Format for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// The string is formatted using the - /// format provider. To specify a localized provider use the - /// method. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - public virtual void ErrorFormat(string format, params object[] args) - { - if (this.IsErrorEnabled) - { - this.Logger.Log(ThisDeclaringType, this.m_levelError, new SystemStringFormat(CultureInfo.InvariantCulture, format, args), null); - } - } - - /// - /// Logs a formatted message string with the ERROR level. - /// - /// A String containing zero or more format items. - /// An Object to format. - /// - /// - /// The message is formatted using the method. See - /// String.Format for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// The string is formatted using the - /// format provider. To specify a localized provider use the - /// method. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - public virtual void ErrorFormat(string format, object arg0) - { - if (this.IsErrorEnabled) - { - this.Logger.Log(ThisDeclaringType, this.m_levelError, new SystemStringFormat(CultureInfo.InvariantCulture, format, new object[] { arg0 }), null); - } - } - - /// - /// Logs a formatted message string with the ERROR level. - /// - /// A String containing zero or more format items. - /// An Object to format. - /// An Object to format. - /// - /// - /// The message is formatted using the method. See - /// String.Format for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// The string is formatted using the - /// format provider. To specify a localized provider use the - /// method. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - public virtual void ErrorFormat(string format, object arg0, object arg1) - { - if (this.IsErrorEnabled) - { - this.Logger.Log(ThisDeclaringType, this.m_levelError, new SystemStringFormat(CultureInfo.InvariantCulture, format, new object[] { arg0, arg1 }), null); - } - } - - /// - /// Logs a formatted message string with the ERROR level. - /// - /// A String containing zero or more format items. - /// An Object to format. - /// An Object to format. - /// An Object to format. - /// - /// - /// The message is formatted using the method. See - /// String.Format for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// The string is formatted using the - /// format provider. To specify a localized provider use the - /// method. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - public virtual void ErrorFormat(string format, object arg0, object arg1, object arg2) - { - if (this.IsErrorEnabled) - { - this.Logger.Log(ThisDeclaringType, this.m_levelError, new SystemStringFormat(CultureInfo.InvariantCulture, format, new object[] { arg0, arg1, arg2 }), null); - } - } - - /// - /// Logs a formatted message string with the ERROR level. - /// - /// An that supplies culture-specific formatting information. - /// A String containing zero or more format items. - /// An Object array containing zero or more objects to format. - /// - /// - /// The message is formatted using the method. See - /// String.Format for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - public virtual void ErrorFormat(IFormatProvider provider, string format, params object[] args) - { - if (this.IsErrorEnabled) - { - this.Logger.Log(ThisDeclaringType, this.m_levelError, new SystemStringFormat(provider, format, args), null); - } - } - - /// - /// Logs a message object with the FATAL level. - /// - /// The message object to log. - /// - /// - /// This method first checks if this logger is FATAL - /// enabled by comparing the level of this logger with the - /// FATAL level. If this logger is - /// FATAL enabled, then it converts the message object - /// (passed as parameter) to a string by invoking the appropriate - /// . It then - /// proceeds to call all the registered appenders in this logger and - /// also higher in the hierarchy depending on the value of the - /// additivity flag. - /// - /// - /// WARNING Note that passing an to this - /// method will print the name of the but no - /// stack trace. To print a stack trace use the - /// form instead. - /// - /// - public virtual void Fatal(object message) - { - this.Logger.Log(ThisDeclaringType, this.m_levelFatal, message, null); - } - - /// - /// Logs a message object with the FATAL level. - /// - /// The message object to log. - /// The exception to log, including its stack trace. - /// - /// - /// Logs a message object with the FATAL level including - /// the stack trace of the - /// passed as a parameter. - /// - /// - /// See the form for more detailed information. - /// - /// - /// - public virtual void Fatal(object message, Exception exception) - { - this.Logger.Log(ThisDeclaringType, this.m_levelFatal, message, exception); - } - - /// - /// Logs a formatted message string with the FATAL level. - /// - /// A String containing zero or more format items. - /// An Object array containing zero or more objects to format. - /// - /// - /// The message is formatted using the method. See - /// String.Format for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// The string is formatted using the - /// format provider. To specify a localized provider use the - /// method. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - public virtual void FatalFormat(string format, params object[] args) - { - if (this.IsFatalEnabled) - { - this.Logger.Log(ThisDeclaringType, this.m_levelFatal, new SystemStringFormat(CultureInfo.InvariantCulture, format, args), null); - } - } - - /// - /// Logs a formatted message string with the FATAL level. - /// - /// A String containing zero or more format items. - /// An Object to format. - /// - /// - /// The message is formatted using the method. See - /// String.Format for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// The string is formatted using the - /// format provider. To specify a localized provider use the - /// method. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - public virtual void FatalFormat(string format, object arg0) - { - if (this.IsFatalEnabled) - { - this.Logger.Log(ThisDeclaringType, this.m_levelFatal, new SystemStringFormat(CultureInfo.InvariantCulture, format, new object[] { arg0 }), null); - } - } - - /// - /// Logs a formatted message string with the FATAL level. - /// - /// A String containing zero or more format items. - /// An Object to format. - /// An Object to format. - /// - /// - /// The message is formatted using the method. See - /// String.Format for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// The string is formatted using the - /// format provider. To specify a localized provider use the - /// method. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - public virtual void FatalFormat(string format, object arg0, object arg1) - { - if (this.IsFatalEnabled) - { - this.Logger.Log(ThisDeclaringType, this.m_levelFatal, new SystemStringFormat(CultureInfo.InvariantCulture, format, new object[] { arg0, arg1 }), null); - } - } - - /// - /// Logs a formatted message string with the FATAL level. - /// - /// A String containing zero or more format items. - /// An Object to format. - /// An Object to format. - /// An Object to format. - /// - /// - /// The message is formatted using the method. See - /// String.Format for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// The string is formatted using the - /// format provider. To specify a localized provider use the - /// method. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - public virtual void FatalFormat(string format, object arg0, object arg1, object arg2) - { - if (this.IsFatalEnabled) - { - this.Logger.Log(ThisDeclaringType, this.m_levelFatal, new SystemStringFormat(CultureInfo.InvariantCulture, format, new object[] { arg0, arg1, arg2 }), null); - } - } - - /// - /// Logs a formatted message string with the FATAL level. - /// - /// An that supplies culture-specific formatting information. - /// A String containing zero or more format items. - /// An Object array containing zero or more objects to format. - /// - /// - /// The message is formatted using the method. See - /// String.Format for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - public virtual void FatalFormat(IFormatProvider provider, string format, params object[] args) - { - if (this.IsFatalEnabled) - { - this.Logger.Log(ThisDeclaringType, this.m_levelFatal, new SystemStringFormat(provider, format, args), null); - } - } - - /// - /// Gets a value indicating whether checks if this logger is enabled for the DEBUG - /// level. - /// - /// - /// true if this logger is enabled for DEBUG events, - /// false otherwise. - /// - /// - /// - /// This function is intended to lessen the computational cost of - /// disabled log debug statements. - /// - /// - /// For some log Logger object, when you write: - /// - /// - /// log.Debug("This is entry number: " + i ); - /// - /// - /// You incur the cost constructing the message, concatenation in - /// this case, regardless of whether the message is logged or not. - /// - /// - /// If you are worried about speed, then you should write: - /// - /// - /// if (log.IsDebugEnabled()) - /// { - /// log.Debug("This is entry number: " + i ); - /// } - /// - /// - /// This way you will not incur the cost of parameter - /// construction if debugging is disabled for log. On - /// the other hand, if the log is debug enabled, you - /// will incur the cost of evaluating whether the logger is debug - /// enabled twice. Once in IsDebugEnabled and once in - /// the Debug. This is an insignificant overhead - /// since evaluating a logger takes about 1% of the time it - /// takes to actually log. - /// - /// - public virtual bool IsDebugEnabled - { - get { return this.Logger.IsEnabledFor(this.m_levelDebug); } - } - - /// - /// Gets a value indicating whether checks if this logger is enabled for the INFO level. - /// - /// - /// true if this logger is enabled for INFO events, - /// false otherwise. - /// - /// - /// - /// See for more information and examples - /// of using this method. - /// - /// - /// - public virtual bool IsInfoEnabled - { - get { return this.Logger.IsEnabledFor(this.m_levelInfo); } - } - - /// - /// Gets a value indicating whether checks if this logger is enabled for the WARN level. - /// - /// - /// true if this logger is enabled for WARN events, - /// false otherwise. - /// - /// - /// - /// See for more information and examples - /// of using this method. - /// - /// - /// - public virtual bool IsWarnEnabled - { - get { return this.Logger.IsEnabledFor(this.m_levelWarn); } - } - - /// - /// Gets a value indicating whether checks if this logger is enabled for the ERROR level. - /// - /// - /// true if this logger is enabled for ERROR events, - /// false otherwise. - /// - /// - /// - /// See for more information and examples of using this method. - /// - /// - /// - public virtual bool IsErrorEnabled - { - get { return this.Logger.IsEnabledFor(this.m_levelError); } - } - - /// - /// Gets a value indicating whether checks if this logger is enabled for the FATAL level. - /// - /// - /// true if this logger is enabled for FATAL events, - /// false otherwise. - /// - /// - /// - /// See for more information and examples of using this method. - /// - /// - /// - public virtual bool IsFatalEnabled - { - get { return this.Logger.IsEnabledFor(this.m_levelFatal); } + /// + /// Logs a formatted message string with the FATAL level. + /// + /// A String containing zero or more format items + /// An Object array containing zero or more objects to format + /// + /// + /// The message is formatted using the method. See + /// String.Format for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// The string is formatted using the + /// format provider. To specify a localized provider use the + /// method. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + public virtual void FatalFormat(string format, params object[] args) + { + if (this.IsFatalEnabled) + { + this.Logger.Log(ThisDeclaringType, this.m_levelFatal, new SystemStringFormat(CultureInfo.InvariantCulture, format, args), null); + } + } + + /// + /// Logs a formatted message string with the FATAL level. + /// + /// A String containing zero or more format items + /// An Object to format + /// + /// + /// The message is formatted using the method. See + /// String.Format for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// The string is formatted using the + /// format provider. To specify a localized provider use the + /// method. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + public virtual void FatalFormat(string format, object arg0) + { + if (this.IsFatalEnabled) + { + this.Logger.Log(ThisDeclaringType, this.m_levelFatal, new SystemStringFormat(CultureInfo.InvariantCulture, format, new object[] { arg0 }), null); + } + } + + /// + /// Logs a formatted message string with the FATAL level. + /// + /// A String containing zero or more format items + /// An Object to format + /// An Object to format + /// + /// + /// The message is formatted using the method. See + /// String.Format for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// The string is formatted using the + /// format provider. To specify a localized provider use the + /// method. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + public virtual void FatalFormat(string format, object arg0, object arg1) + { + if (this.IsFatalEnabled) + { + this.Logger.Log(ThisDeclaringType, this.m_levelFatal, new SystemStringFormat(CultureInfo.InvariantCulture, format, new object[] { arg0, arg1 }), null); + } + } + + /// + /// Logs a formatted message string with the FATAL level. + /// + /// A String containing zero or more format items + /// An Object to format + /// An Object to format + /// An Object to format + /// + /// + /// The message is formatted using the method. See + /// String.Format for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// The string is formatted using the + /// format provider. To specify a localized provider use the + /// method. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + public virtual void FatalFormat(string format, object arg0, object arg1, object arg2) + { + if (this.IsFatalEnabled) + { + this.Logger.Log(ThisDeclaringType, this.m_levelFatal, new SystemStringFormat(CultureInfo.InvariantCulture, format, new object[] { arg0, arg1, arg2 }), null); + } + } + + /// + /// Logs a formatted message string with the FATAL level. + /// + /// An that supplies culture-specific formatting information + /// A String containing zero or more format items + /// An Object array containing zero or more objects to format + /// + /// + /// The message is formatted using the method. See + /// String.Format for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + public virtual void FatalFormat(IFormatProvider provider, string format, params object[] args) + { + if (this.IsFatalEnabled) + { + this.Logger.Log(ThisDeclaringType, this.m_levelFatal, new SystemStringFormat(provider, format, args), null); + } + } + + /// + /// Checks if this logger is enabled for the DEBUG + /// level. + /// + /// + /// true if this logger is enabled for DEBUG events, + /// false otherwise. + /// + /// + /// + /// This function is intended to lessen the computational cost of + /// disabled log debug statements. + /// + /// + /// For some log Logger object, when you write: + /// + /// + /// log.Debug("This is entry number: " + i ); + /// + /// + /// You incur the cost constructing the message, concatenation in + /// this case, regardless of whether the message is logged or not. + /// + /// + /// If you are worried about speed, then you should write: + /// + /// + /// if (log.IsDebugEnabled()) + /// { + /// log.Debug("This is entry number: " + i ); + /// } + /// + /// + /// This way you will not incur the cost of parameter + /// construction if debugging is disabled for log. On + /// the other hand, if the log is debug enabled, you + /// will incur the cost of evaluating whether the logger is debug + /// enabled twice. Once in IsDebugEnabled and once in + /// the Debug. This is an insignificant overhead + /// since evaluating a logger takes about 1% of the time it + /// takes to actually log. + /// + /// + public virtual bool IsDebugEnabled + { + get { return this.Logger.IsEnabledFor(this.m_levelDebug); } + } + + /// + /// Checks if this logger is enabled for the INFO level. + /// + /// + /// true if this logger is enabled for INFO events, + /// false otherwise. + /// + /// + /// + /// See for more information and examples + /// of using this method. + /// + /// + /// + public virtual bool IsInfoEnabled + { + get { return this.Logger.IsEnabledFor(this.m_levelInfo); } + } + + /// + /// Checks if this logger is enabled for the WARN level. + /// + /// + /// true if this logger is enabled for WARN events, + /// false otherwise. + /// + /// + /// + /// See for more information and examples + /// of using this method. + /// + /// + /// + public virtual bool IsWarnEnabled + { + get { return this.Logger.IsEnabledFor(this.m_levelWarn); } } - /// - /// Event handler for the event. - /// - /// the repository. - /// Empty. - private void LoggerRepositoryConfigurationChanged(object sender, EventArgs e) - { - ILoggerRepository repository = sender as ILoggerRepository; - if (repository != null) - { - this.ReloadLevels(repository); - } + /// + /// Checks if this logger is enabled for the ERROR level. + /// + /// + /// true if this logger is enabled for ERROR events, + /// false otherwise. + /// + /// + /// + /// See for more information and examples of using this method. + /// + /// + /// + public virtual bool IsErrorEnabled + { + get { return this.Logger.IsEnabledFor(this.m_levelError); } } - /// - /// The fully qualified name of this declaring type not the type of any subclass. - /// + /// + /// Checks if this logger is enabled for the FATAL level. + /// + /// + /// true if this logger is enabled for FATAL events, + /// false otherwise. + /// + /// + /// + /// See for more information and examples of using this method. + /// + /// + /// + public virtual bool IsFatalEnabled + { + get { return this.Logger.IsEnabledFor(this.m_levelFatal); } + } + + /// + /// Event handler for the event + /// + /// the repository + /// Empty + private void LoggerRepositoryConfigurationChanged(object sender, EventArgs e) + { + ILoggerRepository repository = sender as ILoggerRepository; + if (repository != null) + { + this.ReloadLevels(repository); + } + } + + /// + /// The fully qualified name of this declaring type not the type of any subclass. + /// private static readonly Type ThisDeclaringType = typeof(LogImpl); - private Level m_levelDebug; - private Level m_levelInfo; - private Level m_levelWarn; - private Level m_levelError; + + private Level m_levelDebug; + private Level m_levelInfo; + private Level m_levelWarn; + private Level m_levelError; private Level m_levelFatal; - } -} + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Core/LoggerManager.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Core/LoggerManager.cs index 58bdd99c1b9..2357917e077 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Core/LoggerManager.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Core/LoggerManager.cs @@ -1,892 +1,859 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +using System; +#if NETSTANDARD1_3 +using System.Runtime.InteropServices; +#endif +using System.Reflection; + +using log4net.Util; +using log4net.Repository; + +namespace log4net.Core +{ + /// + /// Static manager that controls the creation of repositories + /// + /// + /// + /// Static manager that controls the creation of repositories + /// + /// + /// This class is used by the wrapper managers (e.g. ) + /// to provide access to the objects. + /// + /// + /// This manager also holds the that is used to + /// lookup and create repositories. The selector can be set either programmatically using + /// the property, or by setting the log4net.RepositorySelector + /// AppSetting in the applications config file to the fully qualified type name of the + /// selector to use. + /// + /// + /// Nicko Cadell + /// Gert Driesen + public sealed class LoggerManager + { + /// + /// Private constructor to prevent instances. Only static methods should be used. + /// + /// + /// + /// Private constructor to prevent instances. Only static methods should be used. + /// + /// + private LoggerManager() + { + } + /// + /// Hook the shutdown event + /// + /// + /// + /// On the full .NET runtime, the static constructor hooks up the + /// AppDomain.ProcessExit and AppDomain.DomainUnload> events. + /// These are used to shutdown the log4net system as the application exits. + /// + /// + static LoggerManager() + { + try + { + // Register the AppDomain events, note we have to do this with a + // method call rather than directly here because the AppDomain + // makes a LinkDemand which throws the exception during the JIT phase. + RegisterAppDomainEvents(); + } + catch(System.Security.SecurityException) + { + LogLog.Debug(declaringType, "Security Exception (ControlAppDomain LinkDemand) while trying "+ + "to register Shutdown handler with the AppDomain. LoggerManager.Shutdown() "+ + "will not be called automatically when the AppDomain exits. It must be called "+ + "programmatically."); + } + + // Dump out our assembly version into the log if debug is enabled + LogLog.Debug(declaringType, GetVersionInfo()); + + // Set the default repository selector +#if NETCF + s_repositorySelector = new CompactRepositorySelector(typeof(log4net.Repository.Hierarchy.Hierarchy)); + return; +#elif !NETSTANDARD1_3 + // Look for the RepositorySelector type specified in the AppSettings 'log4net.RepositorySelector' + string appRepositorySelectorTypeName = SystemInfo.GetAppSetting("log4net.RepositorySelector"); + if (appRepositorySelectorTypeName != null && appRepositorySelectorTypeName.Length > 0) + { + // Resolve the config string into a Type + Type appRepositorySelectorType = null; + try + { + appRepositorySelectorType = SystemInfo.GetTypeFromString(appRepositorySelectorTypeName, false, true); + } + catch(Exception ex) + { + LogLog.Error(declaringType, "Exception while resolving RepositorySelector Type ["+appRepositorySelectorTypeName+"]", ex); + } + + if (appRepositorySelectorType != null) + { + // Create an instance of the RepositorySelectorType + object appRepositorySelectorObj = null; + try + { + appRepositorySelectorObj = Activator.CreateInstance(appRepositorySelectorType); + } + catch(Exception ex) + { + LogLog.Error(declaringType, "Exception while creating RepositorySelector ["+appRepositorySelectorType.FullName+"]", ex); + } + + if (appRepositorySelectorObj != null && appRepositorySelectorObj is IRepositorySelector) + { + s_repositorySelector = (IRepositorySelector)appRepositorySelectorObj; + } + else + { + LogLog.Error(declaringType, "RepositorySelector Type ["+appRepositorySelectorType.FullName+"] is not an IRepositorySelector"); + } + } + } +#endif + // Create the DefaultRepositorySelector if not configured above + if (s_repositorySelector == null) + { + s_repositorySelector = new DefaultRepositorySelector(typeof(Repository.Hierarchy.Hierarchy)); + } + } + + /// + /// Register for ProcessExit and DomainUnload events on the AppDomain + /// + /// + /// + /// This needs to be in a separate method because the events make + /// a LinkDemand for the ControlAppDomain SecurityPermission. Because + /// this is a LinkDemand it is demanded at JIT time. Therefore we cannot + /// catch the exception in the method itself, we have to catch it in the + /// caller. + /// + /// + private static void RegisterAppDomainEvents() + { +#if !NETCF && !NETSTANDARD1_3 + // ProcessExit seems to be fired if we are part of the default domain + AppDomain.CurrentDomain.ProcessExit += new EventHandler(OnProcessExit); + + // Otherwise DomainUnload is fired + AppDomain.CurrentDomain.DomainUnload += new EventHandler(OnDomainUnload); +#endif + } + + /// + /// Return the default instance. + /// + /// the repository to lookup in + /// Return the default instance + /// + /// + /// Gets the for the repository specified + /// by the argument. + /// + /// + [Obsolete("Use GetRepository instead of GetLoggerRepository")] + public static ILoggerRepository GetLoggerRepository(string repository) + { + return GetRepository(repository); + } + + /// + /// Returns the default instance. + /// + /// The assembly to use to lookup the repository. + /// The default instance. + [Obsolete("Use GetRepository instead of GetLoggerRepository")] + public static ILoggerRepository GetLoggerRepository(Assembly repositoryAssembly) + { + return GetRepository(repositoryAssembly); + } -#if NETSTANDARD1_3 -using System.Runtime.InteropServices; -#else -using System.Configuration; - -#endif -using System.Reflection; - -using log4net.Repository; -using log4net.Util; - -namespace log4net.Core -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; - - /// - /// Static manager that controls the creation of repositories. - /// - /// - /// - /// Static manager that controls the creation of repositories. - /// - /// - /// This class is used by the wrapper managers (e.g. ) - /// to provide access to the objects. - /// - /// - /// This manager also holds the that is used to - /// lookup and create repositories. The selector can be set either programmatically using - /// the property, or by setting the log4net.RepositorySelector - /// AppSetting in the applications config file to the fully qualified type name of the - /// selector to use. - /// - /// - /// Nicko Cadell. - /// Gert Driesen. - public sealed class LoggerManager - { /// - /// Initializes a new instance of the class. - /// Private constructor to prevent instances. Only static methods should be used. - /// - /// - /// - /// Private constructor to prevent instances. Only static methods should be used. - /// - /// - private LoggerManager() - { + /// Return the default instance. + /// + /// the repository to lookup in + /// Return the default instance + /// + /// + /// Gets the for the repository specified + /// by the argument. + /// + /// + public static ILoggerRepository GetRepository(string repository) + { + if (repository == null) + { + throw new ArgumentNullException("repository"); + } + return RepositorySelector.GetRepository(repository); } /// - /// Initializes static members of the class. - /// Hook the shutdown event. - /// - /// - /// - /// On the full .NET runtime, the static constructor hooks up the - /// AppDomain.ProcessExit and AppDomain.DomainUnload> events. - /// These are used to shutdown the log4net system as the application exits. - /// - /// - static LoggerManager() - { - try - { - // Register the AppDomain events, note we have to do this with a - // method call rather than directly here because the AppDomain - // makes a LinkDemand which throws the exception during the JIT phase. - RegisterAppDomainEvents(); - } - catch (System.Security.SecurityException) - { - LogLog.Debug(declaringType, "Security Exception (ControlAppDomain LinkDemand) while trying " + - "to register Shutdown handler with the AppDomain. LoggerManager.Shutdown() " + - "will not be called automatically when the AppDomain exits. It must be called " + - "programmatically."); - } - - // Dump out our assembly version into the log if debug is enabled - LogLog.Debug(declaringType, GetVersionInfo()); - - // Set the default repository selector -#if NETCF - s_repositorySelector = new CompactRepositorySelector(typeof(log4net.Repository.Hierarchy.Hierarchy)); - return; -#elif !NETSTANDARD1_3 - // Look for the RepositorySelector type specified in the AppSettings 'log4net.RepositorySelector' - string appRepositorySelectorTypeName = SystemInfo.GetAppSetting("log4net.RepositorySelector"); - if (appRepositorySelectorTypeName != null && appRepositorySelectorTypeName.Length > 0) - { - // Resolve the config string into a Type - Type appRepositorySelectorType = null; - try - { - appRepositorySelectorType = SystemInfo.GetTypeFromString(appRepositorySelectorTypeName, false, true); - } - catch (Exception ex) - { - LogLog.Error(declaringType, "Exception while resolving RepositorySelector Type [" + appRepositorySelectorTypeName + "]", ex); - } - - if (appRepositorySelectorType != null) - { - // Create an instance of the RepositorySelectorType - object appRepositorySelectorObj = null; - try - { - appRepositorySelectorObj = Activator.CreateInstance(appRepositorySelectorType); - } - catch (Exception ex) - { - LogLog.Error(declaringType, "Exception while creating RepositorySelector [" + appRepositorySelectorType.FullName + "]", ex); - } - - if (appRepositorySelectorObj != null && appRepositorySelectorObj is IRepositorySelector) - { - s_repositorySelector = (IRepositorySelector)appRepositorySelectorObj; - } - else - { - LogLog.Error(declaringType, "RepositorySelector Type [" + appRepositorySelectorType.FullName + "] is not an IRepositorySelector"); - } - } - } -#endif - - // Create the DefaultRepositorySelector if not configured above - if (s_repositorySelector == null) - { - s_repositorySelector = new DefaultRepositorySelector(typeof(log4net.Repository.Hierarchy.Hierarchy)); - } - } - - /// - /// Register for ProcessExit and DomainUnload events on the AppDomain. - /// - /// - /// - /// This needs to be in a separate method because the events make - /// a LinkDemand for the ControlAppDomain SecurityPermission. Because - /// this is a LinkDemand it is demanded at JIT time. Therefore we cannot - /// catch the exception in the method itself, we have to catch it in the - /// caller. - /// - /// - private static void RegisterAppDomainEvents() - { -#if !(NETCF || NETSTANDARD1_3) - // ProcessExit seems to be fired if we are part of the default domain - AppDomain.CurrentDomain.ProcessExit += new EventHandler(OnProcessExit); - - // Otherwise DomainUnload is fired - AppDomain.CurrentDomain.DomainUnload += new EventHandler(OnDomainUnload); -#endif + /// Returns the default instance. + /// + /// The assembly to use to lookup the repository. + /// The default instance. + /// + /// + /// Returns the default instance. + /// + /// + public static ILoggerRepository GetRepository(Assembly repositoryAssembly) + { + if (repositoryAssembly == null) + { + throw new ArgumentNullException("repositoryAssembly"); + } + return RepositorySelector.GetRepository(repositoryAssembly); } - /// - /// Return the default instance. - /// - /// the repository to lookup in. - /// Return the default instance. - /// - /// - /// Gets the for the repository specified - /// by the argument. - /// - /// - [Obsolete("Use GetRepository instead of GetLoggerRepository. Scheduled removal in v10.0.0.")] - public static ILoggerRepository GetLoggerRepository(string repository) - { - return GetRepository(repository); - } - - /// - /// Returns the default instance. - /// - /// The assembly to use to lookup the repository. - /// The default instance. - [Obsolete("Use GetRepository instead of GetLoggerRepository. Scheduled removal in v10.0.0.")] - public static ILoggerRepository GetLoggerRepository(Assembly repositoryAssembly) - { - return GetRepository(repositoryAssembly); - } - - /// - /// Return the default instance. - /// - /// the repository to lookup in. - /// Return the default instance. - /// - /// - /// Gets the for the repository specified - /// by the argument. - /// - /// - public static ILoggerRepository GetRepository(string repository) - { - if (repository == null) - { - throw new ArgumentNullException("repository"); - } - - return RepositorySelector.GetRepository(repository); - } - - /// - /// Returns the default instance. - /// - /// The assembly to use to lookup the repository. - /// The default instance. - /// - /// - /// Returns the default instance. - /// - /// - public static ILoggerRepository GetRepository(Assembly repositoryAssembly) - { - if (repositoryAssembly == null) - { - throw new ArgumentNullException("repositoryAssembly"); - } - - return RepositorySelector.GetRepository(repositoryAssembly); - } - - /// - /// Returns the named logger if it exists. - /// - /// The repository to lookup in. - /// The fully qualified logger name to look for. - /// - /// The logger found, or null if the named logger does not exist in the - /// specified repository. - /// - /// - /// - /// If the named logger exists (in the specified repository) then it - /// returns a reference to the logger, otherwise it returns - /// null. - /// - /// - public static ILogger Exists(string repository, string name) - { - if (repository == null) - { - throw new ArgumentNullException("repository"); - } - - if (name == null) - { - throw new ArgumentNullException("name"); - } - - return RepositorySelector.GetRepository(repository).Exists(name); - } - - /// - /// Returns the named logger if it exists. - /// - /// The assembly to use to lookup the repository. - /// The fully qualified logger name to look for. - /// - /// The logger found, or null if the named logger does not exist in the - /// specified assembly's repository. - /// - /// - /// - /// If the named logger exists (in the specified assembly's repository) then it - /// returns a reference to the logger, otherwise it returns - /// null. - /// - /// - public static ILogger Exists(Assembly repositoryAssembly, string name) - { - if (repositoryAssembly == null) - { - throw new ArgumentNullException("repositoryAssembly"); - } - - if (name == null) - { - throw new ArgumentNullException("name"); - } - - return RepositorySelector.GetRepository(repositoryAssembly).Exists(name); - } - - /// - /// Returns all the currently defined loggers in the specified repository. - /// - /// The repository to lookup in. - /// All the defined loggers. - /// - /// - /// The root logger is not included in the returned array. - /// - /// - public static ILogger[] GetCurrentLoggers(string repository) - { - if (repository == null) - { - throw new ArgumentNullException("repository"); - } - - return RepositorySelector.GetRepository(repository).GetCurrentLoggers(); - } - - /// - /// Returns all the currently defined loggers in the specified assembly's repository. - /// - /// The assembly to use to lookup the repository. - /// All the defined loggers. - /// - /// - /// The root logger is not included in the returned array. - /// - /// - public static ILogger[] GetCurrentLoggers(Assembly repositoryAssembly) - { - if (repositoryAssembly == null) - { - throw new ArgumentNullException("repositoryAssembly"); - } - - return RepositorySelector.GetRepository(repositoryAssembly).GetCurrentLoggers(); - } - - /// - /// Retrieves or creates a named logger. - /// - /// The repository to lookup in. - /// The name of the logger to retrieve. - /// The logger with the name specified. - /// - /// - /// Retrieves a logger named as the - /// parameter. If the named logger already exists, then the - /// existing instance will be returned. Otherwise, a new instance is - /// created. - /// - /// - /// By default, loggers do not have a set level but inherit - /// it from the hierarchy. This is one of the central features of - /// log4net. - /// - /// - public static ILogger GetLogger(string repository, string name) - { - if (repository == null) - { - throw new ArgumentNullException("repository"); - } - - if (name == null) - { - throw new ArgumentNullException("name"); - } - - return RepositorySelector.GetRepository(repository).GetLogger(name); - } - - /// - /// Retrieves or creates a named logger. - /// - /// The assembly to use to lookup the repository. - /// The name of the logger to retrieve. - /// The logger with the name specified. - /// - /// - /// Retrieves a logger named as the - /// parameter. If the named logger already exists, then the - /// existing instance will be returned. Otherwise, a new instance is - /// created. - /// - /// - /// By default, loggers do not have a set level but inherit - /// it from the hierarchy. This is one of the central features of - /// log4net. - /// - /// - public static ILogger GetLogger(Assembly repositoryAssembly, string name) - { - if (repositoryAssembly == null) - { - throw new ArgumentNullException("repositoryAssembly"); - } - - if (name == null) - { - throw new ArgumentNullException("name"); - } - - return RepositorySelector.GetRepository(repositoryAssembly).GetLogger(name); - } - - /// - /// Shorthand for . - /// - /// The repository to lookup in. - /// The of which the fullname will be used as the name of the logger to retrieve. - /// The logger with the name specified. - /// - /// - /// Gets the logger for the fully qualified name of the type specified. - /// - /// - public static ILogger GetLogger(string repository, Type type) - { - if (repository == null) - { - throw new ArgumentNullException("repository"); - } - - if (type == null) - { - throw new ArgumentNullException("type"); - } - - return RepositorySelector.GetRepository(repository).GetLogger(type.FullName); - } - - /// - /// Shorthand for . - /// - /// the assembly to use to lookup the repository. - /// The of which the fullname will be used as the name of the logger to retrieve. - /// The logger with the name specified. - /// - /// - /// Gets the logger for the fully qualified name of the type specified. - /// - /// - public static ILogger GetLogger(Assembly repositoryAssembly, Type type) - { - if (repositoryAssembly == null) - { - throw new ArgumentNullException("repositoryAssembly"); - } - - if (type == null) - { - throw new ArgumentNullException("type"); - } - - return RepositorySelector.GetRepository(repositoryAssembly).GetLogger(type.FullName); - } - - /// - /// Shuts down the log4net system. - /// - /// - /// - /// Calling this method will safely close and remove all - /// appenders in all the loggers including root contained in all the - /// default repositories. - /// - /// - /// Some appenders need to be closed before the application exists. - /// Otherwise, pending logging events might be lost. - /// - /// - /// The shutdown method is careful to close nested - /// appenders before closing regular appenders. This is allows - /// configurations where a regular appender is attached to a logger - /// and again to a nested appender. - /// - /// - public static void Shutdown() - { - foreach (ILoggerRepository repository in GetAllRepositories()) - { - repository.Shutdown(); - } - } - - /// - /// Shuts down the repository for the repository specified. - /// - /// The repository to shutdown. - /// - /// - /// Calling this method will safely close and remove all - /// appenders in all the loggers including root contained in the - /// repository for the specified. - /// - /// - /// Some appenders need to be closed before the application exists. - /// Otherwise, pending logging events might be lost. - /// - /// - /// The shutdown method is careful to close nested - /// appenders before closing regular appenders. This is allows - /// configurations where a regular appender is attached to a logger - /// and again to a nested appender. - /// - /// - public static void ShutdownRepository(string repository) - { - if (repository == null) - { - throw new ArgumentNullException("repository"); - } - - RepositorySelector.GetRepository(repository).Shutdown(); - } - - /// - /// Shuts down the repository for the repository specified. - /// - /// The assembly to use to lookup the repository. - /// - /// - /// Calling this method will safely close and remove all - /// appenders in all the loggers including root contained in the - /// repository for the repository. The repository is looked up using - /// the specified. - /// - /// - /// Some appenders need to be closed before the application exists. - /// Otherwise, pending logging events might be lost. - /// - /// - /// The shutdown method is careful to close nested - /// appenders before closing regular appenders. This is allows - /// configurations where a regular appender is attached to a logger - /// and again to a nested appender. - /// - /// - public static void ShutdownRepository(Assembly repositoryAssembly) - { - if (repositoryAssembly == null) - { - throw new ArgumentNullException("repositoryAssembly"); - } - - RepositorySelector.GetRepository(repositoryAssembly).Shutdown(); - } - - /// - /// Resets all values contained in this repository instance to their defaults. - /// - /// The repository to reset. - /// - /// - /// Resets all values contained in the repository instance to their - /// defaults. This removes all appenders from all loggers, sets - /// the level of all non-root loggers to null, - /// sets their additivity flag to true and sets the level - /// of the root logger to . Moreover, - /// message disabling is set its default "off" value. - /// - /// - public static void ResetConfiguration(string repository) - { - if (repository == null) - { - throw new ArgumentNullException("repository"); - } - - RepositorySelector.GetRepository(repository).ResetConfiguration(); - } - - /// - /// Resets all values contained in this repository instance to their defaults. - /// - /// The assembly to use to lookup the repository to reset. - /// - /// - /// Resets all values contained in the repository instance to their - /// defaults. This removes all appenders from all loggers, sets - /// the level of all non-root loggers to null, - /// sets their additivity flag to true and sets the level - /// of the root logger to . Moreover, - /// message disabling is set its default "off" value. - /// - /// - public static void ResetConfiguration(Assembly repositoryAssembly) - { - if (repositoryAssembly == null) - { - throw new ArgumentNullException("repositoryAssembly"); - } - - RepositorySelector.GetRepository(repositoryAssembly).ResetConfiguration(); - } - - /// - /// Creates a repository with the specified name. - /// - /// The name of the repository, this must be unique amongst repositories. - /// The created for the repository. - /// - /// - /// CreateDomain is obsolete. Use CreateRepository instead of CreateDomain. - /// - /// - /// Creates the default type of which is a - /// object. - /// - /// - /// The name must be unique. Repositories cannot be redefined. - /// An will be thrown if the repository already exists. - /// - /// - /// The specified repository already exists. - [Obsolete("Use CreateRepository instead of CreateDomain. Scheduled removal in v10.0.0.")] - public static ILoggerRepository CreateDomain(string repository) - { - return CreateRepository(repository); - } - - /// - /// Creates a repository with the specified name. - /// - /// The name of the repository, this must be unique amongst repositories. - /// The created for the repository. - /// - /// - /// Creates the default type of which is a - /// object. - /// - /// - /// The name must be unique. Repositories cannot be redefined. - /// An will be thrown if the repository already exists. - /// - /// - /// The specified repository already exists. - public static ILoggerRepository CreateRepository(string repository) - { - if (repository == null) - { - throw new ArgumentNullException("repository"); - } - - return RepositorySelector.CreateRepository(repository, null); - } - - /// - /// Creates a repository with the specified name and repository type. - /// - /// The name of the repository, this must be unique to the repository. - /// A that implements - /// and has a no arg constructor. An instance of this type will be created to act - /// as the for the repository specified. - /// The created for the repository. - /// - /// - /// CreateDomain is obsolete. Use CreateRepository instead of CreateDomain. - /// - /// - /// The name must be unique. Repositories cannot be redefined. - /// An Exception will be thrown if the repository already exists. - /// - /// - /// The specified repository already exists. - [Obsolete("Use CreateRepository instead of CreateDomain. Scheduled removal in v10.0.0.")] - public static ILoggerRepository CreateDomain(string repository, Type repositoryType) - { - return CreateRepository(repository, repositoryType); - } - - /// - /// Creates a repository with the specified name and repository type. - /// - /// The name of the repository, this must be unique to the repository. - /// A that implements - /// and has a no arg constructor. An instance of this type will be created to act - /// as the for the repository specified. - /// The created for the repository. - /// - /// - /// The name must be unique. Repositories cannot be redefined. - /// An Exception will be thrown if the repository already exists. - /// - /// - /// The specified repository already exists. - public static ILoggerRepository CreateRepository(string repository, Type repositoryType) - { - if (repository == null) - { - throw new ArgumentNullException("repository"); - } - - if (repositoryType == null) - { - throw new ArgumentNullException("repositoryType"); - } - - return RepositorySelector.CreateRepository(repository, repositoryType); - } - - /// - /// Creates a repository for the specified assembly and repository type. - /// - /// The assembly to use to get the name of the repository. - /// A that implements - /// and has a no arg constructor. An instance of this type will be created to act - /// as the for the repository specified. - /// The created for the repository. - /// - /// - /// CreateDomain is obsolete. Use CreateRepository instead of CreateDomain. - /// - /// - /// The created will be associated with the repository - /// specified such that a call to with the - /// same assembly specified will return the same repository instance. - /// - /// - [Obsolete("Use CreateRepository instead of CreateDomain. Scheduled removal in v10.0.0.")] - public static ILoggerRepository CreateDomain(Assembly repositoryAssembly, Type repositoryType) - { - return CreateRepository(repositoryAssembly, repositoryType); - } - - /// - /// Creates a repository for the specified assembly and repository type. - /// - /// The assembly to use to get the name of the repository. - /// A that implements - /// and has a no arg constructor. An instance of this type will be created to act - /// as the for the repository specified. - /// The created for the repository. - /// - /// - /// The created will be associated with the repository - /// specified such that a call to with the - /// same assembly specified will return the same repository instance. - /// - /// - public static ILoggerRepository CreateRepository(Assembly repositoryAssembly, Type repositoryType) - { - if (repositoryAssembly == null) - { - throw new ArgumentNullException("repositoryAssembly"); - } - - if (repositoryType == null) - { - throw new ArgumentNullException("repositoryType"); - } - - return RepositorySelector.CreateRepository(repositoryAssembly, repositoryType); - } - - /// - /// Gets an array of all currently defined repositories. - /// - /// An array of all the known objects. - /// - /// - /// Gets an array of all currently defined repositories. - /// - /// - public static ILoggerRepository[] GetAllRepositories() - { - return RepositorySelector.GetAllRepositories(); - } - - /// - /// Gets or sets the repository selector used by the . - /// - /// - /// The repository selector used by the . - /// - /// - /// - /// The repository selector () is used by - /// the to create and select repositories - /// (). - /// - /// - /// The caller to supplies either a string name - /// or an assembly (if not supplied the assembly is inferred using - /// ). - /// - /// - /// This context is used by the selector to lookup a specific repository. - /// - /// - /// For the full .NET Framework, the default repository is DefaultRepositorySelector; - /// for the .NET Compact Framework CompactRepositorySelector is the default - /// repository. - /// - /// - public static IRepositorySelector RepositorySelector - { - get { return s_repositorySelector; } - set { s_repositorySelector = value; } + /// + /// Returns the named logger if it exists. + /// + /// The repository to lookup in. + /// The fully qualified logger name to look for. + /// + /// The logger found, or null if the named logger does not exist in the + /// specified repository. + /// + /// + /// + /// If the named logger exists (in the specified repository) then it + /// returns a reference to the logger, otherwise it returns + /// null. + /// + /// + public static ILogger Exists(string repository, string name) + { + if (repository == null) + { + throw new ArgumentNullException("repository"); + } + if (name == null) + { + throw new ArgumentNullException("name"); + } + return RepositorySelector.GetRepository(repository).Exists(name); } - /// - /// Internal method to get pertinent version info. - /// - /// A string of version info. - private static string GetVersionInfo() - { - System.Text.StringBuilder sb = new System.Text.StringBuilder(); - -#if NETSTANDARD1_3 - Assembly myAssembly = typeof(LoggerManager).GetTypeInfo().Assembly; - sb.Append($"log4net assembly [{myAssembly.FullName}]. "); - //sb.Append($"Loaded from [{myAssembly.Location}]. "); // TODO Assembly.Location available in netstandard1.5 - sb.Append($"(.NET Framework [{RuntimeInformation.FrameworkDescription}] on {RuntimeInformation.OSDescription}"); -#else - Assembly myAssembly = Assembly.GetExecutingAssembly(); - sb.Append("log4net assembly [").Append(myAssembly.FullName).Append("]. "); - sb.Append("Loaded from [").Append(SystemInfo.AssemblyLocationInfo(myAssembly)).Append("]. "); - sb.Append("(.NET Runtime [").Append(Environment.Version.ToString()).Append("]"); -#if !SSCLI - sb.Append(" on ").Append(Environment.OSVersion.ToString()); -#endif -#endif // NETSTANDARD1_3 - sb.Append(")"); - return sb.ToString(); - } - -#if !NETCF - /// - /// Called when the event fires. - /// - /// the that is exiting. - /// null. - /// - /// - /// Called when the event fires. - /// - /// - /// When the event is triggered the log4net system is . - /// - /// - private static void OnDomainUnload(object sender, EventArgs e) - { - Shutdown(); - } - - /// - /// Called when the event fires. - /// - /// the that is exiting. - /// null. - /// - /// - /// Called when the event fires. - /// - /// - /// When the event is triggered the log4net system is . - /// - /// - private static void OnProcessExit(object sender, EventArgs e) - { - Shutdown(); + /// + /// Returns the named logger if it exists. + /// + /// The assembly to use to lookup the repository. + /// The fully qualified logger name to look for. + /// + /// The logger found, or null if the named logger does not exist in the + /// specified assembly's repository. + /// + /// + /// + /// If the named logger exists (in the specified assembly's repository) then it + /// returns a reference to the logger, otherwise it returns + /// null. + /// + /// + public static ILogger Exists(Assembly repositoryAssembly, string name) + { + if (repositoryAssembly == null) + { + throw new ArgumentNullException("repositoryAssembly"); + } + if (name == null) + { + throw new ArgumentNullException("name"); + } + return RepositorySelector.GetRepository(repositoryAssembly).Exists(name); } -#endif - - /// - /// The fully qualified type of the LoggerManager class. - /// - /// - /// Used by the internal logger to record the Type of the - /// log message. - /// - private static readonly Type declaringType = typeof(LoggerManager); - - /// - /// Initialize the default repository selector. - /// + + /// + /// Returns all the currently defined loggers in the specified repository. + /// + /// The repository to lookup in. + /// All the defined loggers. + /// + /// + /// The root logger is not included in the returned array. + /// + /// + public static ILogger[] GetCurrentLoggers(string repository) + { + if (repository == null) + { + throw new ArgumentNullException("repository"); + } + return RepositorySelector.GetRepository(repository).GetCurrentLoggers(); + } + + /// + /// Returns all the currently defined loggers in the specified assembly's repository. + /// + /// The assembly to use to lookup the repository. + /// All the defined loggers. + /// + /// + /// The root logger is not included in the returned array. + /// + /// + public static ILogger[] GetCurrentLoggers(Assembly repositoryAssembly) + { + if (repositoryAssembly == null) + { + throw new ArgumentNullException("repositoryAssembly"); + } + return RepositorySelector.GetRepository(repositoryAssembly).GetCurrentLoggers(); + } + + /// + /// Retrieves or creates a named logger. + /// + /// The repository to lookup in. + /// The name of the logger to retrieve. + /// The logger with the name specified. + /// + /// + /// Retrieves a logger named as the + /// parameter. If the named logger already exists, then the + /// existing instance will be returned. Otherwise, a new instance is + /// created. + /// + /// + /// By default, loggers do not have a set level but inherit + /// it from the hierarchy. This is one of the central features of + /// log4net. + /// + /// + public static ILogger GetLogger(string repository, string name) + { + if (repository == null) + { + throw new ArgumentNullException("repository"); + } + if (name == null) + { + throw new ArgumentNullException("name"); + } + return RepositorySelector.GetRepository(repository).GetLogger(name); + } + + /// + /// Retrieves or creates a named logger. + /// + /// The assembly to use to lookup the repository. + /// The name of the logger to retrieve. + /// The logger with the name specified. + /// + /// + /// Retrieves a logger named as the + /// parameter. If the named logger already exists, then the + /// existing instance will be returned. Otherwise, a new instance is + /// created. + /// + /// + /// By default, loggers do not have a set level but inherit + /// it from the hierarchy. This is one of the central features of + /// log4net. + /// + /// + public static ILogger GetLogger(Assembly repositoryAssembly, string name) + { + if (repositoryAssembly == null) + { + throw new ArgumentNullException("repositoryAssembly"); + } + if (name == null) + { + throw new ArgumentNullException("name"); + } + return RepositorySelector.GetRepository(repositoryAssembly).GetLogger(name); + } + + /// + /// Shorthand for . + /// + /// The repository to lookup in. + /// The of which the fullname will be used as the name of the logger to retrieve. + /// The logger with the name specified. + /// + /// + /// Gets the logger for the fully qualified name of the type specified. + /// + /// + public static ILogger GetLogger(string repository, Type type) + { + if (repository == null) + { + throw new ArgumentNullException("repository"); + } + if (type == null) + { + throw new ArgumentNullException("type"); + } + return RepositorySelector.GetRepository(repository).GetLogger(type.FullName); + } + + /// + /// Shorthand for . + /// + /// the assembly to use to lookup the repository + /// The of which the fullname will be used as the name of the logger to retrieve. + /// The logger with the name specified. + /// + /// + /// Gets the logger for the fully qualified name of the type specified. + /// + /// + public static ILogger GetLogger(Assembly repositoryAssembly, Type type) + { + if (repositoryAssembly == null) + { + throw new ArgumentNullException("repositoryAssembly"); + } + if (type == null) + { + throw new ArgumentNullException("type"); + } + return RepositorySelector.GetRepository(repositoryAssembly).GetLogger(type.FullName); + } + + /// + /// Shuts down the log4net system. + /// + /// + /// + /// Calling this method will safely close and remove all + /// appenders in all the loggers including root contained in all the + /// default repositories. + /// + /// + /// Some appenders need to be closed before the application exists. + /// Otherwise, pending logging events might be lost. + /// + /// + /// The shutdown method is careful to close nested + /// appenders before closing regular appenders. This is allows + /// configurations where a regular appender is attached to a logger + /// and again to a nested appender. + /// + /// + public static void Shutdown() + { + foreach(ILoggerRepository repository in GetAllRepositories()) + { + repository.Shutdown(); + } + } + + /// + /// Shuts down the repository for the repository specified. + /// + /// The repository to shutdown. + /// + /// + /// Calling this method will safely close and remove all + /// appenders in all the loggers including root contained in the + /// repository for the specified. + /// + /// + /// Some appenders need to be closed before the application exists. + /// Otherwise, pending logging events might be lost. + /// + /// + /// The shutdown method is careful to close nested + /// appenders before closing regular appenders. This is allows + /// configurations where a regular appender is attached to a logger + /// and again to a nested appender. + /// + /// + public static void ShutdownRepository(string repository) + { + if (repository == null) + { + throw new ArgumentNullException("repository"); + } + RepositorySelector.GetRepository(repository).Shutdown(); + } + + /// + /// Shuts down the repository for the repository specified. + /// + /// The assembly to use to lookup the repository. + /// + /// + /// Calling this method will safely close and remove all + /// appenders in all the loggers including root contained in the + /// repository for the repository. The repository is looked up using + /// the specified. + /// + /// + /// Some appenders need to be closed before the application exists. + /// Otherwise, pending logging events might be lost. + /// + /// + /// The shutdown method is careful to close nested + /// appenders before closing regular appenders. This is allows + /// configurations where a regular appender is attached to a logger + /// and again to a nested appender. + /// + /// + public static void ShutdownRepository(Assembly repositoryAssembly) + { + if (repositoryAssembly == null) + { + throw new ArgumentNullException("repositoryAssembly"); + } + RepositorySelector.GetRepository(repositoryAssembly).Shutdown(); + } + + /// + /// Resets all values contained in this repository instance to their defaults. + /// + /// The repository to reset. + /// + /// + /// Resets all values contained in the repository instance to their + /// defaults. This removes all appenders from all loggers, sets + /// the level of all non-root loggers to null, + /// sets their additivity flag to true and sets the level + /// of the root logger to . Moreover, + /// message disabling is set its default "off" value. + /// + /// + public static void ResetConfiguration(string repository) + { + if (repository == null) + { + throw new ArgumentNullException("repository"); + } + RepositorySelector.GetRepository(repository).ResetConfiguration(); + } + + /// + /// Resets all values contained in this repository instance to their defaults. + /// + /// The assembly to use to lookup the repository to reset. + /// + /// + /// Resets all values contained in the repository instance to their + /// defaults. This removes all appenders from all loggers, sets + /// the level of all non-root loggers to null, + /// sets their additivity flag to true and sets the level + /// of the root logger to . Moreover, + /// message disabling is set its default "off" value. + /// + /// + public static void ResetConfiguration(Assembly repositoryAssembly) + { + if (repositoryAssembly == null) + { + throw new ArgumentNullException("repositoryAssembly"); + } + RepositorySelector.GetRepository(repositoryAssembly).ResetConfiguration(); + } + + /// + /// Creates a repository with the specified name. + /// + /// The name of the repository, this must be unique amongst repositories. + /// The created for the repository. + /// + /// + /// CreateDomain is obsolete. Use CreateRepository instead of CreateDomain. + /// + /// + /// Creates the default type of which is a + /// object. + /// + /// + /// The name must be unique. Repositories cannot be redefined. + /// An will be thrown if the repository already exists. + /// + /// + /// The specified repository already exists. + [Obsolete("Use CreateRepository instead of CreateDomain")] + public static ILoggerRepository CreateDomain(string repository) + { + return CreateRepository(repository); + } + + /// + /// Creates a repository with the specified name. + /// + /// The name of the repository, this must be unique amongst repositories. + /// The created for the repository. + /// + /// + /// Creates the default type of which is a + /// object. + /// + /// + /// The name must be unique. Repositories cannot be redefined. + /// An will be thrown if the repository already exists. + /// + /// + /// The specified repository already exists. + public static ILoggerRepository CreateRepository(string repository) + { + if (repository == null) + { + throw new ArgumentNullException("repository"); + } + return RepositorySelector.CreateRepository(repository, null); + } + + /// + /// Creates a repository with the specified name and repository type. + /// + /// The name of the repository, this must be unique to the repository. + /// A that implements + /// and has a no arg constructor. An instance of this type will be created to act + /// as the for the repository specified. + /// The created for the repository. + /// + /// + /// CreateDomain is obsolete. Use CreateRepository instead of CreateDomain. + /// + /// + /// The name must be unique. Repositories cannot be redefined. + /// An Exception will be thrown if the repository already exists. + /// + /// + /// The specified repository already exists. + [Obsolete("Use CreateRepository instead of CreateDomain")] + public static ILoggerRepository CreateDomain(string repository, Type repositoryType) + { + return CreateRepository(repository, repositoryType); + } + + /// + /// Creates a repository with the specified name and repository type. + /// + /// The name of the repository, this must be unique to the repository. + /// A that implements + /// and has a no arg constructor. An instance of this type will be created to act + /// as the for the repository specified. + /// The created for the repository. + /// + /// + /// The name must be unique. Repositories cannot be redefined. + /// An Exception will be thrown if the repository already exists. + /// + /// + /// The specified repository already exists. + public static ILoggerRepository CreateRepository(string repository, Type repositoryType) + { + if (repository == null) + { + throw new ArgumentNullException("repository"); + } + if (repositoryType == null) + { + throw new ArgumentNullException("repositoryType"); + } + return RepositorySelector.CreateRepository(repository, repositoryType); + } + + /// + /// Creates a repository for the specified assembly and repository type. + /// + /// The assembly to use to get the name of the repository. + /// A that implements + /// and has a no arg constructor. An instance of this type will be created to act + /// as the for the repository specified. + /// The created for the repository. + /// + /// + /// CreateDomain is obsolete. Use CreateRepository instead of CreateDomain. + /// + /// + /// The created will be associated with the repository + /// specified such that a call to with the + /// same assembly specified will return the same repository instance. + /// + /// + [Obsolete("Use CreateRepository instead of CreateDomain")] + public static ILoggerRepository CreateDomain(Assembly repositoryAssembly, Type repositoryType) + { + return CreateRepository(repositoryAssembly, repositoryType); + } + + /// + /// Creates a repository for the specified assembly and repository type. + /// + /// The assembly to use to get the name of the repository. + /// A that implements + /// and has a no arg constructor. An instance of this type will be created to act + /// as the for the repository specified. + /// The created for the repository. + /// + /// + /// The created will be associated with the repository + /// specified such that a call to with the + /// same assembly specified will return the same repository instance. + /// + /// + public static ILoggerRepository CreateRepository(Assembly repositoryAssembly, Type repositoryType) + { + if (repositoryAssembly == null) + { + throw new ArgumentNullException("repositoryAssembly"); + } + if (repositoryType == null) + { + throw new ArgumentNullException("repositoryType"); + } + return RepositorySelector.CreateRepository(repositoryAssembly, repositoryType); + } + + /// + /// Gets an array of all currently defined repositories. + /// + /// An array of all the known objects. + /// + /// + /// Gets an array of all currently defined repositories. + /// + /// + public static ILoggerRepository[] GetAllRepositories() + { + return RepositorySelector.GetAllRepositories(); + } + + /// + /// Gets or sets the repository selector used by the . + /// + /// + /// The repository selector used by the . + /// + /// + /// + /// The repository selector () is used by + /// the to create and select repositories + /// (). + /// + /// + /// The caller to supplies either a string name + /// or an assembly (if not supplied the assembly is inferred using + /// ). + /// + /// + /// This context is used by the selector to lookup a specific repository. + /// + /// + /// For the full .NET Framework, the default repository is DefaultRepositorySelector; + /// for the .NET Compact Framework CompactRepositorySelector is the default + /// repository. + /// + /// + public static IRepositorySelector RepositorySelector + { + get { return s_repositorySelector; } + set { s_repositorySelector = value; } + } + + /// + /// Internal method to get pertinent version info. + /// + /// A string of version info. + private static string GetVersionInfo() + { + System.Text.StringBuilder sb = new System.Text.StringBuilder(); + +#if NETSTANDARD1_3 + Assembly myAssembly = typeof(LoggerManager).GetTypeInfo().Assembly; + sb.Append($"log4net assembly [{myAssembly.FullName}]. "); + //sb.Append($"Loaded from [{myAssembly.Location}]. "); // TODO Assembly.Location available in netstandard1.5 + sb.Append($"(.NET Framework [{RuntimeInformation.FrameworkDescription}] on {RuntimeInformation.OSDescription}"); +#else + Assembly myAssembly = Assembly.GetExecutingAssembly(); + sb.Append("log4net assembly [").Append(myAssembly.FullName).Append("]. "); + sb.Append("Loaded from [").Append(SystemInfo.AssemblyLocationInfo(myAssembly)).Append("]. "); + sb.Append("(.NET Runtime [").Append(Environment.Version.ToString()).Append("]"); +#if (!SSCLI) + sb.Append(" on ").Append(Environment.OSVersion.ToString()); +#endif +#endif // NETSTANDARD1_3 + sb.Append(")"); + return sb.ToString(); + } + +#if (!NETCF) + /// + /// Called when the event fires + /// + /// the that is exiting + /// null + /// + /// + /// Called when the event fires. + /// + /// + /// When the event is triggered the log4net system is . + /// + /// + private static void OnDomainUnload(object sender, EventArgs e) + { + Shutdown(); + } + + /// + /// Called when the event fires + /// + /// the that is exiting + /// null + /// + /// + /// Called when the event fires. + /// + /// + /// When the event is triggered the log4net system is . + /// + /// + private static void OnProcessExit(object sender, EventArgs e) + { + Shutdown(); + } +#endif + + /// + /// The fully qualified type of the LoggerManager class. + /// + /// + /// Used by the internal logger to record the Type of the + /// log message. + /// + private static readonly Type declaringType = typeof(LoggerManager); + + /// + /// Initialize the default repository selector + /// private static IRepositorySelector s_repositorySelector; - } -} + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Core/LoggerWrapperImpl.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Core/LoggerWrapperImpl.cs index 7511f37ae4e..eed73018266 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Core/LoggerWrapperImpl.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Core/LoggerWrapperImpl.cs @@ -1,76 +1,75 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information - -// +// // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at -// +// // http://www.apache.org/licenses/LICENSE-2.0 -// +// // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. -// -namespace log4net.Core -{ - /// - /// Implementation of the interface. - /// - /// - /// - /// This class should be used as the base for all wrapper implementations. - /// - /// - /// Nicko Cadell. - /// Gert Driesen. - public abstract class LoggerWrapperImpl : ILoggerWrapper +// + +namespace log4net.Core +{ + /// + /// Implementation of the interface. + /// + /// + /// + /// This class should be used as the base for all wrapper implementations. + /// + /// + /// Nicko Cadell + /// Gert Driesen + public abstract class LoggerWrapperImpl : ILoggerWrapper { /// - /// Initializes a new instance of the class. - /// Constructs a new wrapper for the specified logger. - /// - /// The logger to wrap. - /// - /// - /// Constructs a new wrapper for the specified logger. - /// - /// - protected LoggerWrapperImpl(ILogger logger) - { - this.m_logger = logger; + /// Constructs a new wrapper for the specified logger. + /// + /// The logger to wrap. + /// + /// + /// Constructs a new wrapper for the specified logger. + /// + /// + protected LoggerWrapperImpl(ILogger logger) + { + this.m_logger = logger; } - /// - /// Gets the implementation behind this wrapper object. - /// - /// - /// The object that this object is implementing. - /// - /// - /// - /// The Logger object may not be the same object as this object - /// because of logger decorators. - /// - /// - /// This gets the actual underlying objects that is used to process - /// the log events. - /// - /// - public virtual ILogger Logger - { - get { return this.m_logger; } + /// + /// Gets the implementation behind this wrapper object. + /// + /// + /// The object that this object is implementing. + /// + /// + /// + /// The Logger object may not be the same object as this object + /// because of logger decorators. + /// + /// + /// This gets the actual underlying objects that is used to process + /// the log events. + /// + /// + public virtual ILogger Logger + { + get { return this.m_logger; } } - /// - /// The logger that this object is wrapping. - /// + /// + /// The logger that this object is wrapping + /// private readonly ILogger m_logger; - } -} + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Core/LoggingEvent.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Core/LoggingEvent.cs index aefb3364c95..c44c92c5d46 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Core/LoggingEvent.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Core/LoggingEvent.cs @@ -1,1616 +1,1653 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +using System; +using System.Collections; +using System.IO; +using System.Runtime.Serialization; +using System.Security; +#if !NETCF && !NETSTANDARD1_3 +using System.Security.Principal; +#endif +using log4net.Util; +using log4net.Repository; -#if !NETCF -using System.Runtime.Serialization; - -#if !NETSTANDARD1_3 -using System.Security.Principal; - -#endif -#endif - -using log4net.Repository; -using log4net.Util; - -namespace log4net.Core -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; - using System.Collections; - using System.IO; - - /// - /// Portable data structure used by . - /// - /// - /// - /// Portable data structure used by . - /// - /// - /// Nicko Cadell. - public struct LoggingEventData +namespace log4net.Core +{ + /// + /// Portable data structure used by + /// + /// + /// + /// Portable data structure used by + /// + /// + /// Nicko Cadell + public struct LoggingEventData { - /// - /// The logger name. - /// - /// - /// - /// The logger name. - /// - /// - public string LoggerName; - - /// - /// Level of logging event. - /// - /// - /// - /// Level of logging event. Level cannot be Serializable - /// because it is a flyweight. Due to its special serialization it - /// cannot be declared final either. - /// - /// - public Level Level; - - /// - /// The application supplied message. - /// - /// - /// - /// The application supplied message of logging event. - /// - /// - public string Message; - - /// - /// The name of thread. - /// - /// - /// - /// The name of thread in which this logging event was generated. - /// - /// - public string ThreadName; - - /// - /// Gets or sets the local time the event was logged. - /// - /// - /// - /// Prefer using the setter, since local time can be ambiguous. - /// - /// - [Obsolete("Prefer using TimeStampUtc, since local time can be ambiguous in time zones with daylight savings time.. Scheduled removal in v11.0.0.")] + /// + /// The logger name. + /// + /// + /// + /// The logger name. + /// + /// + public string LoggerName; + + /// + /// Level of logging event. + /// + /// + /// + /// Level of logging event. Level cannot be Serializable + /// because it is a flyweight. Due to its special serialization it + /// cannot be declared final either. + /// + /// + public Level Level; + + /// + /// The application supplied message. + /// + /// + /// + /// The application supplied message of logging event. + /// + /// + public string Message; + + /// + /// The name of thread + /// + /// + /// + /// The name of thread in which this logging event was generated + /// + /// + public string ThreadName; + + /// + /// Gets or sets the local time the event was logged + /// + /// + /// + /// Prefer using the setter, since local time can be ambiguous. + /// + /// + [Obsolete( + "Prefer using TimeStampUtc, since local time can be ambiguous in time zones with daylight savings time.")] public DateTime TimeStamp; - /// - /// Gets or sets the UTC time the event was logged. - /// - /// - /// - /// The TimeStamp is stored in the UTC time zone. - /// - /// -#pragma warning disable 618 // Suppress warnings that TimeStamp field is obsolete - public DateTime TimeStampUtc - { - get - { - if (this.TimeStamp != default(DateTime) && - this._timeStampUtc == default(DateTime)) - { - // TimeStamp field has been set explicitly but TimeStampUtc hasn't - // => use TimeStamp - return this.TimeStamp.ToUniversalTime(); - } - - return this._timeStampUtc; - } - - set - { - this._timeStampUtc = value; - - // For backwards compatibility - this.TimeStamp = this._timeStampUtc.ToLocalTime(); - } - } - - private DateTime _timeStampUtc; -#pragma warning restore 618 - - /// - /// Location information for the caller. - /// - /// - /// - /// Location information for the caller. - /// - /// - public LocationInfo LocationInfo; - - /// - /// String representation of the user. - /// - /// - /// - /// String representation of the user's windows name, - /// like DOMAIN\username. - /// - /// - public string UserName; - - /// - /// String representation of the identity. - /// - /// - /// - /// String representation of the current thread's principal identity. - /// - /// - public string Identity; - - /// - /// The string representation of the exception. - /// - /// - /// - /// The string representation of the exception. - /// - /// - public string ExceptionString; - - /// - /// String representation of the AppDomain. - /// - /// - /// - /// String representation of the AppDomain. - /// - /// - public string Domain; - - /// - /// Additional event specific properties. - /// - /// - /// - /// A logger or an appender may attach additional - /// properties to specific events. These properties - /// have a string key and an object value. - /// - /// + /// + /// Gets or sets the UTC time the event was logged + /// + /// + /// + /// The TimeStamp is stored in the UTC time zone. + /// + /// +#pragma warning disable 618 // Suppress warnings that TimeStamp field is obsolete + public DateTime TimeStampUtc + { + get + { + if (this.TimeStamp != default(DateTime) && this._timeStampUtc == default(DateTime)) + { + // TimeStamp field has been set explicitly but TimeStampUtc hasn't + // => use TimeStamp + return this.TimeStamp.ToUniversalTime(); + } + + return this._timeStampUtc; + } + set + { + this._timeStampUtc = value; + // For backwards compatibility + this.TimeStamp = this._timeStampUtc.ToLocalTime(); + } + } + + private DateTime _timeStampUtc; +#pragma warning restore 618 + + /// + /// Location information for the caller. + /// + /// + /// + /// Location information for the caller. + /// + /// + public LocationInfo LocationInfo; + + /// + /// String representation of the user + /// + /// + /// + /// String representation of the user's windows name, + /// like DOMAIN\username + /// + /// + public string UserName; + + /// + /// String representation of the identity. + /// + /// + /// + /// String representation of the current thread's principal identity. + /// + /// + public string Identity; + + /// + /// The string representation of the exception + /// + /// + /// + /// The string representation of the exception + /// + /// + public string ExceptionString; + + /// + /// String representation of the AppDomain. + /// + /// + /// + /// String representation of the AppDomain. + /// + /// + public string Domain; + + /// + /// Additional event specific properties + /// + /// + /// + /// A logger or an appender may attach additional + /// properties to specific events. These properties + /// have a string key and an object value. + /// + /// public PropertiesDictionary Properties; - } - - /// - /// Flags passed to the property. - /// - /// - /// - /// Flags passed to the property. - /// - /// - /// Nicko Cadell. + } + + /// + /// Flags passed to the property + /// + /// + /// + /// Flags passed to the property + /// + /// + /// Nicko Cadell [Flags] - public enum FixFlags - { - /// - /// Fix the MDC - /// - [Obsolete("Replaced by composite Properties. Scheduled removal in v10.0.0.")] - Mdc = 0x01, - - /// - /// Fix the NDC - /// - Ndc = 0x02, - - /// - /// Fix the rendered message - /// - Message = 0x04, - - /// - /// Fix the thread name - /// - ThreadName = 0x08, - - /// - /// Fix the callers location information - /// - /// - /// CAUTION: Very slow to generate - /// - LocationInfo = 0x10, - - /// - /// Fix the callers windows user name - /// - /// - /// CAUTION: Slow to generate - /// - UserName = 0x20, - - /// - /// Fix the domain friendly name - /// - Domain = 0x40, - - /// - /// Fix the callers principal name - /// - /// - /// CAUTION: May be slow to generate - /// - Identity = 0x80, - - /// - /// Fix the exception text - /// - Exception = 0x100, - - /// - /// Fix the event properties. Active properties must implement in order to be eligible for fixing. - /// - Properties = 0x200, - - /// - /// No fields fixed - /// - None = 0x0, - - /// - /// All fields fixed - /// - All = 0xFFFFFFF, - - /// - /// Partial fields fixed - /// - /// - /// - /// This set of partial fields gives good performance. The following fields are fixed: - /// - /// - /// - /// - /// - /// - /// - /// - /// - Partial = Message | ThreadName | Exception | Domain | Properties, + public enum FixFlags + { + /// + /// Fix the MDC + /// + [Obsolete("Replaced by composite Properties")] + Mdc = 0x01, + + /// + /// Fix the NDC + /// + Ndc = 0x02, + + /// + /// Fix the rendered message + /// + Message = 0x04, + + /// + /// Fix the thread name + /// + ThreadName = 0x08, + + /// + /// Fix the callers location information + /// + /// + /// CAUTION: Very slow to generate + /// + LocationInfo = 0x10, + + /// + /// Fix the callers windows user name + /// + /// + /// CAUTION: Slow to generate + /// + UserName = 0x20, + + /// + /// Fix the domain friendly name + /// + Domain = 0x40, + + /// + /// Fix the callers principal name + /// + /// + /// CAUTION: May be slow to generate + /// + Identity = 0x80, + + /// + /// Fix the exception text + /// + Exception = 0x100, + + /// + /// Fix the event properties. Active properties must implement in order to be eligible for fixing. + /// + Properties = 0x200, + + /// + /// No fields fixed + /// + None = 0x0, + + /// + /// All fields fixed + /// + All = 0xFFFFFFF, + + /// + /// Partial fields fixed + /// + /// + /// + /// This set of partial fields gives good performance. The following fields are fixed: + /// + /// + /// + /// + /// + /// + /// + /// + /// + Partial = Message | ThreadName | Exception | Domain | Properties, } - /// - /// The internal representation of logging events. - /// - /// - /// - /// When an affirmative decision is made to log then a - /// instance is created. This instance - /// is passed around to the different log4net components. - /// - /// - /// This class is of concern to those wishing to extend log4net. - /// - /// - /// Some of the values in instances of - /// are considered volatile, that is the values are correct at the - /// time the event is delivered to appenders, but will not be consistent - /// at any time afterwards. If an event is to be stored and then processed - /// at a later time these volatile values must be fixed by calling - /// . There is a performance penalty - /// for incurred by calling but it - /// is essential to maintaining data consistency. - /// - /// - /// Nicko Cadell. - /// Gert Driesen. - /// Douglas de la Torre. - /// Daniel Cazzulino. -#if !NETCF - [Serializable] -#endif - public class LoggingEvent -#if !NETCF - : ISerializable -#endif - { + /// + /// The internal representation of logging events. + /// + /// + /// + /// When an affirmative decision is made to log then a + /// instance is created. This instance + /// is passed around to the different log4net components. + /// + /// + /// This class is of concern to those wishing to extend log4net. + /// + /// + /// Some of the values in instances of + /// are considered volatile, that is the values are correct at the + /// time the event is delivered to appenders, but will not be consistent + /// at any time afterwards. If an event is to be stored and then processed + /// at a later time these volatile values must be fixed by calling + /// . There is a performance penalty + /// for incurred by calling but it + /// is essential to maintaining data consistency. + /// + /// + /// Nicko Cadell + /// Gert Driesen + /// Douglas de la Torre + /// Daniel Cazzulino +#if !NETCF + [Serializable] +#endif + public class LoggingEvent +#if !NETCF + : ISerializable +#endif + { private static readonly Type declaringType = typeof(LoggingEvent); - /// - /// Initializes a new instance of the class - /// from the supplied parameters. - /// - /// The declaring type of the method that is - /// the stack boundary into the logging system for this call. - /// The repository this event is logged in. - /// The name of the logger of this event. - /// The level of this event. - /// The message of this event. - /// The exception for this event. - /// - /// - /// Except , and , - /// all fields of LoggingEvent are filled when actually needed. Call - /// to cache all data locally - /// to prevent inconsistencies. - /// - /// This method is called by the log4net framework - /// to create a logging event. - /// - /// - public LoggingEvent(Type callerStackBoundaryDeclaringType, log4net.Repository.ILoggerRepository repository, string loggerName, Level level, object message, Exception exception) - { - this.m_callerStackBoundaryDeclaringType = callerStackBoundaryDeclaringType; - this.m_message = message; - this.m_repository = repository; - this.m_thrownException = exception; - - this.m_data.LoggerName = loggerName; - this.m_data.Level = level; - - // Store the event creation time - this.m_data.TimeStampUtc = DateTime.UtcNow; - } - - /// - /// Initializes a new instance of the class - /// using specific data. - /// - /// The declaring type of the method that is - /// the stack boundary into the logging system for this call. - /// The repository this event is logged in. - /// Data used to initialize the logging event. - /// The fields in the struct that have already been fixed. - /// - /// - /// This constructor is provided to allow a - /// to be created independently of the log4net framework. This can - /// be useful if you require a custom serialization scheme. - /// - /// - /// Use the method to obtain an - /// instance of the class. - /// - /// - /// The parameter should be used to specify which fields in the - /// struct have been preset. Fields not specified in the - /// will be captured from the environment if requested or fixed. - /// - /// - public LoggingEvent(Type callerStackBoundaryDeclaringType, log4net.Repository.ILoggerRepository repository, LoggingEventData data, FixFlags fixedData) - { - this.m_callerStackBoundaryDeclaringType = callerStackBoundaryDeclaringType; - this.m_repository = repository; - - this.m_data = data; - this.m_fixFlags = fixedData; - } - - /// - /// Initializes a new instance of the class - /// using specific data. - /// - /// The declaring type of the method that is - /// the stack boundary into the logging system for this call. - /// The repository this event is logged in. - /// Data used to initialize the logging event. - /// - /// - /// This constructor is provided to allow a - /// to be created independently of the log4net framework. This can - /// be useful if you require a custom serialization scheme. - /// - /// - /// Use the method to obtain an - /// instance of the class. - /// - /// - /// This constructor sets this objects flags to , - /// this assumes that all the data relating to this event is passed in via the - /// parameter and no other data should be captured from the environment. - /// - /// - public LoggingEvent(Type callerStackBoundaryDeclaringType, log4net.Repository.ILoggerRepository repository, LoggingEventData data) - : this(callerStackBoundaryDeclaringType, repository, data, FixFlags.All) - { - } - - /// - /// Initializes a new instance of the class - /// using specific data. - /// - /// Data used to initialize the logging event. - /// - /// - /// This constructor is provided to allow a - /// to be created independently of the log4net framework. This can - /// be useful if you require a custom serialization scheme. - /// - /// - /// Use the method to obtain an - /// instance of the class. - /// - /// - /// This constructor sets this objects flags to , - /// this assumes that all the data relating to this event is passed in via the - /// parameter and no other data should be captured from the environment. - /// - /// - public LoggingEvent(LoggingEventData data) - : this(null, null, data) - { + /// + /// Initializes a new instance of the class + /// from the supplied parameters. + /// + /// The declaring type of the method that is + /// the stack boundary into the logging system for this call. + /// The repository this event is logged in. + /// The name of the logger of this event. + /// The level of this event. + /// The message of this event. + /// The exception for this event. + /// + /// + /// Except , and , + /// all fields of LoggingEvent are filled when actually needed. Call + /// to cache all data locally + /// to prevent inconsistencies. + /// + /// This method is called by the log4net framework + /// to create a logging event. + /// + /// + public LoggingEvent(Type callerStackBoundaryDeclaringType, + ILoggerRepository repository, + string loggerName, + Level level, + object message, + Exception exception) + { + this.m_callerStackBoundaryDeclaringType = callerStackBoundaryDeclaringType; + this.m_message = message; + this.m_repository = repository; + this.m_thrownException = exception; + + this.m_data.LoggerName = loggerName; + this.m_data.Level = level; + + // Store the event creation time + this.m_data.TimeStampUtc = DateTime.UtcNow; } -#if !(NETCF || NETSTANDARD1_3) - - /// - /// Initializes a new instance of the class. - /// Serialization constructor. - /// - /// The that holds the serialized object data. - /// The that contains contextual information about the source or destination. - /// - /// - /// Initializes a new instance of the class - /// with serialized data. - /// - /// - protected LoggingEvent(SerializationInfo info, StreamingContext context) - { - this.m_data.LoggerName = info.GetString("LoggerName"); - - // Note we are deserializing the whole level object. That is the - // name and the value. This value is correct for the source - // hierarchy but may not be for the target hierarchy that this - // event may be re-logged into. If it is to be re-logged it may - // be necessary to re-lookup the level based only on the name. - this.m_data.Level = (Level)info.GetValue("Level", typeof(Level)); - - this.m_data.Message = info.GetString("Message"); - this.m_data.ThreadName = info.GetString("ThreadName"); - this.m_data.TimeStampUtc = info.GetDateTime("TimeStamp").ToUniversalTime(); - this.m_data.LocationInfo = (LocationInfo)info.GetValue("LocationInfo", typeof(LocationInfo)); - this.m_data.UserName = info.GetString("UserName"); - this.m_data.ExceptionString = info.GetString("ExceptionString"); - this.m_data.Properties = (PropertiesDictionary)info.GetValue("Properties", typeof(PropertiesDictionary)); - this.m_data.Domain = info.GetString("Domain"); - this.m_data.Identity = info.GetString("Identity"); - - // We have restored all the values of this instance, i.e. all the values are fixed - // Set the fix flags otherwise the data values may be overwritten from the current environment. - this.m_fixFlags = FixFlags.All; + /// + /// Initializes a new instance of the class + /// using specific data. + /// + /// The declaring type of the method that is + /// the stack boundary into the logging system for this call. + /// The repository this event is logged in. + /// Data used to initialize the logging event. + /// The fields in the struct that have already been fixed. + /// + /// + /// This constructor is provided to allow a + /// to be created independently of the log4net framework. This can + /// be useful if you require a custom serialization scheme. + /// + /// + /// Use the method to obtain an + /// instance of the class. + /// + /// + /// The parameter should be used to specify which fields in the + /// struct have been preset. Fields not specified in the + /// will be captured from the environment if requested or fixed. + /// + /// + public LoggingEvent(Type callerStackBoundaryDeclaringType, + ILoggerRepository repository, + LoggingEventData data, + FixFlags fixedData) + { + this.m_callerStackBoundaryDeclaringType = callerStackBoundaryDeclaringType; + this.m_repository = repository; + + this.m_data = data; + this.m_fixFlags = fixedData; } -#endif - - /// - /// Gets the time when the current process started. - /// - /// - /// This is the time when this process started. - /// - /// - /// - /// The TimeStamp is stored internally in UTC and converted to the local time zone for this computer. - /// - /// - /// Tries to get the start time for the current process. - /// Failing that it returns the time of the first call to - /// this property. - /// - /// - /// Note that AppDomains may be loaded and unloaded within the - /// same process without the process terminating and therefore - /// without the process start time being reset. - /// - /// - public static DateTime StartTime - { - get { return SystemInfo.ProcessStartTimeUtc.ToLocalTime(); } - } - - /// - /// Gets the UTC time when the current process started. - /// - /// - /// This is the UTC time when this process started. - /// - /// - /// - /// Tries to get the start time for the current process. - /// Failing that it returns the time of the first call to - /// this property. - /// - /// - /// Note that AppDomains may be loaded and unloaded within the - /// same process without the process terminating and therefore - /// without the process start time being reset. - /// - /// - public static DateTime StartTimeUtc - { - get { return SystemInfo.ProcessStartTimeUtc; } - } - - /// - /// Gets the of the logging event. - /// - /// - /// The of the logging event. - /// - /// - /// - /// Gets the of the logging event. - /// - /// - public Level Level - { - get { return this.m_data.Level; } - } - - /// - /// Gets the time of the logging event. - /// - /// - /// The time of the logging event. - /// - /// - /// - /// The TimeStamp is stored in UTC and converted to the local time zone for this computer. - /// - /// - public DateTime TimeStamp - { - get { return this.m_data.TimeStampUtc.ToLocalTime(); } - } - - /// - /// Gets UTC the time of the logging event. - /// - /// - /// The UTC time of the logging event. - /// - public DateTime TimeStampUtc - { - get { return this.m_data.TimeStampUtc; } - } - - /// - /// Gets the name of the logger that logged the event. - /// - /// - /// The name of the logger that logged the event. - /// - /// - /// - /// Gets the name of the logger that logged the event. - /// - /// - public string LoggerName - { - get { return this.m_data.LoggerName; } - } - - /// - /// Gets the location information for this logging event. - /// - /// - /// The location information for this logging event. - /// - /// - /// - /// The collected information is cached for future use. - /// - /// - /// See the class for more information on - /// supported frameworks and the different behavior in Debug and - /// Release builds. - /// - /// - public LocationInfo LocationInformation - { - get - { - if (this.m_data.LocationInfo == null && this.m_cacheUpdatable) - { - this.m_data.LocationInfo = new LocationInfo(this.m_callerStackBoundaryDeclaringType); - } - - return this.m_data.LocationInfo; - } - } - - /// - /// Gets the message object used to initialize this event. - /// - /// - /// The message object used to initialize this event. - /// - /// - /// - /// Gets the message object used to initialize this event. - /// Note that this event may not have a valid message object. - /// If the event is serialized the message object will not - /// be transferred. To get the text of the message the - /// property must be used - /// not this property. - /// - /// - /// If there is no defined message object for this event then - /// null will be returned. - /// - /// - public object MessageObject - { - get { return this.m_message; } - } - - /// - /// Gets the exception object used to initialize this event. - /// - /// - /// The exception object used to initialize this event. - /// - /// - /// - /// Gets the exception object used to initialize this event. - /// Note that this event may not have a valid exception object. - /// If the event is serialized the exception object will not - /// be transferred. To get the text of the exception the - /// method must be used - /// not this property. - /// - /// - /// If there is no defined exception object for this event then - /// null will be returned. - /// - /// - public Exception ExceptionObject - { - get { return this.m_thrownException; } - } - - /// - /// Gets the that this event was created in. - /// - /// - /// - /// The that this event was created in. - /// - /// - public ILoggerRepository Repository - { - get { return this.m_repository; } - } - - /// - /// Ensure that the repository is set. - /// - /// the value for the repository. - internal void EnsureRepository(ILoggerRepository repository) - { - if (repository != null) - { - this.m_repository = repository; - } - } - - /// - /// Gets the message, rendered through the . - /// - /// - /// The message rendered through the . - /// - /// - /// - /// The collected information is cached for future use. - /// - /// - public string RenderedMessage - { - get - { - if (this.m_data.Message == null && this.m_cacheUpdatable) - { - if (this.m_message == null) - { - this.m_data.Message = string.Empty; - } - else if (this.m_message is string) - { - this.m_data.Message = this.m_message as string; - } - else if (this.m_repository != null) - { - this.m_data.Message = this.m_repository.RendererMap.FindAndRender(this.m_message); - } - else - { - // Very last resort - this.m_data.Message = this.m_message.ToString(); - } - } - - return this.m_data.Message; - } - } - - /// - /// Write the rendered message to a TextWriter. - /// - /// the writer to write the message to. - /// - /// - /// Unlike the property this method - /// does store the message data in the internal cache. Therefore - /// if called only once this method should be faster than the - /// property, however if the message is - /// to be accessed multiple times then the property will be more efficient. - /// - /// - public void WriteRenderedMessage(TextWriter writer) - { - if (this.m_data.Message != null) - { - writer.Write(this.m_data.Message); - } - else - { - if (this.m_message != null) - { - if (this.m_message is string) - { - writer.Write(this.m_message as string); - } - else if (this.m_repository != null) - { - this.m_repository.RendererMap.FindAndRender(this.m_message, writer); - } - else - { - // Very last resort - writer.Write(this.m_message.ToString()); - } - } - } - } - - /// - /// Gets the name of the current thread. - /// - /// - /// The name of the current thread, or the thread ID when - /// the name is not available. - /// - /// - /// - /// The collected information is cached for future use. - /// - /// - public string ThreadName - { - get - { - if (this.m_data.ThreadName == null && this.m_cacheUpdatable) - { -#if NETCF || NETSTANDARD1_3 - // Get thread ID only - m_data.ThreadName = SystemInfo.CurrentThreadId.ToString(System.Globalization.NumberFormatInfo.InvariantInfo); -#else - this.m_data.ThreadName = System.Threading.Thread.CurrentThread.Name; - if (this.m_data.ThreadName == null || this.m_data.ThreadName.Length == 0) - { - // The thread name is not available. Therefore we - // go the the AppDomain to get the ID of the - // current thread. (Why don't Threads know their own ID?) - try - { - this.m_data.ThreadName = SystemInfo.CurrentThreadId.ToString(System.Globalization.NumberFormatInfo.InvariantInfo); - } - catch (System.Security.SecurityException) - { - // This security exception will occur if the caller does not have - // some undefined set of SecurityPermission flags. - LogLog.Debug(declaringType, "Security exception while trying to get current thread ID. Error Ignored. Empty thread name."); - - // As a last resort use the hash code of the Thread object - this.m_data.ThreadName = System.Threading.Thread.CurrentThread.GetHashCode().ToString(System.Globalization.CultureInfo.InvariantCulture); - } - } -#endif - } - - return this.m_data.ThreadName; - } - } - - /// - /// Gets the name of the current user. - /// - /// - /// The name of the current user, or NOT AVAILABLE when the - /// underlying runtime has no support for retrieving the name of the - /// current user. - /// - /// - /// - /// Calls WindowsIdentity.GetCurrent().Name to get the name of - /// the current windows user. - /// - /// - /// To improve performance, we could cache the string representation of - /// the name, and reuse that as long as the identity stayed constant. - /// Once the identity changed, we would need to re-assign and re-render - /// the string. - /// - /// - /// However, the WindowsIdentity.GetCurrent() call seems to - /// return different objects every time, so the current implementation - /// doesn't do this type of caching. - /// - /// - /// Timing for these operations: - /// - /// - /// - /// Method - /// Results - /// - /// - /// WindowsIdentity.GetCurrent() - /// 10000 loops, 00:00:00.2031250 seconds - /// - /// - /// WindowsIdentity.GetCurrent().Name - /// 10000 loops, 00:00:08.0468750 seconds - /// - /// - /// - /// This means we could speed things up almost 40 times by caching the - /// value of the WindowsIdentity.GetCurrent().Name property, since - /// this takes (8.04-0.20) = 7.84375 seconds. - /// - /// - public string UserName - { - get - { - if (this.m_data.UserName == null && this.m_cacheUpdatable) - { -#if NETCF || SSCLI || NETSTANDARD1_3 // NETSTANDARD1_3 TODO requires platform-specific code - // On compact framework there's no notion of current Windows user - m_data.UserName = SystemInfo.NotAvailableText; -#else - try - { - WindowsIdentity windowsIdentity = WindowsIdentity.GetCurrent(); - if (windowsIdentity != null && windowsIdentity.Name != null) - { - this.m_data.UserName = windowsIdentity.Name; - } - else - { - this.m_data.UserName = string.Empty; - } - } - catch (System.Security.SecurityException) - { - // This security exception will occur if the caller does not have - // some undefined set of SecurityPermission flags. - LogLog.Debug(declaringType, "Security exception while trying to get current windows identity. Error Ignored. Empty user name."); - - this.m_data.UserName = string.Empty; - } -#endif - } - - return this.m_data.UserName; - } - } - - /// - /// Gets the identity of the current thread principal. - /// - /// - /// The string name of the identity of the current thread principal. - /// - /// - /// - /// Calls System.Threading.Thread.CurrentPrincipal.Identity.Name to get - /// the name of the current thread principal. - /// - /// - public string Identity - { - get - { - if (this.m_data.Identity == null && this.m_cacheUpdatable) - { -#if NETCF || SSCLI || NETSTANDARD1_3 - // On compact framework there's no notion of current thread principals - m_data.Identity = SystemInfo.NotAvailableText; -#else - try - { - if (System.Threading.Thread.CurrentPrincipal != null && - System.Threading.Thread.CurrentPrincipal.Identity != null && - System.Threading.Thread.CurrentPrincipal.Identity.Name != null) - { - this.m_data.Identity = System.Threading.Thread.CurrentPrincipal.Identity.Name; - } - else - { - this.m_data.Identity = string.Empty; - } - } - catch (ObjectDisposedException) - { - // This exception will occur if System.Threading.Thread.CurrentPrincipal.Identity is not null but - // the getter of the property Name tries to access disposed objects. - // Seen to happen on IIS 7 or greater with windows authentication. - LogLog.Debug(declaringType, "Object disposed exception while trying to get current thread principal. Error Ignored. Empty identity name."); - - this.m_data.Identity = string.Empty; - } - catch (System.Security.SecurityException) - { - // This security exception will occur if the caller does not have - // some undefined set of SecurityPermission flags. - LogLog.Debug(declaringType, "Security exception while trying to get current thread principal. Error Ignored. Empty identity name."); - - this.m_data.Identity = string.Empty; - } -#endif - } - - return this.m_data.Identity; - } - } - - /// - /// Gets the AppDomain friendly name. - /// - /// - /// The AppDomain friendly name. - /// - /// - /// - /// Gets the AppDomain friendly name. - /// - /// - public string Domain - { - get - { - if (this.m_data.Domain == null && this.m_cacheUpdatable) - { - this.m_data.Domain = SystemInfo.ApplicationFriendlyName; - } - - return this.m_data.Domain; - } - } - - /// - /// Gets additional event specific properties. - /// - /// - /// Additional event specific properties. - /// - /// - /// - /// A logger or an appender may attach additional - /// properties to specific events. These properties - /// have a string key and an object value. - /// - /// - /// This property is for events that have been added directly to - /// this event. The aggregate properties (which include these - /// event properties) can be retrieved using - /// and . - /// - /// - /// Once the properties have been fixed this property - /// returns the combined cached properties. This ensures that updates to - /// this property are always reflected in the underlying storage. When - /// returning the combined properties there may be more keys in the - /// Dictionary than expected. - /// - /// - public PropertiesDictionary Properties - { - get - { - // If we have cached properties then return that otherwise changes will be lost - if (this.m_data.Properties != null) - { - return this.m_data.Properties; - } - - if (this.m_eventProperties == null) - { - this.m_eventProperties = new PropertiesDictionary(); - } - - return this.m_eventProperties; - } - } - - /// - /// Gets or sets the fixed fields in this event. - /// - /// - /// The set of fields that are fixed in this event. - /// - /// - /// - /// Fields will not be fixed if they have previously been fixed. - /// It is not possible to 'unfix' a field. - /// - /// - public FixFlags Fix - { - get { return this.m_fixFlags; } - set { this.FixVolatileData(value); } + /// + /// Initializes a new instance of the class + /// using specific data. + /// + /// The declaring type of the method that is + /// the stack boundary into the logging system for this call. + /// The repository this event is logged in. + /// Data used to initialize the logging event. + /// + /// + /// This constructor is provided to allow a + /// to be created independently of the log4net framework. This can + /// be useful if you require a custom serialization scheme. + /// + /// + /// Use the method to obtain an + /// instance of the class. + /// + /// + /// This constructor sets this objects flags to , + /// this assumes that all the data relating to this event is passed in via the + /// parameter and no other data should be captured from the environment. + /// + /// + public LoggingEvent(Type callerStackBoundaryDeclaringType, + ILoggerRepository repository, + LoggingEventData data) : this(callerStackBoundaryDeclaringType, repository, data, FixFlags.All) + { + } + + /// + /// Initializes a new instance of the class + /// using specific data. + /// + /// Data used to initialize the logging event. + /// + /// + /// This constructor is provided to allow a + /// to be created independently of the log4net framework. This can + /// be useful if you require a custom serialization scheme. + /// + /// + /// Use the method to obtain an + /// instance of the class. + /// + /// + /// This constructor sets this objects flags to , + /// this assumes that all the data relating to this event is passed in via the + /// parameter and no other data should be captured from the environment. + /// + /// + public LoggingEvent(LoggingEventData data) : this(null, null, data) + { + } + +#if !NETCF + + /// + /// Serialization constructor + /// + /// The that holds the serialized object data. + /// The that contains contextual information about the source or destination. + /// + /// + /// Initializes a new instance of the class + /// with serialized data. + /// + /// + protected LoggingEvent(SerializationInfo info, StreamingContext context) + { + this.m_data.LoggerName = info.GetString("LoggerName"); + + // Note we are deserializing the whole level object. That is the + // name and the value. This value is correct for the source + // hierarchy but may not be for the target hierarchy that this + // event may be re-logged into. If it is to be re-logged it may + // be necessary to re-lookup the level based only on the name. + this.m_data.Level = (Level)info.GetValue("Level", typeof(Level)); + + this.m_data.Message = info.GetString("Message"); + this.m_data.ThreadName = info.GetString("ThreadName"); + this.m_data.TimeStampUtc = info.GetDateTime("TimeStamp").ToUniversalTime(); + this.m_data.LocationInfo = (LocationInfo)info.GetValue("LocationInfo", typeof(LocationInfo)); + this.m_data.UserName = info.GetString("UserName"); + this.m_data.ExceptionString = info.GetString("ExceptionString"); + this.m_data.Properties = (PropertiesDictionary)info.GetValue("Properties", typeof(PropertiesDictionary)); + this.m_data.Domain = info.GetString("Domain"); + this.m_data.Identity = info.GetString("Identity"); + + // We have restored all the values of this instance, i.e. all the values are fixed + // Set the fix flags otherwise the data values may be overwritten from the current environment. + this.m_fixFlags = FixFlags.All; + } + +#endif + + /// + /// Gets the time when the current process started. + /// + /// + /// This is the time when this process started. + /// + /// + /// + /// The TimeStamp is stored internally in UTC and converted to the local time zone for this computer. + /// + /// + /// Tries to get the start time for the current process. + /// Failing that it returns the time of the first call to + /// this property. + /// + /// + /// Note that AppDomains may be loaded and unloaded within the + /// same process without the process terminating and therefore + /// without the process start time being reset. + /// + /// + public static DateTime StartTime + { + get { return SystemInfo.ProcessStartTimeUtc.ToLocalTime(); } + } + + /// + /// Gets the UTC time when the current process started. + /// + /// + /// This is the UTC time when this process started. + /// + /// + /// + /// Tries to get the start time for the current process. + /// Failing that it returns the time of the first call to + /// this property. + /// + /// + /// Note that AppDomains may be loaded and unloaded within the + /// same process without the process terminating and therefore + /// without the process start time being reset. + /// + /// + public static DateTime StartTimeUtc + { + get { return SystemInfo.ProcessStartTimeUtc; } + } + + /// + /// Gets the of the logging event. + /// + /// + /// The of the logging event. + /// + /// + /// + /// Gets the of the logging event. + /// + /// + public Level Level + { + get { return this.m_data.Level; } + } + + /// + /// Gets the time of the logging event. + /// + /// + /// The time of the logging event. + /// + /// + /// + /// The TimeStamp is stored in UTC and converted to the local time zone for this computer. + /// + /// + public DateTime TimeStamp + { + get { return this.m_data.TimeStampUtc.ToLocalTime(); } + } + + /// + /// Gets UTC the time of the logging event. + /// + /// + /// The UTC time of the logging event. + /// + public DateTime TimeStampUtc + { + get { return this.m_data.TimeStampUtc; } + } + + /// + /// Gets the name of the logger that logged the event. + /// + /// + /// The name of the logger that logged the event. + /// + /// + /// + /// Gets the name of the logger that logged the event. + /// + /// + public string LoggerName + { + get { return this.m_data.LoggerName; } + } + + /// + /// Gets the location information for this logging event. + /// + /// + /// The location information for this logging event. + /// + /// + /// + /// The collected information is cached for future use. + /// + /// + /// See the class for more information on + /// supported frameworks and the different behavior in Debug and + /// Release builds. + /// + /// + public LocationInfo LocationInformation + { + get + { + if (this.m_data.LocationInfo == null && this.m_cacheUpdatable) + { + this.m_data.LocationInfo = new LocationInfo(this.m_callerStackBoundaryDeclaringType); + } + + return this.m_data.LocationInfo; + } } -#if !NETCF - - /// - /// Serializes this object into the provided. - /// - /// The to populate with data. - /// The destination for this serialization. - /// - /// - /// The data in this event must be fixed before it can be serialized. - /// - /// - /// The method must be called during the - /// method call if this event - /// is to be used outside that method. - /// - /// -#if NET_4_0 || MONO_4_0 || NETSTANDARD1_3 - [System.Security.SecurityCritical] -#else - [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.Demand, SerializationFormatter=true)] -#endif - public virtual void GetObjectData(SerializationInfo info, StreamingContext context) - { - // The caller must call FixVolatileData before this object - // can be serialized. - info.AddValue("LoggerName", this.m_data.LoggerName); - info.AddValue("Level", this.m_data.Level); - info.AddValue("Message", this.m_data.Message); - info.AddValue("ThreadName", this.m_data.ThreadName); - - // TODO: consider serializing UTC rather than local time. Not implemented here because it - // would give an unexpected result if client and server have different versions of this class. - // info.AddValue("TimeStamp", m_data.TimeStampUtc); -#pragma warning disable 618 - info.AddValue("TimeStamp", this.m_data.TimeStamp); -#pragma warning restore 618 - info.AddValue("LocationInfo", this.m_data.LocationInfo); - info.AddValue("UserName", this.m_data.UserName); - info.AddValue("ExceptionString", this.m_data.ExceptionString); - info.AddValue("Properties", this.m_data.Properties); - info.AddValue("Domain", this.m_data.Domain); - info.AddValue("Identity", this.m_data.Identity); + /// + /// Gets the message object used to initialize this event. + /// + /// + /// The message object used to initialize this event. + /// + /// + /// + /// Gets the message object used to initialize this event. + /// Note that this event may not have a valid message object. + /// If the event is serialized the message object will not + /// be transferred. To get the text of the message the + /// property must be used + /// not this property. + /// + /// + /// If there is no defined message object for this event then + /// null will be returned. + /// + /// + public object MessageObject + { + get { return this.m_message; } } -#endif - - /// - /// Gets the portable data for this . - /// - /// The for this event. - /// - /// - /// A new can be constructed using a - /// instance. - /// - /// - /// Does a fix of the data - /// in the logging event before returning the event data. - /// - /// - public LoggingEventData GetLoggingEventData() - { - return this.GetLoggingEventData(FixFlags.Partial); - } - - /// - /// Gets the portable data for this . - /// - /// The set of data to ensure is fixed in the LoggingEventData. - /// The for this event. - /// - /// - /// A new can be constructed using a - /// instance. - /// - /// - public LoggingEventData GetLoggingEventData(FixFlags fixFlags) - { - this.Fix = fixFlags; - return this.m_data; - } - - /// - /// Returns this event's exception's rendered using the - /// . - /// - /// - /// This event's exception's rendered using the . - /// - /// - /// - /// Obsolete. Use instead. - /// - /// - [Obsolete("Use GetExceptionString instead. Scheduled removal in v10.0.0.")] - public string GetExceptionStrRep() - { - return this.GetExceptionString(); - } - - /// - /// Returns this event's exception's rendered using the - /// . - /// - /// - /// This event's exception's rendered using the . - /// - /// - /// - /// Returns this event's exception's rendered using the - /// . - /// - /// - public string GetExceptionString() - { - if (this.m_data.ExceptionString == null && this.m_cacheUpdatable) - { - if (this.m_thrownException != null) - { - if (this.m_repository != null) - { - // Render exception using the repositories renderer map - this.m_data.ExceptionString = this.m_repository.RendererMap.FindAndRender(this.m_thrownException); - } - else - { - // Very last resort - this.m_data.ExceptionString = this.m_thrownException.ToString(); - } - } - else - { - this.m_data.ExceptionString = string.Empty; - } - } - - return this.m_data.ExceptionString; - } - - /// - /// Fix instance fields that hold volatile data. - /// - /// - /// - /// Some of the values in instances of - /// are considered volatile, that is the values are correct at the - /// time the event is delivered to appenders, but will not be consistent - /// at any time afterwards. If an event is to be stored and then processed - /// at a later time these volatile values must be fixed by calling - /// . There is a performance penalty - /// incurred by calling but it - /// is essential to maintaining data consistency. - /// - /// - /// Calling is equivalent to - /// calling passing the parameter - /// false. - /// - /// - /// See for more - /// information. - /// - /// - [Obsolete("Use Fix property. Scheduled removal in v10.0.0.")] - public void FixVolatileData() - { - this.Fix = FixFlags.All; - } - - /// - /// Fixes instance fields that hold volatile data. - /// - /// Set to true to not fix data that takes a long time to fix. - /// - /// - /// Some of the values in instances of - /// are considered volatile, that is the values are correct at the - /// time the event is delivered to appenders, but will not be consistent - /// at any time afterwards. If an event is to be stored and then processed - /// at a later time these volatile values must be fixed by calling - /// . There is a performance penalty - /// for incurred by calling but it - /// is essential to maintaining data consistency. - /// - /// - /// The param controls the data that - /// is fixed. Some of the data that can be fixed takes a long time to - /// generate, therefore if you do not require those settings to be fixed - /// they can be ignored by setting the param - /// to true. This setting will ignore the - /// and settings. - /// - /// - /// Set to false to ensure that all - /// settings are fixed. - /// - /// - [Obsolete("Use Fix property. Scheduled removal in v10.0.0.")] - public void FixVolatileData(bool fastButLoose) - { - if (fastButLoose) - { - this.Fix = FixFlags.Partial; - } - else - { - this.Fix = FixFlags.All; - } - } - - /// - /// Fix the fields specified by the parameter. - /// - /// the fields to fix. - /// - /// - /// Only fields specified in the will be fixed. - /// Fields will not be fixed if they have previously been fixed. - /// It is not possible to 'unfix' a field. - /// - /// - protected void FixVolatileData(FixFlags flags) - { - object forceCreation = null; - - // Unlock the cache so that new values can be stored - // This may not be ideal if we are no longer in the correct context - // and someone calls fix. - this.m_cacheUpdatable = true; - - // determine the flags that we are actually fixing - FixFlags updateFlags = (FixFlags)((flags ^ this.m_fixFlags) & flags); - - if (updateFlags > 0) - { - if ((updateFlags & FixFlags.Message) != 0) - { - // Force the message to be rendered - forceCreation = this.RenderedMessage; - - this.m_fixFlags |= FixFlags.Message; - } - - if ((updateFlags & FixFlags.ThreadName) != 0) - { - // Grab the thread name - forceCreation = this.ThreadName; - - this.m_fixFlags |= FixFlags.ThreadName; - } - - if ((updateFlags & FixFlags.LocationInfo) != 0) - { - // Force the location information to be loaded - forceCreation = this.LocationInformation; - - this.m_fixFlags |= FixFlags.LocationInfo; - } - - if ((updateFlags & FixFlags.UserName) != 0) - { - // Grab the user name - forceCreation = this.UserName; - - this.m_fixFlags |= FixFlags.UserName; - } - - if ((updateFlags & FixFlags.Domain) != 0) - { - // Grab the domain name - forceCreation = this.Domain; - - this.m_fixFlags |= FixFlags.Domain; - } - - if ((updateFlags & FixFlags.Identity) != 0) - { - // Grab the identity - forceCreation = this.Identity; - - this.m_fixFlags |= FixFlags.Identity; - } - - if ((updateFlags & FixFlags.Exception) != 0) - { - // Force the exception text to be loaded - forceCreation = this.GetExceptionString(); - - this.m_fixFlags |= FixFlags.Exception; - } - - if ((updateFlags & FixFlags.Properties) != 0) - { - this.CacheProperties(); - - this.m_fixFlags |= FixFlags.Properties; - } - } - - // avoid warning CS0219 - if (forceCreation != null) - { - } - - // Finaly lock everything we've cached. - this.m_cacheUpdatable = false; + /// + /// Gets the exception object used to initialize this event. + /// + /// + /// The exception object used to initialize this event. + /// + /// + /// + /// Gets the exception object used to initialize this event. + /// Note that this event may not have a valid exception object. + /// If the event is serialized the exception object will not + /// be transferred. To get the text of the exception the + /// method must be used + /// not this property. + /// + /// + /// If there is no defined exception object for this event then + /// null will be returned. + /// + /// + public Exception ExceptionObject + { + get { return this.m_thrownException; } } - private void CreateCompositeProperties() - { - CompositeProperties compositeProperties = new CompositeProperties(); - - if (this.m_eventProperties != null) - { - compositeProperties.Add(this.m_eventProperties); - } -#if !(NETCF || NETSTANDARD1_3) - PropertiesDictionary logicalThreadProperties = LogicalThreadContext.Properties.GetProperties(false); - if (logicalThreadProperties != null) - { - compositeProperties.Add(logicalThreadProperties); - } -#endif - PropertiesDictionary threadProperties = ThreadContext.Properties.GetProperties(false); - if (threadProperties != null) - { - compositeProperties.Add(threadProperties); - } - - // TODO: Add Repository Properties - - // event properties - PropertiesDictionary eventProperties = new PropertiesDictionary(); - eventProperties[UserNameProperty] = this.UserName; - eventProperties[IdentityProperty] = this.Identity; - compositeProperties.Add(eventProperties); - - compositeProperties.Add(GlobalContext.Properties.GetReadOnlyProperties()); - this.m_compositeProperties = compositeProperties; - } - - private void CacheProperties() - { - if (this.m_data.Properties == null && this.m_cacheUpdatable) - { - if (this.m_compositeProperties == null) - { - this.CreateCompositeProperties(); - } - - PropertiesDictionary flattenedProperties = this.m_compositeProperties.Flatten(); - - PropertiesDictionary fixedProperties = new PropertiesDictionary(); - - // Validate properties - foreach (DictionaryEntry entry in flattenedProperties) - { - string key = entry.Key as string; - - if (key != null) - { - object val = entry.Value; - - // Fix any IFixingRequired objects - IFixingRequired fixingRequired = val as IFixingRequired; - if (fixingRequired != null) - { - val = fixingRequired.GetFixedObject(); - } - - // Strip keys with null values - if (val != null) - { - fixedProperties[key] = val; - } - } - } - - this.m_data.Properties = fixedProperties; - } - } - - /// - /// Lookup a composite property in this event. - /// - /// the key for the property to lookup. - /// the value for the property. - /// - /// - /// This event has composite properties that combine together properties from - /// several different contexts in the following order: - /// - /// - /// this events properties - /// - /// This event has that can be set. These - /// properties are specific to this event only. - /// - /// - /// - /// the thread properties - /// - /// The that are set on the current - /// thread. These properties are shared by all events logged on this thread. - /// - /// - /// - /// the global properties - /// - /// The that are set globally. These - /// properties are shared by all the threads in the AppDomain. - /// - /// - /// - /// - /// - public object LookupProperty(string key) - { - if (this.m_data.Properties != null) - { - return this.m_data.Properties[key]; - } - - if (this.m_compositeProperties == null) - { - this.CreateCompositeProperties(); - } - - return this.m_compositeProperties[key]; - } - - /// - /// Get all the composite properties in this event. - /// - /// the containing all the properties. - /// - /// - /// See for details of the composite properties - /// stored by the event. - /// - /// - /// This method returns a single containing all the - /// properties defined for this event. - /// - /// - public PropertiesDictionary GetProperties() - { - if (this.m_data.Properties != null) - { - return this.m_data.Properties; - } - - if (this.m_compositeProperties == null) - { - this.CreateCompositeProperties(); - } - - return this.m_compositeProperties.Flatten(); + /// + /// The that this event was created in. + /// + /// + /// + /// The that this event was created in. + /// + /// + public ILoggerRepository Repository + { + get { return this.m_repository; } + } + + /// + /// Ensure that the repository is set. + /// + /// the value for the repository + internal void EnsureRepository(ILoggerRepository repository) + { + if (repository != null) + { + this.m_repository = repository; + } + } + + /// + /// Gets the message, rendered through the . + /// + /// + /// The message rendered through the . + /// + /// + /// + /// The collected information is cached for future use. + /// + /// + public string RenderedMessage + { + get + { + if (this.m_data.Message == null && this.m_cacheUpdatable) + { + if (this.m_message == null) + { + this.m_data.Message = string.Empty; + } + else if (this.m_message is string) + { + this.m_data.Message = (this.m_message as string); + } + else if (this.m_repository != null) + { + this.m_data.Message = this.m_repository.RendererMap.FindAndRender(this.m_message); + } + else + { + // Very last resort + this.m_data.Message = this.m_message.ToString(); + } + } + + return this.m_data.Message; + } } - /// - /// The internal logging event data. - /// - private LoggingEventData m_data; - - /// - /// The internal logging event data. - /// - private CompositeProperties m_compositeProperties; - - /// - /// The internal logging event data. - /// - private PropertiesDictionary m_eventProperties; - - /// - /// The fully qualified Type of the calling - /// logger class in the stack frame (i.e. the declaring type of the method). - /// - private readonly Type m_callerStackBoundaryDeclaringType; - - /// - /// The application supplied message of logging event. - /// - private readonly object m_message; - - /// - /// The exception that was thrown. - /// - /// - /// This is not serialized. The string representation - /// is serialized instead. - /// - private readonly Exception m_thrownException; - - /// - /// The repository that generated the logging event. - /// - /// - /// This is not serialized. - /// - private ILoggerRepository m_repository = null; - - /// - /// The fix state for this event. - /// - /// - /// These flags indicate which fields have been fixed. - /// Not serialized. - /// - private FixFlags m_fixFlags = FixFlags.None; - - /// - /// Indicated that the internal cache is updateable (ie not fixed). - /// - /// - /// This is a seperate flag to m_fixFlags as it allows incrementel fixing and simpler - /// changes in the caching strategy. - /// + /// + /// Write the rendered message to a TextWriter + /// + /// the writer to write the message to + /// + /// + /// Unlike the property this method + /// does store the message data in the internal cache. Therefore + /// if called only once this method should be faster than the + /// property, however if the message is + /// to be accessed multiple times then the property will be more efficient. + /// + /// + public void WriteRenderedMessage(TextWriter writer) + { + if (this.m_data.Message != null) + { + writer.Write(this.m_data.Message); + } + else + { + if (this.m_message != null) + { + if (this.m_message is string) + { + writer.Write(this.m_message as string); + } + else if (this.m_repository != null) + { + this.m_repository.RendererMap.FindAndRender(this.m_message, writer); + } + else + { + // Very last resort + writer.Write(this.m_message.ToString()); + } + } + } + } + + /// + /// Gets the name of the current thread. + /// + /// + /// The name of the current thread, or the thread ID when + /// the name is not available. + /// + /// + /// + /// The collected information is cached for future use. + /// + /// + public string ThreadName + { + get + { + if (this.m_data.ThreadName == null && this.m_cacheUpdatable) + { +#if NETCF + // Get thread ID only + m_data.ThreadName = + SystemInfo.CurrentThreadId.ToString(System.Globalization.NumberFormatInfo.InvariantInfo); +#else + // '.NET ThreadPool Worker' appears as a default thread pool name in .NET 6+. + // Prefer the numeric thread ID instead. + string threadName = System.Threading.Thread.CurrentThread.Name; + if (!string.IsNullOrEmpty(threadName) && threadName != ".NET ThreadPool Worker") + { + this.m_data.ThreadName = threadName; + } + else + { + // The thread name is not available or unsuitable. Therefore we + // go the the AppDomain to get the ID of the + // current thread. (Why don't Threads know their own ID?) + try + { + this.m_data.ThreadName = + SystemInfo.CurrentThreadId.ToString(System.Globalization.NumberFormatInfo + .InvariantInfo); + } + catch (SecurityException) + { + // This security exception will occur if the caller does not have + // some undefined set of SecurityPermission flags. + LogLog.Debug(declaringType, + "Security exception while trying to get current thread ID. Error Ignored. Empty thread name."); + + // As a last resort use the hash code of the Thread object + this.m_data.ThreadName = System.Threading.Thread.CurrentThread.GetHashCode() + .ToString(System.Globalization.CultureInfo.InvariantCulture); + } + } +#endif + } + + return this.m_data.ThreadName; + } + } + + /// + /// Gets the name of the current user. + /// + /// + /// The name of the current user, or NOT AVAILABLE when the + /// underlying runtime has no support for retrieving the name of the + /// current user. + /// + /// + /// + /// Calls WindowsIdentity.GetCurrent().Name to get the name of + /// the current windows user. + /// + /// + /// To improve performance, we could cache the string representation of + /// the name, and reuse that as long as the identity stayed constant. + /// Once the identity changed, we would need to re-assign and re-render + /// the string. + /// + /// + /// However, the WindowsIdentity.GetCurrent() call seems to + /// return different objects every time, so the current implementation + /// doesn't do this type of caching. + /// + /// + /// Timing for these operations: + /// + /// + /// + /// Method + /// Results + /// + /// + /// WindowsIdentity.GetCurrent() + /// 10000 loops, 00:00:00.2031250 seconds + /// + /// + /// WindowsIdentity.GetCurrent().Name + /// 10000 loops, 00:00:08.0468750 seconds + /// + /// + /// + /// This means we could speed things up almost 40 times by caching the + /// value of the WindowsIdentity.GetCurrent().Name property, since + /// this takes (8.04-0.20) = 7.84375 seconds. + /// + /// + public string UserName + { + get + { + if (this.m_data.UserName == null) + { + this.m_data.UserName = TryGetCurrentUserName() ?? SystemInfo.NotAvailableText; + } + + return this.m_data.UserName; + } + } + + private static string TryGetCurrentUserName() + { +#if (NETCF || SSCLI || NETSTANDARD1_3) + // On compact framework there's no notion of current Windows user + return SystemInfo.NotAvailableText; +#else + if (_platformDoesNotSupportWindowsIdentity) + { + // we've already received one PlatformNotSupportedException + // and it's highly unlikely that will change + return Environment.UserName; + } + + try + { + using (WindowsIdentity windowsIdentity = WindowsIdentity.GetCurrent()) + { + return windowsIdentity?.Name ?? string.Empty; + } + } + catch (PlatformNotSupportedException) + { + _platformDoesNotSupportWindowsIdentity = true; + return Environment.UserName; + } + catch (SecurityException) + { + // This security exception will occur if the caller does not have + // some undefined set of SecurityPermission flags. + LogLog.Debug( + declaringType, + "Security exception while trying to get current windows identity. Error Ignored." + ); + return Environment.UserName; + } + catch + { + return null; + } +#endif + } + +#if (NETCF || SSCLI || NETSTANDARD1_3) +#else + private static bool _platformDoesNotSupportWindowsIdentity; +#endif + + /// + /// Gets the identity of the current thread principal. + /// + /// + /// The string name of the identity of the current thread principal. + /// + /// + /// + /// Calls System.Threading.Thread.CurrentPrincipal.Identity.Name to get + /// the name of the current thread principal. + /// + /// + public string Identity + { + get + { + if (this.m_data.Identity == null && this.m_cacheUpdatable) + { +#if (NETCF || SSCLI || NETSTANDARD1_3) + // On compact framework there's no notion of current thread principals + m_data.Identity = SystemInfo.NotAvailableText; +#else + try + { + if (System.Threading.Thread.CurrentPrincipal != null && + System.Threading.Thread.CurrentPrincipal.Identity != null && + System.Threading.Thread.CurrentPrincipal.Identity.Name != null) + { + this.m_data.Identity = System.Threading.Thread.CurrentPrincipal.Identity.Name; + } + else + { + this.m_data.Identity = string.Empty; + } + } + catch (ObjectDisposedException) + { + // This exception will occur if System.Threading.Thread.CurrentPrincipal.Identity is not null but + // the getter of the property Name tries to access disposed objects. + // Seen to happen on IIS 7 or greater with windows authentication. + LogLog.Debug(declaringType, + "Object disposed exception while trying to get current thread principal. Error Ignored. Empty identity name."); + + this.m_data.Identity = string.Empty; + } + catch (SecurityException) + { + // This security exception will occur if the caller does not have + // some undefined set of SecurityPermission flags. + LogLog.Debug(declaringType, + "Security exception while trying to get current thread principal. Error Ignored. Empty identity name."); + + this.m_data.Identity = string.Empty; + } +#endif + } + + return this.m_data.Identity; + } + } + + /// + /// Gets the AppDomain friendly name. + /// + /// + /// The AppDomain friendly name. + /// + /// + /// + /// Gets the AppDomain friendly name. + /// + /// + public string Domain + { + get + { + if (this.m_data.Domain == null && this.m_cacheUpdatable) + { + this.m_data.Domain = SystemInfo.ApplicationFriendlyName; + } + + return this.m_data.Domain; + } + } + + /// + /// Additional event specific properties. + /// + /// + /// Additional event specific properties. + /// + /// + /// + /// A logger or an appender may attach additional + /// properties to specific events. These properties + /// have a string key and an object value. + /// + /// + /// This property is for events that have been added directly to + /// this event. The aggregate properties (which include these + /// event properties) can be retrieved using + /// and . + /// + /// + /// Once the properties have been fixed this property + /// returns the combined cached properties. This ensures that updates to + /// this property are always reflected in the underlying storage. When + /// returning the combined properties there may be more keys in the + /// Dictionary than expected. + /// + /// + public PropertiesDictionary Properties + { + get + { + // If we have cached properties then return that otherwise changes will be lost + if (this.m_data.Properties != null) + { + return this.m_data.Properties; + } + + if (this.m_eventProperties == null) + { + this.m_eventProperties = new PropertiesDictionary(); + } + + return this.m_eventProperties; + } + } + + /// + /// The fixed fields in this event + /// + /// + /// The set of fields that are fixed in this event + /// + /// + /// + /// Fields will not be fixed if they have previously been fixed. + /// It is not possible to 'unfix' a field. + /// + /// + public FixFlags Fix + { + get { return this.m_fixFlags; } + set { this.FixVolatileData(value); } + } + +#if !NETCF + + /// + /// Serializes this object into the provided. + /// + /// The to populate with data. + /// The destination for this serialization. + /// + /// + /// The data in this event must be fixed before it can be serialized. + /// + /// + /// The method must be called during the + /// method call if this event + /// is to be used outside that method. + /// + /// +#if NET_4_0 || MONO_4_0 || NETSTANDARD + [SecurityCritical] +#endif +#if !NETCF && !NETSTANDARD1_3 + [System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Demand, + SerializationFormatter = true)] +#endif + public virtual void GetObjectData(SerializationInfo info, StreamingContext context) + { + // The caller must call FixVolatileData before this object + // can be serialized. + + info.AddValue("LoggerName", this.m_data.LoggerName); + info.AddValue("Level", this.m_data.Level); + info.AddValue("Message", this.m_data.Message); + info.AddValue("ThreadName", this.m_data.ThreadName); + // TODO: consider serializing UTC rather than local time. Not implemented here because it + // would give an unexpected result if client and server have different versions of this class. + // info.AddValue("TimeStamp", m_data.TimeStampUtc); +#pragma warning disable 618 + info.AddValue("TimeStamp", this.m_data.TimeStamp); +#pragma warning restore 618 + info.AddValue("LocationInfo", this.m_data.LocationInfo); + info.AddValue("UserName", this.m_data.UserName); + info.AddValue("ExceptionString", this.m_data.ExceptionString); + info.AddValue("Properties", this.m_data.Properties); + info.AddValue("Domain", this.m_data.Domain); + info.AddValue("Identity", this.m_data.Identity); + } + +#endif + + /// + /// Gets the portable data for this . + /// + /// The for this event. + /// + /// + /// A new can be constructed using a + /// instance. + /// + /// + /// Does a fix of the data + /// in the logging event before returning the event data. + /// + /// + public LoggingEventData GetLoggingEventData() + { + return this.GetLoggingEventData(FixFlags.Partial); + } + + /// + /// Gets the portable data for this . + /// + /// The set of data to ensure is fixed in the LoggingEventData + /// The for this event. + /// + /// + /// A new can be constructed using a + /// instance. + /// + /// + public LoggingEventData GetLoggingEventData(FixFlags fixFlags) + { + this.Fix = fixFlags; + return this.m_data; + } + + /// + /// Returns this event's exception's rendered using the + /// . + /// + /// + /// This event's exception's rendered using the . + /// + /// + /// + /// Obsolete. Use instead. + /// + /// + [Obsolete("Use GetExceptionString instead")] + public string GetExceptionStrRep() + { + return this.GetExceptionString(); + } + + /// + /// Returns this event's exception's rendered using the + /// . + /// + /// + /// This event's exception's rendered using the . + /// + /// + /// + /// Returns this event's exception's rendered using the + /// . + /// + /// + public string GetExceptionString() + { + if (this.m_data.ExceptionString == null && this.m_cacheUpdatable) + { + if (this.m_thrownException != null) + { + if (this.m_repository != null) + { + // Render exception using the repositories renderer map + this.m_data.ExceptionString = this.m_repository.RendererMap.FindAndRender(this.m_thrownException); + } + else + { + // Very last resort + this.m_data.ExceptionString = this.m_thrownException.ToString(); + } + } + else + { + this.m_data.ExceptionString = string.Empty; + } + } + + return this.m_data.ExceptionString; + } + + /// + /// Fix instance fields that hold volatile data. + /// + /// + /// + /// Some of the values in instances of + /// are considered volatile, that is the values are correct at the + /// time the event is delivered to appenders, but will not be consistent + /// at any time afterwards. If an event is to be stored and then processed + /// at a later time these volatile values must be fixed by calling + /// . There is a performance penalty + /// incurred by calling but it + /// is essential to maintaining data consistency. + /// + /// + /// Calling is equivalent to + /// calling passing the parameter + /// false. + /// + /// + /// See for more + /// information. + /// + /// + [Obsolete("Use Fix property")] + public void FixVolatileData() + { + this.Fix = FixFlags.All; + } + + /// + /// Fixes instance fields that hold volatile data. + /// + /// Set to true to not fix data that takes a long time to fix. + /// + /// + /// Some of the values in instances of + /// are considered volatile, that is the values are correct at the + /// time the event is delivered to appenders, but will not be consistent + /// at any time afterwards. If an event is to be stored and then processed + /// at a later time these volatile values must be fixed by calling + /// . There is a performance penalty + /// for incurred by calling but it + /// is essential to maintaining data consistency. + /// + /// + /// The param controls the data that + /// is fixed. Some of the data that can be fixed takes a long time to + /// generate, therefore if you do not require those settings to be fixed + /// they can be ignored by setting the param + /// to true. This setting will ignore the + /// and settings. + /// + /// + /// Set to false to ensure that all + /// settings are fixed. + /// + /// + [Obsolete("Use Fix property")] + public void FixVolatileData(bool fastButLoose) + { + if (fastButLoose) + { + this.Fix = FixFlags.Partial; + } + else + { + this.Fix = FixFlags.All; + } + } + + /// + /// Fix the fields specified by the parameter + /// + /// the fields to fix + /// + /// + /// Only fields specified in the will be fixed. + /// Fields will not be fixed if they have previously been fixed. + /// It is not possible to 'unfix' a field. + /// + /// + protected void FixVolatileData(FixFlags flags) + { + object forceCreation = null; + + //Unlock the cache so that new values can be stored + //This may not be ideal if we are no longer in the correct context + //and someone calls fix. + this.m_cacheUpdatable = true; + + // determine the flags that we are actually fixing + var updateFlags = (FixFlags)((flags ^ this.m_fixFlags) & flags); + + if (updateFlags > 0) + { + if ((updateFlags & FixFlags.Message) != 0) + { + // Force the message to be rendered + forceCreation = this.RenderedMessage; + + this.m_fixFlags |= FixFlags.Message; + } + + if ((updateFlags & FixFlags.ThreadName) != 0) + { + // Grab the thread name + forceCreation = this.ThreadName; + + this.m_fixFlags |= FixFlags.ThreadName; + } + + if ((updateFlags & FixFlags.LocationInfo) != 0) + { + // Force the location information to be loaded + forceCreation = this.LocationInformation; + + this.m_fixFlags |= FixFlags.LocationInfo; + } + + if ((updateFlags & FixFlags.UserName) != 0) + { + // Grab the user name + forceCreation = this.UserName; + + this.m_fixFlags |= FixFlags.UserName; + } + + if ((updateFlags & FixFlags.Domain) != 0) + { + // Grab the domain name + forceCreation = this.Domain; + + this.m_fixFlags |= FixFlags.Domain; + } + + if ((updateFlags & FixFlags.Identity) != 0) + { + // Grab the identity + forceCreation = this.Identity; + + this.m_fixFlags |= FixFlags.Identity; + } + + if ((updateFlags & FixFlags.Exception) != 0) + { + // Force the exception text to be loaded + forceCreation = this.GetExceptionString(); + + this.m_fixFlags |= FixFlags.Exception; + } + + if ((updateFlags & FixFlags.Properties) != 0) + { + this.CacheProperties(); + + this.m_fixFlags |= FixFlags.Properties; + } + } + + // avoid warning CS0219 + if (forceCreation != null) + { + } + + //Finaly lock everything we've cached. + this.m_cacheUpdatable = false; + } + + private void CreateCompositeProperties() + { + var compositeProperties = new CompositeProperties(); + + if (this.m_eventProperties != null) + { + compositeProperties.Add(this.m_eventProperties); + } +#if !NETCF + var logicalThreadProperties = LogicalThreadContext.Properties.GetProperties(false); + if (logicalThreadProperties != null) + { + compositeProperties.Add(logicalThreadProperties); + } +#endif + var threadProperties = ThreadContext.Properties.GetProperties(false); + if (threadProperties != null) + { + compositeProperties.Add(threadProperties); + } + + // TODO: Add Repository Properties + + // event properties + var eventProperties = new PropertiesDictionary(); + eventProperties[UserNameProperty] = this.UserName; + eventProperties[IdentityProperty] = this.Identity; + compositeProperties.Add(eventProperties); + + compositeProperties.Add(GlobalContext.Properties.GetReadOnlyProperties()); + this.m_compositeProperties = compositeProperties; + } + + private void CacheProperties() + { + if (this.m_data.Properties == null && this.m_cacheUpdatable) + { + if (this.m_compositeProperties == null) + { + this.CreateCompositeProperties(); + } + + var flattenedProperties = this.m_compositeProperties.Flatten(); + + var fixedProperties = new PropertiesDictionary(); + + // Validate properties + foreach (DictionaryEntry entry in flattenedProperties) + { + var key = entry.Key as string; + + if (key != null) + { + var val = entry.Value; + + // Fix any IFixingRequired objects + var fixingRequired = val as IFixingRequired; + if (fixingRequired != null) + { + val = fixingRequired.GetFixedObject(); + } + + // Strip keys with null values + if (val != null) + { + fixedProperties[key] = val; + } + } + } + + this.m_data.Properties = fixedProperties; + } + } + + /// + /// Lookup a composite property in this event + /// + /// the key for the property to lookup + /// the value for the property + /// + /// + /// This event has composite properties that combine together properties from + /// several different contexts in the following order: + /// + /// + /// this events properties + /// + /// This event has that can be set. These + /// properties are specific to this event only. + /// + /// + /// + /// the thread properties + /// + /// The that are set on the current + /// thread. These properties are shared by all events logged on this thread. + /// + /// + /// + /// the global properties + /// + /// The that are set globally. These + /// properties are shared by all the threads in the AppDomain. + /// + /// + /// + /// + /// + public object LookupProperty(string key) + { + if (this.m_data.Properties != null) + { + return this.m_data.Properties[key]; + } + + if (this.m_compositeProperties == null) + { + this.CreateCompositeProperties(); + } + + return this.m_compositeProperties[key]; + } + + /// + /// Get all the composite properties in this event + /// + /// the containing all the properties + /// + /// + /// See for details of the composite properties + /// stored by the event. + /// + /// + /// This method returns a single containing all the + /// properties defined for this event. + /// + /// + public PropertiesDictionary GetProperties() + { + if (this.m_data.Properties != null) + { + return this.m_data.Properties; + } + + if (this.m_compositeProperties == null) + { + this.CreateCompositeProperties(); + } + + return this.m_compositeProperties.Flatten(); + } + + /// + /// The internal logging event data. + /// + private LoggingEventData m_data; + + /// + /// The internal logging event data. + /// + private CompositeProperties m_compositeProperties; + + /// + /// The internal logging event data. + /// + private PropertiesDictionary m_eventProperties; + + /// + /// The fully qualified Type of the calling + /// logger class in the stack frame (i.e. the declaring type of the method). + /// + private readonly Type m_callerStackBoundaryDeclaringType; + + /// + /// The application supplied message of logging event. + /// + private readonly object m_message; + + /// + /// The exception that was thrown. + /// + /// + /// This is not serialized. The string representation + /// is serialized instead. + /// + private readonly Exception m_thrownException; + + /// + /// The repository that generated the logging event + /// + /// + /// This is not serialized. + /// + private ILoggerRepository m_repository = null; + + /// + /// The fix state for this event + /// + /// + /// These flags indicate which fields have been fixed. + /// Not serialized. + /// + private FixFlags m_fixFlags = FixFlags.None; + + /// + /// Indicated that the internal cache is updateable (ie not fixed) + /// + /// + /// This is a seperate flag to m_fixFlags as it allows incrementel fixing and simpler + /// changes in the caching strategy. + /// private bool m_cacheUpdatable = true; - /// - /// The key into the Properties map for the host name value. - /// - public const string HostNameProperty = "log4net:HostName"; - - /// - /// The key into the Properties map for the thread identity value. - /// - public const string IdentityProperty = "log4net:Identity"; - - /// - /// The key into the Properties map for the user name value. - /// + /// + /// The key into the Properties map for the host name value. + /// + public const string HostNameProperty = "log4net:HostName"; + + /// + /// The key into the Properties map for the thread identity value. + /// + public const string IdentityProperty = "log4net:Identity"; + + /// + /// The key into the Properties map for the user name value. + /// public const string UserNameProperty = "log4net:UserName"; - } -} + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Core/MethodItem.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Core/MethodItem.cs index d258747cb83..0364195a6f4 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Core/MethodItem.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Core/MethodItem.cs @@ -1,161 +1,156 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.Core -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; - using System.Collections; - using System.Text; +using System; +using System.Collections; - using log4net.Util; +using log4net.Util; - /// - /// provides method information without actually referencing a System.Reflection.MethodBase - /// as that would require that the containing assembly is loaded. - /// - /// -#if !NETCF - [Serializable] -#endif - public class MethodItem +namespace log4net.Core +{ + /// + /// provides method information without actually referencing a System.Reflection.MethodBase + /// as that would require that the containing assembly is loaded. + /// + /// +#if !NETCF + [Serializable] +#endif + public class MethodItem { /// - /// Initializes a new instance of the class. - /// constructs a method item for an unknown method. - /// - public MethodItem() - { - this.m_name = NA; - this.m_parameters = new string[0]; + /// constructs a method item for an unknown method. + /// + public MethodItem() + { + this.m_name = NA; + this.m_parameters = new string[0]; } /// - /// Initializes a new instance of the class. - /// constructs a method item from the name of the method. - /// - /// - public MethodItem(string name) - : this() - { - this.m_name = name; + /// constructs a method item from the name of the method. + /// + /// + public MethodItem(string name) + : this() + { + this.m_name = name; } /// - /// Initializes a new instance of the class. - /// constructs a method item from the name of the method and its parameters. - /// - /// - /// - public MethodItem(string name, string[] parameters) - : this(name) - { - this.m_parameters = parameters; + /// constructs a method item from the name of the method and its parameters. + /// + /// + /// + public MethodItem(string name, string[] parameters) + : this(name) + { + this.m_parameters = parameters; } /// - /// Initializes a new instance of the class. - /// constructs a method item from a method base by determining the method name and its parameters. - /// - /// - public MethodItem(System.Reflection.MethodBase methodBase) - : this(methodBase.Name, GetMethodParameterNames(methodBase)) - { + /// constructs a method item from a method base by determining the method name and its parameters. + /// + /// + public MethodItem(System.Reflection.MethodBase methodBase) + : this(methodBase.Name, GetMethodParameterNames(methodBase)) + { } - private static string[] GetMethodParameterNames(System.Reflection.MethodBase methodBase) - { - ArrayList methodParameterNames = new ArrayList(); - try - { - System.Reflection.ParameterInfo[] methodBaseGetParameters = methodBase.GetParameters(); - - int methodBaseGetParametersCount = methodBaseGetParameters.GetUpperBound(0); - - for (int i = 0; i <= methodBaseGetParametersCount; i++) - { - methodParameterNames.Add(methodBaseGetParameters[i].ParameterType + " " + methodBaseGetParameters[i].Name); - } - } - catch (Exception ex) - { - LogLog.Error(declaringType, "An exception ocurred while retreiving method parameters.", ex); - } - - return (string[])methodParameterNames.ToArray(typeof(string)); + private static string[] GetMethodParameterNames(System.Reflection.MethodBase methodBase) + { + ArrayList methodParameterNames = new ArrayList(); + try + { + System.Reflection.ParameterInfo[] methodBaseGetParameters = methodBase.GetParameters(); + + int methodBaseGetParametersCount = methodBaseGetParameters.GetUpperBound(0); + + for (int i = 0; i <= methodBaseGetParametersCount; i++) + { + methodParameterNames.Add(methodBaseGetParameters[i].ParameterType + " " + methodBaseGetParameters[i].Name); + } + } + catch (Exception ex) + { + LogLog.Error(declaringType, "An exception ocurred while retreiving method parameters.", ex); + } + + return (string[])methodParameterNames.ToArray(typeof(string)); + } + + /// + /// Gets the method name of the caller making the logging + /// request. + /// + /// + /// The method name of the caller making the logging + /// request. + /// + /// + /// + /// Gets the method name of the caller making the logging + /// request. + /// + /// + public string Name + { + get { return this.m_name; } } - /// - /// Gets the method name of the caller making the logging - /// request. - /// - /// - /// The method name of the caller making the logging - /// request. - /// - /// - /// - /// Gets the method name of the caller making the logging - /// request. - /// - /// - public string Name - { - get { return this.m_name; } - } - - /// - /// Gets the method parameters of the caller making - /// the logging request. - /// - /// - /// The method parameters of the caller making - /// the logging request. - /// - /// - /// - /// Gets the method parameters of the caller making - /// the logging request. - /// - /// - public string[] Parameters - { - get { return this.m_parameters; } + /// + /// Gets the method parameters of the caller making + /// the logging request. + /// + /// + /// The method parameters of the caller making + /// the logging request + /// + /// + /// + /// Gets the method parameters of the caller making + /// the logging request. + /// + /// + public string[] Parameters + { + get { return this.m_parameters; } } - private readonly string m_name; + private readonly string m_name; private readonly string[] m_parameters; - /// - /// The fully qualified type of the StackFrameItem class. - /// - /// - /// Used by the internal logger to record the Type of the - /// log message. - /// - private static readonly Type declaringType = typeof(MethodItem); - - /// - /// When location information is not available the constant - /// NA is returned. Current value of this string - /// constant is ?. - /// + /// + /// The fully qualified type of the StackFrameItem class. + /// + /// + /// Used by the internal logger to record the Type of the + /// log message. + /// + private static readonly Type declaringType = typeof(MethodItem); + + /// + /// When location information is not available the constant + /// NA is returned. Current value of this string + /// constant is ?. + /// private const string NA = "?"; - } -} + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Core/SecurityContext.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Core/SecurityContext.cs index b4a42c6c818..74d5e7676a2 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Core/SecurityContext.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Core/SecurityContext.cs @@ -1,56 +1,56 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.Core -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; +using System; - /// - /// A SecurityContext used by log4net when interacting with protected resources. - /// - /// - /// - /// A SecurityContext used by log4net when interacting with protected resources - /// for example with operating system services. This can be used to impersonate - /// a principal that has been granted privileges on the system resources. - /// - /// - /// Nicko Cadell. - public abstract class SecurityContext - { - /// - /// Impersonate this SecurityContext. - /// - /// State supplied by the caller. - /// An instance that will - /// revoke the impersonation of this SecurityContext, or null. - /// - /// - /// Impersonate this security context. Further calls on the current - /// thread should now be made in the security context provided - /// by this object. When the result - /// method is called the security - /// context of the thread should be reverted to the state it was in - /// before was called. - /// - /// - public abstract IDisposable Impersonate(object state); - } -} +namespace log4net.Core +{ + /// + /// A SecurityContext used by log4net when interacting with protected resources + /// + /// + /// + /// A SecurityContext used by log4net when interacting with protected resources + /// for example with operating system services. This can be used to impersonate + /// a principal that has been granted privileges on the system resources. + /// + /// + /// Nicko Cadell + public abstract class SecurityContext + { + /// + /// Impersonate this SecurityContext + /// + /// State supplied by the caller + /// An instance that will + /// revoke the impersonation of this SecurityContext, or null + /// + /// + /// Impersonate this security context. Further calls on the current + /// thread should now be made in the security context provided + /// by this object. When the result + /// method is called the security + /// context of the thread should be reverted to the state it was in + /// before was called. + /// + /// + public abstract IDisposable Impersonate(object state); + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Core/SecurityContextProvider.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Core/SecurityContextProvider.cs index 5c8a082908b..e5bc8285e81 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Core/SecurityContextProvider.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Core/SecurityContextProvider.cs @@ -1,126 +1,125 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.Core -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; +using System; - using log4net.Util; +using log4net.Util; - /// - /// The providers default instances. - /// - /// - /// - /// A configured component that interacts with potentially protected system - /// resources uses a to provide the elevated - /// privileges required. If the object has - /// been not been explicitly provided to the component then the component - /// will request one from this . - /// - /// - /// By default the is - /// an instance of which returns only - /// objects. This is a reasonable default - /// where the privileges required are not know by the system. - /// - /// - /// This default behavior can be overridden by subclassing the - /// and overriding the method to return - /// the desired objects. The default provider - /// can be replaced by programmatically setting the value of the - /// property. - /// - /// - /// An alternative is to use the log4net.Config.SecurityContextProviderAttribute - /// This attribute can be applied to an assembly in the same way as the - /// log4net.Config.XmlConfiguratorAttribute". The attribute takes - /// the type to use as the as an argument. - /// - /// - /// Nicko Cadell. - public class SecurityContextProvider - { - /// - /// The default provider. - /// - private static SecurityContextProvider s_defaultProvider = new SecurityContextProvider(); - - /// - /// Gets or sets the default SecurityContextProvider. - /// - /// - /// The default SecurityContextProvider. - /// - /// - /// - /// The default provider is used by configured components that - /// require a and have not had one - /// given to them. - /// - /// - /// By default this is an instance of - /// that returns objects. - /// - /// - /// The default provider can be set programmatically by setting - /// the value of this property to a sub class of - /// that has the desired behavior. - /// - /// - public static SecurityContextProvider DefaultProvider - { - get { return s_defaultProvider; } - set { s_defaultProvider = value; } +namespace log4net.Core +{ + /// + /// The providers default instances. + /// + /// + /// + /// A configured component that interacts with potentially protected system + /// resources uses a to provide the elevated + /// privileges required. If the object has + /// been not been explicitly provided to the component then the component + /// will request one from this . + /// + /// + /// By default the is + /// an instance of which returns only + /// objects. This is a reasonable default + /// where the privileges required are not know by the system. + /// + /// + /// This default behavior can be overridden by subclassing the + /// and overriding the method to return + /// the desired objects. The default provider + /// can be replaced by programmatically setting the value of the + /// property. + /// + /// + /// An alternative is to use the log4net.Config.SecurityContextProviderAttribute + /// This attribute can be applied to an assembly in the same way as the + /// log4net.Config.XmlConfiguratorAttribute". The attribute takes + /// the type to use as the as an argument. + /// + /// + /// Nicko Cadell + public class SecurityContextProvider + { + /// + /// The default provider + /// + private static SecurityContextProvider s_defaultProvider = new SecurityContextProvider(); + + /// + /// Gets or sets the default SecurityContextProvider + /// + /// + /// The default SecurityContextProvider + /// + /// + /// + /// The default provider is used by configured components that + /// require a and have not had one + /// given to them. + /// + /// + /// By default this is an instance of + /// that returns objects. + /// + /// + /// The default provider can be set programmatically by setting + /// the value of this property to a sub class of + /// that has the desired behavior. + /// + /// + public static SecurityContextProvider DefaultProvider + { + get { return s_defaultProvider; } + set { s_defaultProvider = value; } } /// - /// Initializes a new instance of the class. - /// Protected default constructor to allow subclassing. - /// - /// - /// - /// Protected default constructor to allow subclassing. - /// - /// - protected SecurityContextProvider() - { - } - - /// - /// Create a SecurityContext for a consumer. - /// - /// The consumer requesting the SecurityContext. - /// An impersonation context. - /// - /// - /// The default implementation is to return a . - /// - /// - /// Subclasses should override this method to provide their own - /// behavior. - /// - /// - public virtual SecurityContext CreateSecurityContext(object consumer) - { - return NullSecurityContext.Instance; - } - } -} + /// Protected default constructor to allow subclassing + /// + /// + /// + /// Protected default constructor to allow subclassing + /// + /// + protected SecurityContextProvider() + { + } + + /// + /// Create a SecurityContext for a consumer + /// + /// The consumer requesting the SecurityContext + /// An impersonation context + /// + /// + /// The default implementation is to return a . + /// + /// + /// Subclasses should override this method to provide their own + /// behavior. + /// + /// + public virtual SecurityContext CreateSecurityContext(object consumer) + { + return NullSecurityContext.Instance; + } + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Core/StackFrameItem.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Core/StackFrameItem.cs index 92930ff63b6..e0455f7bfa1 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Core/StackFrameItem.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Core/StackFrameItem.cs @@ -1,187 +1,184 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -#if !NETCF -// +// // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at -// +// // http://www.apache.org/licenses/LICENSE-2.0 -// +// // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. -// -using System; -using System.Diagnostics; -using System.Reflection; -using System.Text; +// -using log4net.Util; - -namespace log4net.Core -{ - /// - /// provides stack frame information without actually referencing a System.Diagnostics.StackFrame - /// as that would require that the containing assembly is loaded. - /// - /// - [Serializable] - public class StackFrameItem +#if !NETCF +using System; +using System.Diagnostics; +using System.Reflection; +using log4net.Util; + +namespace log4net.Core +{ + /// + /// provides stack frame information without actually referencing a System.Diagnostics.StackFrame + /// as that would require that the containing assembly is loaded. + /// + /// + [Serializable] + public class StackFrameItem { /// - /// Initializes a new instance of the class. - /// returns a stack frame item from a stack frame. This. - /// - /// - /// - public StackFrameItem(StackFrame frame) - { - // set default values - this.m_lineNumber = NA; - this.m_fileName = NA; - this.m_method = new MethodItem(); - this.m_className = NA; - - try - { - // get frame values - this.m_lineNumber = frame.GetFileLineNumber().ToString(System.Globalization.NumberFormatInfo.InvariantInfo); - this.m_fileName = frame.GetFileName(); + /// returns a stack frame item from a stack frame. This + /// + /// + /// + public StackFrameItem(StackFrame frame) + { + // set default values + this.m_lineNumber = NA; + this.m_fileName = NA; + this.m_method = new MethodItem(); + this.m_className = NA; - // get method values - MethodBase method = frame.GetMethod(); - if (method != null) - { - if (method.DeclaringType != null) + try + { + // get frame values + this.m_lineNumber = frame.GetFileLineNumber().ToString(System.Globalization.NumberFormatInfo.InvariantInfo); + this.m_fileName = frame.GetFileName(); + // get method values + MethodBase method = frame.GetMethod(); + if (method != null) + { + if(method.DeclaringType != null) { this.m_className = method.DeclaringType.FullName; } - this.m_method = new MethodItem(method); - } - } - catch (Exception ex) - { - LogLog.Error(declaringType, "An exception ocurred while retreiving stack frame information.", ex); - } - - // set full info - this.m_fullInfo = this.m_className + '.' + this.m_method.Name + '(' + this.m_fileName + ':' + this.m_lineNumber + ')'; + this.m_method = new MethodItem(method); + } + } + catch (Exception ex) + { + LogLog.Error(declaringType, "An exception ocurred while retreiving stack frame information.", ex); + } + + // set full info + this.m_fullInfo = this.m_className + '.' + this.m_method.Name + '(' + this.m_fileName + ':' + this.m_lineNumber + ')'; + } + + /// + /// Gets the fully qualified class name of the caller making the logging + /// request. + /// + /// + /// The fully qualified class name of the caller making the logging + /// request. + /// + /// + /// + /// Gets the fully qualified class name of the caller making the logging + /// request. + /// + /// + public string ClassName + { + get { return this.m_className; } + } + + /// + /// Gets the file name of the caller. + /// + /// + /// The file name of the caller. + /// + /// + /// + /// Gets the file name of the caller. + /// + /// + public string FileName + { + get { return this.m_fileName; } + } + + /// + /// Gets the line number of the caller. + /// + /// + /// The line number of the caller. + /// + /// + /// + /// Gets the line number of the caller. + /// + /// + public string LineNumber + { + get { return this.m_lineNumber; } } - /// - /// Gets the fully qualified class name of the caller making the logging - /// request. - /// - /// - /// The fully qualified class name of the caller making the logging - /// request. - /// - /// - /// - /// Gets the fully qualified class name of the caller making the logging - /// request. - /// - /// - public string ClassName - { - get { return this.m_className; } - } - - /// - /// Gets the file name of the caller. - /// - /// - /// The file name of the caller. - /// - /// - /// - /// Gets the file name of the caller. - /// - /// - public string FileName - { - get { return this.m_fileName; } - } - - /// - /// Gets the line number of the caller. - /// - /// - /// The line number of the caller. - /// - /// - /// - /// Gets the line number of the caller. - /// - /// - public string LineNumber - { - get { return this.m_lineNumber; } - } - - /// - /// Gets the method name of the caller. - /// - /// - /// The method name of the caller. - /// - /// - /// - /// Gets the method name of the caller. - /// - /// - public MethodItem Method - { - get { return this.m_method; } - } - - /// - /// Gets all available caller information. - /// - /// - /// All available caller information, in the format - /// fully.qualified.classname.of.caller.methodName(Filename:line). - /// - /// - /// - /// Gets all available caller information, in the format - /// fully.qualified.classname.of.caller.methodName(Filename:line). - /// - /// - public string FullInfo - { - get { return this.m_fullInfo; } + /// + /// Gets the method name of the caller. + /// + /// + /// The method name of the caller. + /// + /// + /// + /// Gets the method name of the caller. + /// + /// + public MethodItem Method + { + get { return this.m_method; } } - private readonly string m_lineNumber; - private readonly string m_fileName; - private readonly string m_className; - private readonly string m_fullInfo; + /// + /// Gets all available caller information + /// + /// + /// All available caller information, in the format + /// fully.qualified.classname.of.caller.methodName(Filename:line) + /// + /// + /// + /// Gets all available caller information, in the format + /// fully.qualified.classname.of.caller.methodName(Filename:line) + /// + /// + public string FullInfo + { + get { return this.m_fullInfo; } + } + + private readonly string m_lineNumber; + private readonly string m_fileName; + private readonly string m_className; + private readonly string m_fullInfo; private readonly MethodItem m_method; - /// - /// The fully qualified type of the StackFrameItem class. - /// - /// - /// Used by the internal logger to record the Type of the - /// log message. - /// - private static readonly Type declaringType = typeof(StackFrameItem); - - /// - /// When location information is not available the constant - /// NA is returned. Current value of this string - /// constant is ?. - /// + /// + /// The fully qualified type of the StackFrameItem class. + /// + /// + /// Used by the internal logger to record the Type of the + /// log message. + /// + private static readonly Type declaringType = typeof(StackFrameItem); + + /// + /// When location information is not available the constant + /// NA is returned. Current value of this string + /// constant is ?. + /// private const string NA = "?"; - } -} -#endif + } +} +#endif diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Core/TimeEvaluator.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Core/TimeEvaluator.cs index 4718deb8092..6fa2d7b72cc 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Core/TimeEvaluator.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Core/TimeEvaluator.cs @@ -1,154 +1,152 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.Core -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; +using System; - /// - /// An evaluator that triggers after specified number of seconds. - /// - /// - /// - /// This evaluator will trigger if the specified time period - /// has passed since last check. - /// - /// - /// Robert Sevcik. - public class TimeEvaluator : ITriggeringEventEvaluator - { - /// - /// The time threshold for triggering in seconds. Zero means it won't trigger at all. - /// - private int m_interval; - - /// - /// The UTC time of last check. This gets updated when the object is created and when the evaluator triggers. - /// - private DateTime m_lastTimeUtc; - - /// - /// The default time threshold for triggering in seconds. Zero means it won't trigger at all. - /// - private const int DEFAULT_INTERVAL = 0; +namespace log4net.Core +{ + /// + /// An evaluator that triggers after specified number of seconds. + /// + /// + /// + /// This evaluator will trigger if the specified time period + /// has passed since last check. + /// + /// + /// Robert Sevcik + public class TimeEvaluator : ITriggeringEventEvaluator + { + /// + /// The time threshold for triggering in seconds. Zero means it won't trigger at all. + /// + private int m_interval; + + /// + /// The UTC time of last check. This gets updated when the object is created and when the evaluator triggers. + /// + private DateTime m_lastTimeUtc; + + /// + /// The default time threshold for triggering in seconds. Zero means it won't trigger at all. + /// + const int DEFAULT_INTERVAL = 0; + + /// + /// Create a new evaluator using the time threshold in seconds. + /// + /// + /// + /// Create a new evaluator using the time threshold in seconds. + /// + /// + /// This evaluator will trigger if the specified time period + /// has passed since last check. + /// + /// + public TimeEvaluator() + : this(DEFAULT_INTERVAL) + { + } + + /// + /// Create a new evaluator using the specified time threshold in seconds. + /// + /// + /// The time threshold in seconds to trigger after. + /// Zero means it won't trigger at all. + /// + /// + /// + /// Create a new evaluator using the specified time threshold in seconds. + /// + /// + /// This evaluator will trigger if the specified time period + /// has passed since last check. + /// + /// + public TimeEvaluator(int interval) + { + this.m_interval = interval; + this.m_lastTimeUtc = DateTime.UtcNow; + } /// - /// Initializes a new instance of the class. - /// Create a new evaluator using the time threshold in seconds. - /// - /// - /// - /// Create a new evaluator using the time threshold in seconds. - /// - /// - /// This evaluator will trigger if the specified time period - /// has passed since last check. - /// - /// - public TimeEvaluator() - : this(DEFAULT_INTERVAL) - { + /// The time threshold in seconds to trigger after + /// + /// + /// The time threshold in seconds to trigger after. + /// Zero means it won't trigger at all. + /// + /// + /// + /// This evaluator will trigger if the specified time period + /// has passed since last check. + /// + /// + public int Interval + { + get { return this.m_interval; } + set { this.m_interval = value; } } /// - /// Initializes a new instance of the class. - /// Create a new evaluator using the specified time threshold in seconds. - /// - /// - /// The time threshold in seconds to trigger after. - /// Zero means it won't trigger at all. - /// - /// - /// - /// Create a new evaluator using the specified time threshold in seconds. - /// - /// - /// This evaluator will trigger if the specified time period - /// has passed since last check. - /// - /// - public TimeEvaluator(int interval) - { - this.m_interval = interval; - this.m_lastTimeUtc = DateTime.UtcNow; - } - - /// - /// Gets or sets the time threshold in seconds to trigger after. - /// - /// - /// The time threshold in seconds to trigger after. - /// Zero means it won't trigger at all. - /// - /// - /// - /// This evaluator will trigger if the specified time period - /// has passed since last check. - /// - /// - public int Interval - { - get { return this.m_interval; } - set { this.m_interval = value; } - } - - /// - /// Is this the triggering event?. - /// - /// The event to check. - /// This method returns true, if the specified time period - /// has passed since last check.. - /// Otherwise it returns false. - /// - /// - /// This evaluator will trigger if the specified time period - /// has passed since last check. - /// - /// - public bool IsTriggeringEvent(LoggingEvent loggingEvent) - { - if (loggingEvent == null) - { - throw new ArgumentNullException("loggingEvent"); - } - - // disable the evaluator if threshold is zero + /// Is this the triggering event? + /// + /// The event to check + /// This method returns true, if the specified time period + /// has passed since last check.. + /// Otherwise it returns false + /// + /// + /// This evaluator will trigger if the specified time period + /// has passed since last check. + /// + /// + public bool IsTriggeringEvent(LoggingEvent loggingEvent) + { + if (loggingEvent == null) + { + throw new ArgumentNullException("loggingEvent"); + } + + // disable the evaluator if threshold is zero if (this.m_interval == 0) { return false; } - lock (this) // avoid triggering multiple times - { - TimeSpan passed = DateTime.UtcNow.Subtract(this.m_lastTimeUtc); - - if (passed.TotalSeconds > this.m_interval) - { - this.m_lastTimeUtc = DateTime.UtcNow; - return true; - } - else - { - return false; - } - } - } - } -} + lock (this) // avoid triggering multiple times + { + TimeSpan passed = DateTime.UtcNow.Subtract(this.m_lastTimeUtc); + + if (passed.TotalSeconds > this.m_interval) + { + this.m_lastTimeUtc = DateTime.UtcNow; + return true; + } + else + { + return false; + } + } + } + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Core/WrapperMap.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Core/WrapperMap.cs index 96622e49df9..9de1ce6952a 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Core/WrapperMap.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Core/WrapperMap.cs @@ -1,238 +1,236 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.Core +using System; +using System.Collections; + +using log4net.Repository; + +namespace log4net.Core { - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; - using System.Collections; - - using log4net.Repository; - - /// - /// Delegate used to handle creation of new wrappers. - /// - /// The logger to wrap in a wrapper. - /// - /// - /// Delegate used to handle creation of new wrappers. This delegate - /// is called from the - /// method to construct the wrapper for the specified logger. - /// - /// - /// The delegate to use is supplied to the - /// constructor. - /// + /// + /// Delegate used to handle creation of new wrappers. + /// + /// The logger to wrap in a wrapper. + /// + /// + /// Delegate used to handle creation of new wrappers. This delegate + /// is called from the + /// method to construct the wrapper for the specified logger. + /// + /// + /// The delegate to use is supplied to the + /// constructor. + /// /// - /// public delegate ILoggerWrapper WrapperCreationHandler(ILogger logger); - /// - /// Maps between logger objects and wrapper objects. - /// - /// - /// - /// This class maintains a mapping between objects and - /// objects. Use the method to - /// lookup the for the specified . - /// - /// - /// New wrapper instances are created by the - /// method. The default behavior is for this method to delegate construction - /// of the wrapper to the delegate supplied - /// to the constructor. This allows specialization of the behavior without - /// requiring subclassing of this type. - /// - /// - /// Nicko Cadell. - /// Gert Driesen. - public class WrapperMap + /// + /// Maps between logger objects and wrapper objects. + /// + /// + /// + /// This class maintains a mapping between objects and + /// objects. Use the method to + /// lookup the for the specified . + /// + /// + /// New wrapper instances are created by the + /// method. The default behavior is for this method to delegate construction + /// of the wrapper to the delegate supplied + /// to the constructor. This allows specialization of the behavior without + /// requiring subclassing of this type. + /// + /// + /// Nicko Cadell + /// Gert Driesen + public class WrapperMap { /// - /// Initializes a new instance of the class. - /// Initializes a new instance of the . - /// - /// The handler to use to create the wrapper objects. - /// - /// - /// Initializes a new instance of the class with - /// the specified handler to create the wrapper objects. - /// - /// - public WrapperMap(WrapperCreationHandler createWrapperHandler) - { - this.m_createWrapperHandler = createWrapperHandler; - - // Create the delegates for the event callbacks - this.m_shutdownHandler = new LoggerRepositoryShutdownEventHandler(this.ILoggerRepository_Shutdown); + /// Initializes a new instance of the + /// + /// The handler to use to create the wrapper objects. + /// + /// + /// Initializes a new instance of the class with + /// the specified handler to create the wrapper objects. + /// + /// + public WrapperMap(WrapperCreationHandler createWrapperHandler) + { + this.m_createWrapperHandler = createWrapperHandler; + + // Create the delegates for the event callbacks + this.m_shutdownHandler = new LoggerRepositoryShutdownEventHandler(this.ILoggerRepository_Shutdown); } - /// - /// Gets the wrapper object for the specified logger. - /// - /// The wrapper object for the specified logger. - /// - /// - /// If the logger is null then the corresponding wrapper is null. - /// - /// - /// Looks up the wrapper it it has previously been requested and - /// returns it. If the wrapper has never been requested before then - /// the virtual method is - /// called. - /// - /// - public virtual ILoggerWrapper GetWrapper(ILogger logger) - { - // If the logger is null then the corresponding wrapper is null - if (logger == null) - { - return null; - } - - lock (this) - { - // Lookup hierarchy in map. - Hashtable wrappersMap = (Hashtable)this.m_repositories[logger.Repository]; - - if (wrappersMap == null) - { - // Hierarchy does not exist in map. - // Must register with hierarchy - wrappersMap = new Hashtable(); - this.m_repositories[logger.Repository] = wrappersMap; - - // Register for config reset & shutdown on repository - logger.Repository.ShutdownEvent += this.m_shutdownHandler; - } - - // Look for the wrapper object in the map - ILoggerWrapper wrapperObject = wrappersMap[logger] as ILoggerWrapper; - - if (wrapperObject == null) - { - // No wrapper object exists for the specified logger - - // Create a new wrapper wrapping the logger - wrapperObject = this.CreateNewWrapperObject(logger); - - // Store wrapper logger in map - wrappersMap[logger] = wrapperObject; - } - - return wrapperObject; - } + /// + /// Gets the wrapper object for the specified logger. + /// + /// The wrapper object for the specified logger + /// + /// + /// If the logger is null then the corresponding wrapper is null. + /// + /// + /// Looks up the wrapper it it has previously been requested and + /// returns it. If the wrapper has never been requested before then + /// the virtual method is + /// called. + /// + /// + public virtual ILoggerWrapper GetWrapper(ILogger logger) + { + // If the logger is null then the corresponding wrapper is null + if (logger == null) + { + return null; + } + + lock(this) + { + // Lookup hierarchy in map. + Hashtable wrappersMap = (Hashtable)this.m_repositories[logger.Repository]; + + if (wrappersMap == null) + { + // Hierarchy does not exist in map. + // Must register with hierarchy + + wrappersMap = new Hashtable(); + this.m_repositories[logger.Repository] = wrappersMap; + + // Register for config reset & shutdown on repository + logger.Repository.ShutdownEvent += this.m_shutdownHandler; + } + + // Look for the wrapper object in the map + ILoggerWrapper wrapperObject = wrappersMap[logger] as ILoggerWrapper; + + if (wrapperObject == null) + { + // No wrapper object exists for the specified logger + + // Create a new wrapper wrapping the logger + wrapperObject = this.CreateNewWrapperObject(logger); + + // Store wrapper logger in map + wrappersMap[logger] = wrapperObject; + } + + return wrapperObject; + } } - /// - /// Gets the map of logger repositories. - /// - /// - /// Map of logger repositories. - /// - /// - /// - /// Gets the hashtable that is keyed on . The - /// values are hashtables keyed on with the - /// value being the corresponding . - /// - /// - protected Hashtable Repositories - { - get { return this.m_repositories; } + /// + /// Gets the map of logger repositories. + /// + /// + /// Map of logger repositories. + /// + /// + /// + /// Gets the hashtable that is keyed on . The + /// values are hashtables keyed on with the + /// value being the corresponding . + /// + /// + protected Hashtable Repositories + { + get { return this.m_repositories; } } - /// - /// Creates the wrapper object for the specified logger. - /// - /// The logger to wrap in a wrapper. - /// The wrapper object for the logger. - /// - /// - /// This implementation uses the - /// passed to the constructor to create the wrapper. This method - /// can be overridden in a subclass. - /// - /// - protected virtual ILoggerWrapper CreateNewWrapperObject(ILogger logger) - { - if (this.m_createWrapperHandler != null) - { - return this.m_createWrapperHandler(logger); - } - - return null; - } - - /// - /// Called when a monitored repository shutdown event is received. - /// - /// The that is shutting down. - /// - /// - /// This method is called when a that this - /// is holding loggers for has signaled its shutdown - /// event . The default - /// behavior of this method is to release the references to the loggers - /// and their wrappers generated for this repository. - /// - /// - protected virtual void RepositoryShutdown(ILoggerRepository repository) - { - lock (this) - { - // Remove the repository from map - this.m_repositories.Remove(repository); - - // Unhook events from the repository - repository.ShutdownEvent -= this.m_shutdownHandler; - } - } - - /// - /// Event handler for repository shutdown event. - /// - /// The sender of the event. - /// The event args. - private void ILoggerRepository_Shutdown(object sender, EventArgs e) - { - ILoggerRepository repository = sender as ILoggerRepository; - if (repository != null) - { - // Remove all repository from map - this.RepositoryShutdown(repository); - } + /// + /// Creates the wrapper object for the specified logger. + /// + /// The logger to wrap in a wrapper. + /// The wrapper object for the logger. + /// + /// + /// This implementation uses the + /// passed to the constructor to create the wrapper. This method + /// can be overridden in a subclass. + /// + /// + protected virtual ILoggerWrapper CreateNewWrapperObject(ILogger logger) + { + if (this.m_createWrapperHandler != null) + { + return this.m_createWrapperHandler(logger); + } + return null; } - /// - /// Map of logger repositories to hashtables of ILogger to ILoggerWrapper mappings. - /// - private readonly Hashtable m_repositories = new Hashtable(); - - /// - /// The handler to use to create the extension wrapper objects. - /// - private readonly WrapperCreationHandler m_createWrapperHandler; - - /// - /// Internal reference to the delegate used to register for repository shutdown events. - /// + /// + /// Called when a monitored repository shutdown event is received. + /// + /// The that is shutting down + /// + /// + /// This method is called when a that this + /// is holding loggers for has signaled its shutdown + /// event . The default + /// behavior of this method is to release the references to the loggers + /// and their wrappers generated for this repository. + /// + /// + protected virtual void RepositoryShutdown(ILoggerRepository repository) + { + lock(this) + { + // Remove the repository from map + this.m_repositories.Remove(repository); + + // Unhook events from the repository + repository.ShutdownEvent -= this.m_shutdownHandler; + } + } + + /// + /// Event handler for repository shutdown event. + /// + /// The sender of the event. + /// The event args. + private void ILoggerRepository_Shutdown(object sender, EventArgs e) + { + ILoggerRepository repository = sender as ILoggerRepository; + if (repository != null) + { + // Remove all repository from map + this.RepositoryShutdown(repository); + } + } + + /// + /// Map of logger repositories to hashtables of ILogger to ILoggerWrapper mappings + /// + private readonly Hashtable m_repositories = new Hashtable(); + + /// + /// The handler to use to create the extension wrapper objects. + /// + private readonly WrapperCreationHandler m_createWrapperHandler; + + /// + /// Internal reference to the delegate used to register for repository shutdown events. + /// private readonly LoggerRepositoryShutdownEventHandler m_shutdownHandler; - } -} + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/DateFormatter/AbsoluteTimeDateFormatter.cs b/DNN Platform/DotNetNuke.Log4net/log4net/DateFormatter/AbsoluteTimeDateFormatter.cs index f65ea592b69..72f96147bcb 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/DateFormatter/AbsoluteTimeDateFormatter.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/DateFormatter/AbsoluteTimeDateFormatter.cs @@ -1,206 +1,198 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information - -namespace log4net.DateFormatter -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; - using System.Collections; - using System.IO; - using System.Text; - - /// - /// Formats a as "HH:mm:ss,fff". - /// - /// - /// - /// Formats a in the format "HH:mm:ss,fff" for example, "15:49:37,459". - /// - /// - /// Nicko Cadell. - /// Gert Driesen. - public class AbsoluteTimeDateFormatter : IDateFormatter +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +using System; +using System.Collections; +using System.IO; +using System.Text; + +namespace log4net.DateFormatter +{ + /// + /// Formats a as "HH:mm:ss,fff". + /// + /// + /// + /// Formats a in the format "HH:mm:ss,fff" for example, "15:49:37,459". + /// + /// + /// Nicko Cadell + /// Gert Driesen + public class AbsoluteTimeDateFormatter : IDateFormatter { - /// - /// Renders the date into a string. Format is "HH:mm:ss". - /// - /// The date to render into a string. - /// The string builder to write to. - /// - /// - /// Subclasses should override this method to render the date - /// into a string using a precision up to the second. This method - /// will be called at most once per second and the result will be - /// reused if it is needed again during the same second. - /// - /// - protected virtual void FormatDateWithoutMillis(DateTime dateToFormat, StringBuilder buffer) - { - int hour = dateToFormat.Hour; - if (hour < 10) - { - buffer.Append('0'); - } - - buffer.Append(hour); - buffer.Append(':'); - - int mins = dateToFormat.Minute; - if (mins < 10) - { - buffer.Append('0'); - } - - buffer.Append(mins); - buffer.Append(':'); - - int secs = dateToFormat.Second; - if (secs < 10) - { - buffer.Append('0'); - } - - buffer.Append(secs); - } - - /// - /// Renders the date into a string. Format is "HH:mm:ss,fff". - /// - /// The date to render into a string. - /// The writer to write to. - /// - /// - /// Uses the method to generate the - /// time string up to the seconds and then appends the current - /// milliseconds. The results from are - /// cached and is called at most once - /// per second. - /// - /// - /// Sub classes should override - /// rather than . - /// - /// - public virtual void FormatDate(DateTime dateToFormat, TextWriter writer) + /// + /// Renders the date into a string. Format is "HH:mm:ss". + /// + /// The date to render into a string. + /// The string builder to write to. + /// + /// + /// Subclasses should override this method to render the date + /// into a string using a precision up to the second. This method + /// will be called at most once per second and the result will be + /// reused if it is needed again during the same second. + /// + /// + protected virtual void FormatDateWithoutMillis(DateTime dateToFormat, StringBuilder buffer) { - lock (s_lastTimeStrings) + int hour = dateToFormat.Hour; + if (hour < 10) { - // Calculate the current time precise only to the second - long currentTimeToTheSecond = dateToFormat.Ticks - (dateToFormat.Ticks % TimeSpan.TicksPerSecond); - - string timeString = null; - - // Compare this time with the stored last time - // If we are in the same second then append - // the previously calculated time string - if (s_lastTimeToTheSecond != currentTimeToTheSecond) - { - s_lastTimeStrings.Clear(); - } - else - { - timeString = (string)s_lastTimeStrings[this.GetType()]; - } + buffer.Append('0'); + } + buffer.Append(hour); + buffer.Append(':'); - if (timeString == null) - { - // lock so that only one thread can use the buffer and - // update the s_lastTimeToTheSecond and s_lastTimeStrings - - // PERF: Try removing this lock and using a new StringBuilder each time - lock (s_lastTimeBuf) - { - timeString = (string)s_lastTimeStrings[this.GetType()]; + int mins = dateToFormat.Minute; + if (mins < 10) + { + buffer.Append('0'); + } + buffer.Append(mins); + buffer.Append(':'); + + int secs = dateToFormat.Second; + if (secs < 10) + { + buffer.Append('0'); + } + buffer.Append(secs); + } - if (timeString == null) + /// + /// Renders the date into a string. Format is "HH:mm:ss,fff". + /// + /// The date to render into a string. + /// The writer to write to. + /// + /// + /// Uses the method to generate the + /// time string up to the seconds and then appends the current + /// milliseconds. The results from are + /// cached and is called at most once + /// per second. + /// + /// + /// Sub classes should override + /// rather than . + /// + /// + public virtual void FormatDate(DateTime dateToFormat, TextWriter writer) + { + lock (s_lastTimeStrings) + { + // Calculate the current time precise only to the second + long currentTimeToTheSecond = (dateToFormat.Ticks - (dateToFormat.Ticks % TimeSpan.TicksPerSecond)); + + string timeString = null; + // Compare this time with the stored last time + // If we are in the same second then append + // the previously calculated time string + if (s_lastTimeToTheSecond != currentTimeToTheSecond) { - // We are in a new second. - s_lastTimeBuf.Length = 0; - - // Calculate the new string for this second - this.FormatDateWithoutMillis(dateToFormat, s_lastTimeBuf); - - // Render the string buffer to a string - timeString = s_lastTimeBuf.ToString(); - -#if NET_1_1 - // Ensure that the above string is written into the variable NOW on all threads. - // This is only required on multiprocessor machines with weak memeory models - System.Threading.Thread.MemoryBarrier(); -#endif - - // Store the time as a string (we only have to do this once per second) - s_lastTimeStrings[this.GetType()] = timeString; - s_lastTimeToTheSecond = currentTimeToTheSecond; + s_lastTimeStrings.Clear(); + } + else + { + timeString = (string) s_lastTimeStrings[this.GetType()]; } - } - } - writer.Write(timeString); + if (timeString == null) + { + // lock so that only one thread can use the buffer and + // update the s_lastTimeToTheSecond and s_lastTimeStrings - // Append the current millisecond info - writer.Write(','); - int millis = dateToFormat.Millisecond; - if (millis < 100) + // PERF: Try removing this lock and using a new StringBuilder each time + lock(s_lastTimeBuf) { - writer.Write('0'); + timeString = (string) s_lastTimeStrings[this.GetType()]; + + if (timeString == null) + { + // We are in a new second. + s_lastTimeBuf.Length = 0; + + // Calculate the new string for this second + this.FormatDateWithoutMillis(dateToFormat, s_lastTimeBuf); + + // Render the string buffer to a string + timeString = s_lastTimeBuf.ToString(); + +#if NET_1_1 + // Ensure that the above string is written into the variable NOW on all threads. + // This is only required on multiprocessor machines with weak memeory models + System.Threading.Thread.MemoryBarrier(); +#endif + // Store the time as a string (we only have to do this once per second) + s_lastTimeStrings[this.GetType()] = timeString; + s_lastTimeToTheSecond = currentTimeToTheSecond; + } } + } + writer.Write(timeString); + + // Append the current millisecond info + writer.Write(','); + int millis = dateToFormat.Millisecond; + if (millis < 100) + { + writer.Write('0'); + } + if (millis < 10) + { + writer.Write('0'); + } + writer.Write(millis); + } + } - if (millis < 10) - { - writer.Write('0'); - } + /// + /// String constant used to specify AbsoluteTimeDateFormat in layouts. Current value is ABSOLUTE. + /// + public const string AbsoluteTimeDateFormat = "ABSOLUTE"; - writer.Write(millis); - } - } + /// + /// String constant used to specify DateTimeDateFormat in layouts. Current value is DATE. + /// + public const string DateAndTimeDateFormat = "DATE"; - /// - /// String constant used to specify AbsoluteTimeDateFormat in layouts. Current value is ABSOLUTE. - /// - public const string AbsoluteTimeDateFormat = "ABSOLUTE"; - - /// - /// String constant used to specify DateTimeDateFormat in layouts. Current value is DATE. - /// - public const string DateAndTimeDateFormat = "DATE"; - - /// - /// String constant used to specify ISO8601DateFormat in layouts. Current value is ISO8601. - /// + /// + /// String constant used to specify ISO8601DateFormat in layouts. Current value is ISO8601. + /// public const string Iso8601TimeDateFormat = "ISO8601"; - /// - /// Last stored time with precision up to the second. - /// - private static long s_lastTimeToTheSecond = 0; - - /// - /// Last stored time with precision up to the second, formatted - /// as a string. - /// - private static StringBuilder s_lastTimeBuf = new StringBuilder(); - - /// - /// Last stored time with precision up to the second, formatted - /// as a string. - /// + /// + /// Last stored time with precision up to the second. + /// + private static long s_lastTimeToTheSecond = 0; + + /// + /// Last stored time with precision up to the second, formatted + /// as a string. + /// + private static StringBuilder s_lastTimeBuf = new StringBuilder(); + + /// + /// Last stored time with precision up to the second, formatted + /// as a string. + /// private static Hashtable s_lastTimeStrings = new Hashtable(); - } -} + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/DateFormatter/DateTimeDateFormatter.cs b/DNN Platform/DotNetNuke.Log4net/log4net/DateFormatter/DateTimeDateFormatter.cs index 568841722d5..b6ef0259bc8 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/DateFormatter/DateTimeDateFormatter.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/DateFormatter/DateTimeDateFormatter.cs @@ -1,97 +1,95 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.DateFormatter -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; - using System.Globalization; - using System.Text; +using System; +using System.Text; +using System.Globalization; - /// - /// Formats a as "dd MMM yyyy HH:mm:ss,fff". - /// - /// - /// - /// Formats a in the format - /// "dd MMM yyyy HH:mm:ss,fff" for example, - /// "06 Nov 1994 15:49:37,459". - /// - /// - /// Nicko Cadell. - /// Gert Driesen. - /// Angelika Schnagl. - public class DateTimeDateFormatter : AbsoluteTimeDateFormatter +namespace log4net.DateFormatter +{ + /// + /// Formats a as "dd MMM yyyy HH:mm:ss,fff" + /// + /// + /// + /// Formats a in the format + /// "dd MMM yyyy HH:mm:ss,fff" for example, + /// "06 Nov 1994 15:49:37,459". + /// + /// + /// Nicko Cadell + /// Gert Driesen + /// Angelika Schnagl + public class DateTimeDateFormatter : AbsoluteTimeDateFormatter { /// - /// Initializes a new instance of the class. - /// Default constructor. - /// - /// - /// - /// Initializes a new instance of the class. - /// - /// - public DateTimeDateFormatter() - { - this.m_dateTimeFormatInfo = DateTimeFormatInfo.InvariantInfo; + /// Default constructor. + /// + /// + /// + /// Initializes a new instance of the class. + /// + /// + public DateTimeDateFormatter() + { + this.m_dateTimeFormatInfo = DateTimeFormatInfo.InvariantInfo; } - /// - /// Formats the date without the milliseconds part. - /// - /// The date to format. - /// The string builder to write to. - /// - /// - /// Formats a DateTime in the format "dd MMM yyyy HH:mm:ss" - /// for example, "06 Nov 1994 15:49:37". - /// - /// - /// The base class will append the ",fff" milliseconds section. - /// This method will only be called at most once per second. - /// - /// - protected override void FormatDateWithoutMillis(DateTime dateToFormat, StringBuilder buffer) - { - int day = dateToFormat.Day; - if (day < 10) - { - buffer.Append('0'); - } + /// + /// Formats the date without the milliseconds part + /// + /// The date to format. + /// The string builder to write to. + /// + /// + /// Formats a DateTime in the format "dd MMM yyyy HH:mm:ss" + /// for example, "06 Nov 1994 15:49:37". + /// + /// + /// The base class will append the ",fff" milliseconds section. + /// This method will only be called at most once per second. + /// + /// + protected override void FormatDateWithoutMillis(DateTime dateToFormat, StringBuilder buffer) + { + int day = dateToFormat.Day; + if (day < 10) + { + buffer.Append('0'); + } + buffer.Append(day); + buffer.Append(' '); + + buffer.Append(this.m_dateTimeFormatInfo.GetAbbreviatedMonthName(dateToFormat.Month)); + buffer.Append(' '); - buffer.Append(day); - buffer.Append(' '); - - buffer.Append(this.m_dateTimeFormatInfo.GetAbbreviatedMonthName(dateToFormat.Month)); - buffer.Append(' '); - - buffer.Append(dateToFormat.Year); - buffer.Append(' '); - - // Append the 'HH:mm:ss' - base.FormatDateWithoutMillis(dateToFormat, buffer); + buffer.Append(dateToFormat.Year); + buffer.Append(' '); + + // Append the 'HH:mm:ss' + base.FormatDateWithoutMillis(dateToFormat, buffer); } - /// - /// The format info for the invariant culture. - /// + /// + /// The format info for the invariant culture. + /// private readonly DateTimeFormatInfo m_dateTimeFormatInfo; - } -} + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/DateFormatter/IDateFormatter.cs b/DNN Platform/DotNetNuke.Log4net/log4net/DateFormatter/IDateFormatter.cs index d82e51ab753..f4e41d9b2bd 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/DateFormatter/IDateFormatter.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/DateFormatter/IDateFormatter.cs @@ -1,56 +1,56 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.DateFormatter -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; - using System.IO; +using System; +using System.IO; - /// - /// Render a as a string. - /// - /// - /// - /// Interface to abstract the rendering of a - /// instance into a string. - /// - /// - /// The method is used to render the - /// date to a text writer. - /// - /// - /// Nicko Cadell. - /// Gert Driesen. - public interface IDateFormatter - { - /// - /// Formats the specified date as a string. - /// - /// The date to format. - /// The writer to write to. - /// - /// - /// Format the as a string and write it - /// to the provided. - /// - /// - void FormatDate(DateTime dateToFormat, TextWriter writer); - } -} +namespace log4net.DateFormatter +{ + /// + /// Render a as a string. + /// + /// + /// + /// Interface to abstract the rendering of a + /// instance into a string. + /// + /// + /// The method is used to render the + /// date to a text writer. + /// + /// + /// Nicko Cadell + /// Gert Driesen + public interface IDateFormatter + { + /// + /// Formats the specified date as a string. + /// + /// The date to format. + /// The writer to write to. + /// + /// + /// Format the as a string and write it + /// to the provided. + /// + /// + void FormatDate(DateTime dateToFormat, TextWriter writer); + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/DateFormatter/Iso8601DateFormatter.cs b/DNN Platform/DotNetNuke.Log4net/log4net/DateFormatter/Iso8601DateFormatter.cs index 2bb6438cf5e..8d8eaa13b5d 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/DateFormatter/Iso8601DateFormatter.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/DateFormatter/Iso8601DateFormatter.cs @@ -1,92 +1,89 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.DateFormatter -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; - using System.Text; +using System; +using System.Text; - /// - /// Formats the as "yyyy-MM-dd HH:mm:ss,fff". - /// - /// - /// - /// Formats the specified as a string: "yyyy-MM-dd HH:mm:ss,fff". - /// - /// - /// Nicko Cadell. - /// Gert Driesen. - public class Iso8601DateFormatter : AbsoluteTimeDateFormatter +namespace log4net.DateFormatter +{ + /// + /// Formats the as "yyyy-MM-dd HH:mm:ss,fff". + /// + /// + /// + /// Formats the specified as a string: "yyyy-MM-dd HH:mm:ss,fff". + /// + /// + /// Nicko Cadell + /// Gert Driesen + public class Iso8601DateFormatter : AbsoluteTimeDateFormatter { /// - /// Initializes a new instance of the class. - /// Default constructor. - /// - /// - /// - /// Initializes a new instance of the class. - /// - /// - public Iso8601DateFormatter() - { + /// Default constructor + /// + /// + /// + /// Initializes a new instance of the class. + /// + /// + public Iso8601DateFormatter() + { } - /// - /// Formats the date without the milliseconds part. - /// - /// The date to format. - /// The string builder to write to. - /// - /// - /// Formats the date specified as a string: "yyyy-MM-dd HH:mm:ss". - /// - /// - /// The base class will append the ",fff" milliseconds section. - /// This method will only be called at most once per second. - /// - /// - protected override void FormatDateWithoutMillis(DateTime dateToFormat, StringBuilder buffer) - { - buffer.Append(dateToFormat.Year); - - buffer.Append('-'); - int month = dateToFormat.Month; - if (month < 10) - { - buffer.Append('0'); - } + /// + /// Formats the date without the milliseconds part + /// + /// The date to format. + /// The string builder to write to. + /// + /// + /// Formats the date specified as a string: "yyyy-MM-dd HH:mm:ss". + /// + /// + /// The base class will append the ",fff" milliseconds section. + /// This method will only be called at most once per second. + /// + /// + protected override void FormatDateWithoutMillis(DateTime dateToFormat, StringBuilder buffer) + { + buffer.Append(dateToFormat.Year); + + buffer.Append('-'); + int month = dateToFormat.Month; + if (month < 10) + { + buffer.Append('0'); + } + buffer.Append(month); + buffer.Append('-'); - buffer.Append(month); - buffer.Append('-'); - - int day = dateToFormat.Day; - if (day < 10) - { - buffer.Append('0'); - } + int day = dateToFormat.Day; + if (day < 10) + { + buffer.Append('0'); + } + buffer.Append(day); + buffer.Append(' '); - buffer.Append(day); - buffer.Append(' '); - - // Append the 'HH:mm:ss' - base.FormatDateWithoutMillis(dateToFormat, buffer); + // Append the 'HH:mm:ss' + base.FormatDateWithoutMillis(dateToFormat, buffer); } - } -} + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/DateFormatter/SimpleDateFormatter.cs b/DNN Platform/DotNetNuke.Log4net/log4net/DateFormatter/SimpleDateFormatter.cs index 41f1e42f092..8e41fb1504e 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/DateFormatter/SimpleDateFormatter.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/DateFormatter/SimpleDateFormatter.cs @@ -1,85 +1,84 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.DateFormatter -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; - using System.IO; +using System; +using System.IO; - /// - /// Formats the using the method. - /// - /// - /// - /// Formats the using the method. - /// - /// - /// Nicko Cadell. - /// Gert Driesen. - public class SimpleDateFormatter : IDateFormatter +namespace log4net.DateFormatter +{ + /// + /// Formats the using the method. + /// + /// + /// + /// Formats the using the method. + /// + /// + /// Nicko Cadell + /// Gert Driesen + public class SimpleDateFormatter : IDateFormatter { /// - /// Initializes a new instance of the class. - /// Constructor. - /// - /// The format string. - /// - /// - /// Initializes a new instance of the class - /// with the specified format string. - /// - /// - /// The format string must be compatible with the options - /// that can be supplied to . - /// - /// - public SimpleDateFormatter(string format) - { - this.m_formatString = format; + /// Constructor + /// + /// The format string. + /// + /// + /// Initializes a new instance of the class + /// with the specified format string. + /// + /// + /// The format string must be compatible with the options + /// that can be supplied to . + /// + /// + public SimpleDateFormatter(string format) + { + this.m_formatString = format; } - /// - /// Formats the date using . - /// - /// The date to convert to a string. - /// The writer to write to. - /// - /// - /// Uses the date format string supplied to the constructor to call - /// the method to format the date. - /// - /// - public virtual void FormatDate(DateTime dateToFormat, TextWriter writer) - { - writer.Write(dateToFormat.ToString(this.m_formatString, System.Globalization.DateTimeFormatInfo.InvariantInfo)); + /// + /// Formats the date using . + /// + /// The date to convert to a string. + /// The writer to write to. + /// + /// + /// Uses the date format string supplied to the constructor to call + /// the method to format the date. + /// + /// + public virtual void FormatDate(DateTime dateToFormat, TextWriter writer) + { + writer.Write(dateToFormat.ToString(this.m_formatString, System.Globalization.DateTimeFormatInfo.InvariantInfo)); } - /// - /// The format string used to format the . - /// - /// - /// - /// The format string must be compatible with the options - /// that can be supplied to . - /// - /// + /// + /// The format string used to format the . + /// + /// + /// + /// The format string must be compatible with the options + /// that can be supplied to . + /// + /// private readonly string m_formatString; - } -} + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Filter/DenyAllFilter.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Filter/DenyAllFilter.cs index 74673fe255e..601fd797080 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Filter/DenyAllFilter.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Filter/DenyAllFilter.cs @@ -1,69 +1,68 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.Filter -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; +using System; - using log4net.Core; +using log4net.Core; - /// - /// This filter drops all . - /// - /// - /// - /// You can add this filter to the end of a filter chain to - /// switch from the default "accept all unless instructed otherwise" - /// filtering behavior to a "deny all unless instructed otherwise" - /// behavior. - /// - /// - /// Nicko Cadell. - /// Gert Driesen. - public sealed class DenyAllFilter : FilterSkeleton +namespace log4net.Filter +{ + /// + /// This filter drops all . + /// + /// + /// + /// You can add this filter to the end of a filter chain to + /// switch from the default "accept all unless instructed otherwise" + /// filtering behavior to a "deny all unless instructed otherwise" + /// behavior. + /// + /// + /// Nicko Cadell + /// Gert Driesen + public sealed class DenyAllFilter : FilterSkeleton { /// - /// Initializes a new instance of the class. - /// Default constructor. - /// - public DenyAllFilter() - { + /// Default constructor + /// + public DenyAllFilter() + { } - /// - /// Always returns the integer constant . - /// - /// the LoggingEvent to filter. - /// Always returns . - /// - /// - /// Ignores the event being logged and just returns - /// . This can be used to change the default filter - /// chain behavior from to . This filter - /// should only be used as the last filter in the chain - /// as any further filters will be ignored!. - /// - /// - public override FilterDecision Decide(LoggingEvent loggingEvent) - { - return FilterDecision.Deny; + /// + /// Always returns the integer constant + /// + /// the LoggingEvent to filter + /// Always returns + /// + /// + /// Ignores the event being logged and just returns + /// . This can be used to change the default filter + /// chain behavior from to . This filter + /// should only be used as the last filter in the chain + /// as any further filters will be ignored! + /// + /// + public override FilterDecision Decide(LoggingEvent loggingEvent) + { + return FilterDecision.Deny; } - } -} + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Filter/FilterDecision.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Filter/FilterDecision.cs index c80edf64b76..9e4de180b9e 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Filter/FilterDecision.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Filter/FilterDecision.cs @@ -1,55 +1,55 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.Filter -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; +using System; - using log4net.Core; +using log4net.Core; - /// - /// The return result from . - /// - /// - /// - /// The return result from . - /// - /// - public enum FilterDecision : int - { - /// - /// The log event must be dropped immediately without - /// consulting with the remaining filters, if any, in the chain. - /// - Deny = -1, - - /// - /// This filter is neutral with respect to the log event. - /// The remaining filters, if any, should be consulted for a final decision. - /// - Neutral = 0, - - /// - /// The log event must be logged immediately without - /// consulting with the remaining filters, if any, in the chain. - /// - Accept = 1, - } -} +namespace log4net.Filter +{ + /// + /// The return result from + /// + /// + /// + /// The return result from + /// + /// + public enum FilterDecision : int + { + /// + /// The log event must be dropped immediately without + /// consulting with the remaining filters, if any, in the chain. + /// + Deny = -1, + + /// + /// This filter is neutral with respect to the log event. + /// The remaining filters, if any, should be consulted for a final decision. + /// + Neutral = 0, + + /// + /// The log event must be logged immediately without + /// consulting with the remaining filters, if any, in the chain. + /// + Accept = 1, + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Filter/FilterSkeleton.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Filter/FilterSkeleton.cs index 5328920fd8f..dc1777155c5 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Filter/FilterSkeleton.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Filter/FilterSkeleton.cs @@ -1,145 +1,144 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.Filter -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; +using System; +using log4net.Core; - using log4net.Core; - - /// - /// Subclass this type to implement customized logging event filtering. - /// - /// - /// - /// Users should extend this class to implement customized logging - /// event filtering. Note that and - /// , the parent class of all standard - /// appenders, have built-in filtering rules. It is suggested that you - /// first use and understand the built-in rules before rushing to write - /// your own custom filters. - /// - /// - /// This abstract class assumes and also imposes that filters be - /// organized in a linear chain. The - /// method of each filter is called sequentially, in the order of their - /// addition to the chain. - /// - /// - /// The method must return one - /// of the integer constants , - /// or . - /// - /// - /// If the value is returned, then the log event is dropped - /// immediately without consulting with the remaining filters. - /// - /// - /// If the value is returned, then the next filter - /// in the chain is consulted. If there are no more filters in the - /// chain, then the log event is logged. Thus, in the presence of no - /// filters, the default behavior is to log all logging events. - /// - /// - /// If the value is returned, then the log - /// event is logged without consulting the remaining filters. - /// - /// - /// The philosophy of log4net filters is largely inspired from the - /// Linux ipchains. - /// - /// - /// Nicko Cadell. - /// Gert Driesen. - public abstract class FilterSkeleton : IFilter +namespace log4net.Filter +{ + /// + /// Subclass this type to implement customized logging event filtering + /// + /// + /// + /// Users should extend this class to implement customized logging + /// event filtering. Note that and + /// , the parent class of all standard + /// appenders, have built-in filtering rules. It is suggested that you + /// first use and understand the built-in rules before rushing to write + /// your own custom filters. + /// + /// + /// This abstract class assumes and also imposes that filters be + /// organized in a linear chain. The + /// method of each filter is called sequentially, in the order of their + /// addition to the chain. + /// + /// + /// The method must return one + /// of the integer constants , + /// or . + /// + /// + /// If the value is returned, then the log event is dropped + /// immediately without consulting with the remaining filters. + /// + /// + /// If the value is returned, then the next filter + /// in the chain is consulted. If there are no more filters in the + /// chain, then the log event is logged. Thus, in the presence of no + /// filters, the default behavior is to log all logging events. + /// + /// + /// If the value is returned, then the log + /// event is logged without consulting the remaining filters. + /// + /// + /// The philosophy of log4net filters is largely inspired from the + /// Linux ipchains. + /// + /// + /// Nicko Cadell + /// Gert Driesen + public abstract class FilterSkeleton : IFilter { - /// - /// Points to the next filter in the filter chain. - /// - /// - /// - /// See for more information. - /// - /// + /// + /// Points to the next filter in the filter chain. + /// + /// + /// + /// See for more information. + /// + /// private IFilter m_next; - /// - /// Initialize the filter with the options set. - /// - /// - /// - /// This is part of the delayed object - /// activation scheme. The method must - /// be called on this object after the configuration properties have - /// been set. Until is called this - /// object is in an undefined state and must not be used. - /// - /// - /// If any of the configuration properties are modified then - /// must be called again. - /// - /// - /// Typically filter's options become active immediately on set, - /// however this method must still be called. - /// - /// - public virtual void ActivateOptions() - { + /// + /// Initialize the filter with the options set + /// + /// + /// + /// This is part of the delayed object + /// activation scheme. The method must + /// be called on this object after the configuration properties have + /// been set. Until is called this + /// object is in an undefined state and must not be used. + /// + /// + /// If any of the configuration properties are modified then + /// must be called again. + /// + /// + /// Typically filter's options become active immediately on set, + /// however this method must still be called. + /// + /// + public virtual void ActivateOptions() + { } - /// - /// Decide if the should be logged through an appender. - /// - /// The to decide upon. - /// The decision of the filter. - /// - /// - /// If the decision is , then the event will be - /// dropped. If the decision is , then the next - /// filter, if any, will be invoked. If the decision is then - /// the event will be logged without consulting with other filters in - /// the chain. - /// - /// - /// This method is marked abstract and must be implemented - /// in a subclass. - /// - /// - public abstract FilterDecision Decide(LoggingEvent loggingEvent); - - /// - /// Gets or sets property to get and set the next filter. - /// - /// - /// The next filter in the chain. - /// - /// - /// - /// Filters are typically composed into chains. This property allows the next filter in - /// the chain to be accessed. - /// - /// - public IFilter Next - { - get { return this.m_next; } - set { this.m_next = value; } + /// + /// Decide if the should be logged through an appender. + /// + /// The to decide upon + /// The decision of the filter + /// + /// + /// If the decision is , then the event will be + /// dropped. If the decision is , then the next + /// filter, if any, will be invoked. If the decision is then + /// the event will be logged without consulting with other filters in + /// the chain. + /// + /// + /// This method is marked abstract and must be implemented + /// in a subclass. + /// + /// + public abstract FilterDecision Decide(LoggingEvent loggingEvent); + + /// + /// Property to get and set the next filter + /// + /// + /// The next filter in the chain + /// + /// + /// + /// Filters are typically composed into chains. This property allows the next filter in + /// the chain to be accessed. + /// + /// + public IFilter Next + { + get { return this.m_next; } + set { this.m_next = value; } } - } -} + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Filter/IFilter.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Filter/IFilter.cs index 0666a393592..35e32ba018b 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Filter/IFilter.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Filter/IFilter.cs @@ -1,103 +1,103 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.Filter -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; +using System; - using log4net.Core; +using log4net.Core; - /// - /// Implement this interface to provide customized logging event filtering. - /// - /// - /// - /// Users should implement this interface to implement customized logging - /// event filtering. Note that and - /// , the parent class of all standard - /// appenders, have built-in filtering rules. It is suggested that you - /// first use and understand the built-in rules before rushing to write - /// your own custom filters. - /// - /// - /// This abstract class assumes and also imposes that filters be - /// organized in a linear chain. The - /// method of each filter is called sequentially, in the order of their - /// addition to the chain. - /// - /// - /// The method must return one - /// of the integer constants , - /// or . - /// - /// - /// If the value is returned, then the log event is dropped - /// immediately without consulting with the remaining filters. - /// - /// - /// If the value is returned, then the next filter - /// in the chain is consulted. If there are no more filters in the - /// chain, then the log event is logged. Thus, in the presence of no - /// filters, the default behavior is to log all logging events. - /// - /// - /// If the value is returned, then the log - /// event is logged without consulting the remaining filters. - /// - /// - /// The philosophy of log4net filters is largely inspired from the - /// Linux ipchains. - /// - /// - /// Nicko Cadell. - /// Gert Driesen. - public interface IFilter : IOptionHandler - { - /// - /// Decide if the logging event should be logged through an appender. - /// - /// The LoggingEvent to decide upon. - /// The decision of the filter. - /// - /// - /// If the decision is , then the event will be - /// dropped. If the decision is , then the next - /// filter, if any, will be invoked. If the decision is then - /// the event will be logged without consulting with other filters in - /// the chain. - /// - /// - FilterDecision Decide(LoggingEvent loggingEvent); - - /// - /// Gets or sets property to get and set the next filter. - /// - /// - /// The next filter in the chain. - /// - /// - /// - /// Filters are typically composed into chains. This property allows the next filter in - /// the chain to be accessed. - /// - /// - IFilter Next { get; set; } - } -} +namespace log4net.Filter +{ + /// + /// Implement this interface to provide customized logging event filtering + /// + /// + /// + /// Users should implement this interface to implement customized logging + /// event filtering. Note that and + /// , the parent class of all standard + /// appenders, have built-in filtering rules. It is suggested that you + /// first use and understand the built-in rules before rushing to write + /// your own custom filters. + /// + /// + /// This abstract class assumes and also imposes that filters be + /// organized in a linear chain. The + /// method of each filter is called sequentially, in the order of their + /// addition to the chain. + /// + /// + /// The method must return one + /// of the integer constants , + /// or . + /// + /// + /// If the value is returned, then the log event is dropped + /// immediately without consulting with the remaining filters. + /// + /// + /// If the value is returned, then the next filter + /// in the chain is consulted. If there are no more filters in the + /// chain, then the log event is logged. Thus, in the presence of no + /// filters, the default behavior is to log all logging events. + /// + /// + /// If the value is returned, then the log + /// event is logged without consulting the remaining filters. + /// + /// + /// The philosophy of log4net filters is largely inspired from the + /// Linux ipchains. + /// + /// + /// Nicko Cadell + /// Gert Driesen + public interface IFilter : IOptionHandler + { + /// + /// Decide if the logging event should be logged through an appender. + /// + /// The LoggingEvent to decide upon + /// The decision of the filter + /// + /// + /// If the decision is , then the event will be + /// dropped. If the decision is , then the next + /// filter, if any, will be invoked. If the decision is then + /// the event will be logged without consulting with other filters in + /// the chain. + /// + /// + FilterDecision Decide(LoggingEvent loggingEvent); + + /// + /// Property to get and set the next filter + /// + /// + /// The next filter in the chain + /// + /// + /// + /// Filters are typically composed into chains. This property allows the next filter in + /// the chain to be accessed. + /// + /// + IFilter Next { get; set; } + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Filter/LevelMatchFilter.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Filter/LevelMatchFilter.cs index f6b44a90018..4afac8507d9 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Filter/LevelMatchFilter.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Filter/LevelMatchFilter.cs @@ -1,133 +1,131 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.Filter -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; +using System; - using log4net; - using log4net.Core; - using log4net.Util; +using log4net; +using log4net.Core; +using log4net.Util; - /// - /// This is a very simple filter based on matching. - /// - /// - /// - /// The filter admits two options and - /// . If there is an exact match between the value - /// of the option and the of the - /// , then the method returns in - /// case the option value is set - /// to true, if it is false then - /// is returned. If the does not match then - /// the result will be . - /// - /// - /// Nicko Cadell. - /// Gert Driesen. - public class LevelMatchFilter : FilterSkeleton +namespace log4net.Filter +{ + /// + /// This is a very simple filter based on matching. + /// + /// + /// + /// The filter admits two options and + /// . If there is an exact match between the value + /// of the option and the of the + /// , then the method returns in + /// case the option value is set + /// to true, if it is false then + /// is returned. If the does not match then + /// the result will be . + /// + /// + /// Nicko Cadell + /// Gert Driesen + public class LevelMatchFilter : FilterSkeleton { - /// - /// flag to indicate if the filter should on a match. - /// - private bool m_acceptOnMatch = true; - - /// - /// the to match against. - /// + /// + /// flag to indicate if the filter should on a match + /// + private bool m_acceptOnMatch = true; + + /// + /// the to match against + /// private Level m_levelToMatch; /// - /// Initializes a new instance of the class. - /// Default constructor. - /// - public LevelMatchFilter() - { + /// Default constructor + /// + public LevelMatchFilter() + { + } + + /// + /// when matching + /// + /// + /// + /// The property is a flag that determines + /// the behavior when a matching is found. If the + /// flag is set to true then the filter will the + /// logging event, otherwise it will the event. + /// + /// + /// The default is true i.e. to the event. + /// + /// + public bool AcceptOnMatch + { + get { return this.m_acceptOnMatch; } + set { this.m_acceptOnMatch = value; } } - /// - /// Gets or sets a value indicating whether when matching . - /// - /// - /// - /// The property is a flag that determines - /// the behavior when a matching is found. If the - /// flag is set to true then the filter will the - /// logging event, otherwise it will the event. - /// - /// - /// The default is true i.e. to the event. - /// - /// - public bool AcceptOnMatch - { - get { return this.m_acceptOnMatch; } - set { this.m_acceptOnMatch = value; } - } - - /// - /// Gets or sets the that the filter will match. - /// - /// - /// - /// The level that this filter will attempt to match against the - /// level. If a match is found then - /// the result depends on the value of . - /// - /// - public Level LevelToMatch - { - get { return this.m_levelToMatch; } - set { this.m_levelToMatch = value; } + /// + /// The that the filter will match + /// + /// + /// + /// The level that this filter will attempt to match against the + /// level. If a match is found then + /// the result depends on the value of . + /// + /// + public Level LevelToMatch + { + get { return this.m_levelToMatch; } + set { this.m_levelToMatch = value; } } - /// - /// Tests if the of the logging event matches that of the filter. - /// - /// the event to filter. - /// see remarks. - /// - /// - /// If the of the event matches the level of the - /// filter then the result of the function depends on the - /// value of . If it is true then - /// the function will return , it it is false then it - /// will return . If the does not match then - /// the result will be . - /// - /// - public override FilterDecision Decide(LoggingEvent loggingEvent) - { - if (loggingEvent == null) - { - throw new ArgumentNullException("loggingEvent"); - } - - if (this.m_levelToMatch != null && this.m_levelToMatch == loggingEvent.Level) - { - // Found match - return this.m_acceptOnMatch ? FilterDecision.Accept : FilterDecision.Deny; - } + /// + /// Tests if the of the logging event matches that of the filter + /// + /// the event to filter + /// see remarks + /// + /// + /// If the of the event matches the level of the + /// filter then the result of the function depends on the + /// value of . If it is true then + /// the function will return , it it is false then it + /// will return . If the does not match then + /// the result will be . + /// + /// + public override FilterDecision Decide(LoggingEvent loggingEvent) + { + if (loggingEvent == null) + { + throw new ArgumentNullException("loggingEvent"); + } - return FilterDecision.Neutral; + if (this.m_levelToMatch != null && this.m_levelToMatch == loggingEvent.Level) + { + // Found match + return this.m_acceptOnMatch ? FilterDecision.Accept : FilterDecision.Deny; + } + return FilterDecision.Neutral; } - } -} + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Filter/LevelRangeFilter.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Filter/LevelRangeFilter.cs index 9186c029d93..f777cadf7e9 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Filter/LevelRangeFilter.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Filter/LevelRangeFilter.cs @@ -1,175 +1,174 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.Filter -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; +using System; - using log4net; - using log4net.Core; - using log4net.Util; +using log4net; +using log4net.Core; +using log4net.Util; - /// - /// This is a simple filter based on matching. - /// - /// - /// - /// The filter admits three options and - /// that determine the range of priorities that are matched, and - /// . If there is a match between the range - /// of priorities and the of the , then the - /// method returns in case the - /// option value is set to true, if it is false - /// then is returned. If there is no match, is returned. - /// - /// - /// Nicko Cadell. - /// Gert Driesen. - public class LevelRangeFilter : FilterSkeleton +namespace log4net.Filter +{ + /// + /// This is a simple filter based on matching. + /// + /// + /// + /// The filter admits three options and + /// that determine the range of priorities that are matched, and + /// . If there is a match between the range + /// of priorities and the of the , then the + /// method returns in case the + /// option value is set to true, if it is false + /// then is returned. If there is no match, is returned. + /// + /// + /// Nicko Cadell + /// Gert Driesen + public class LevelRangeFilter : FilterSkeleton { - /// - /// Flag to indicate the behavior when matching a . - /// - private bool m_acceptOnMatch = true; - - /// - /// the minimum value to match. - /// - private Level m_levelMin; - - /// - /// the maximum value to match. - /// + /// + /// Flag to indicate the behavior when matching a + /// + private bool m_acceptOnMatch = true; + + /// + /// the minimum value to match + /// + private Level m_levelMin; + + /// + /// the maximum value to match + /// private Level m_levelMax; /// - /// Initializes a new instance of the class. - /// Default constructor. - /// - public LevelRangeFilter() - { + /// Default constructor + /// + public LevelRangeFilter() + { + } + + /// + /// when matching and + /// + /// + /// + /// The property is a flag that determines + /// the behavior when a matching is found. If the + /// flag is set to true then the filter will the + /// logging event, otherwise it will the event. + /// + /// + /// The default is true i.e. to the event. + /// + /// + public bool AcceptOnMatch + { + get { return this.m_acceptOnMatch; } + set { this.m_acceptOnMatch = value; } } - /// - /// Gets or sets a value indicating whether when matching and . - /// - /// - /// - /// The property is a flag that determines - /// the behavior when a matching is found. If the - /// flag is set to true then the filter will the - /// logging event, otherwise it will the event. - /// - /// - /// The default is true i.e. to the event. - /// - /// - public bool AcceptOnMatch - { - get { return this.m_acceptOnMatch; } - set { this.m_acceptOnMatch = value; } - } - - /// - /// Gets or sets set the minimum matched . - /// - /// - /// - /// The minimum level that this filter will attempt to match against the - /// level. If a match is found then - /// the result depends on the value of . - /// - /// - public Level LevelMin - { - get { return this.m_levelMin; } - set { this.m_levelMin = value; } - } - - /// - /// Gets or sets the maximum matched . - /// - /// - /// - /// The maximum level that this filter will attempt to match against the - /// level. If a match is found then - /// the result depends on the value of . - /// - /// - public Level LevelMax - { - get { return this.m_levelMax; } - set { this.m_levelMax = value; } + /// + /// Set the minimum matched + /// + /// + /// + /// The minimum level that this filter will attempt to match against the + /// level. If a match is found then + /// the result depends on the value of . + /// + /// + public Level LevelMin + { + get { return this.m_levelMin; } + set { this.m_levelMin = value; } + } + + /// + /// Sets the maximum matched + /// + /// + /// + /// The maximum level that this filter will attempt to match against the + /// level. If a match is found then + /// the result depends on the value of . + /// + /// + public Level LevelMax + { + get { return this.m_levelMax; } + set { this.m_levelMax = value; } } - /// - /// Check if the event should be logged. - /// - /// the logging event to check. - /// see remarks. - /// - /// - /// If the of the logging event is outside the range - /// matched by this filter then - /// is returned. If the is matched then the value of - /// is checked. If it is true then - /// is returned, otherwise - /// is returned. - /// - /// - public override FilterDecision Decide(LoggingEvent loggingEvent) - { - if (loggingEvent == null) - { - throw new ArgumentNullException("loggingEvent"); - } - - if (this.m_levelMin != null) - { - if (loggingEvent.Level < this.m_levelMin) - { - // level of event is less than minimum - return FilterDecision.Deny; - } - } - - if (this.m_levelMax != null) - { - if (loggingEvent.Level > this.m_levelMax) - { - // level of event is greater than maximum - return FilterDecision.Deny; - } - } - - if (this.m_acceptOnMatch) - { - // this filter set up to bypass later filters and always return - // accept if level in range - return FilterDecision.Accept; - } - else - { - // event is ok for this filter; allow later filters to have a look.. - return FilterDecision.Neutral; - } + /// + /// Check if the event should be logged. + /// + /// the logging event to check + /// see remarks + /// + /// + /// If the of the logging event is outside the range + /// matched by this filter then + /// is returned. If the is matched then the value of + /// is checked. If it is true then + /// is returned, otherwise + /// is returned. + /// + /// + public override FilterDecision Decide(LoggingEvent loggingEvent) + { + if (loggingEvent == null) + { + throw new ArgumentNullException("loggingEvent"); + } + + if (this.m_levelMin != null) + { + if (loggingEvent.Level < this.m_levelMin) + { + // level of event is less than minimum + return FilterDecision.Deny; + } + } + + if (this.m_levelMax != null) + { + if (loggingEvent.Level > this.m_levelMax) + { + // level of event is greater than maximum + return FilterDecision.Deny; + } + } + + if (this.m_acceptOnMatch) + { + // this filter set up to bypass later filters and always return + // accept if level in range + return FilterDecision.Accept; + } + else + { + // event is ok for this filter; allow later filters to have a look.. + return FilterDecision.Neutral; + } } - } -} + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Filter/LoggerMatchFilter.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Filter/LoggerMatchFilter.cs index 3d29dcb8c56..dfe6411a1c6 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Filter/LoggerMatchFilter.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Filter/LoggerMatchFilter.cs @@ -1,147 +1,145 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.Filter -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; +using System; - using log4net; - using log4net.Core; - using log4net.Util; +using log4net; +using log4net.Core; +using log4net.Util; - /// - /// Simple filter to match a string in the event's logger name. - /// - /// - /// - /// The works very similar to the . It admits two - /// options and . If the - /// of the starts - /// with the value of the option, then the - /// method returns in - /// case the option value is set to true, - /// if it is false then is returned. - /// - /// - /// Daniel Cazzulino. - public class LoggerMatchFilter : FilterSkeleton +namespace log4net.Filter +{ + /// + /// Simple filter to match a string in the event's logger name. + /// + /// + /// + /// The works very similar to the . It admits two + /// options and . If the + /// of the starts + /// with the value of the option, then the + /// method returns in + /// case the option value is set to true, + /// if it is false then is returned. + /// + /// + /// Daniel Cazzulino + public class LoggerMatchFilter : FilterSkeleton { - /// - /// Flag to indicate the behavior when we have a match. - /// - private bool m_acceptOnMatch = true; - - /// - /// The logger name string to substring match against the event. - /// + /// + /// Flag to indicate the behavior when we have a match + /// + private bool m_acceptOnMatch = true; + + /// + /// The logger name string to substring match against the event + /// private string m_loggerToMatch; /// - /// Initializes a new instance of the class. - /// Default constructor. - /// - public LoggerMatchFilter() - { + /// Default constructor + /// + public LoggerMatchFilter() + { + } + + /// + /// when matching + /// + /// + /// + /// The property is a flag that determines + /// the behavior when a matching is found. If the + /// flag is set to true then the filter will the + /// logging event, otherwise it will the event. + /// + /// + /// The default is true i.e. to the event. + /// + /// + public bool AcceptOnMatch + { + get { return this.m_acceptOnMatch; } + set { this.m_acceptOnMatch = value; } } - /// - /// Gets or sets a value indicating whether when matching . - /// - /// - /// - /// The property is a flag that determines - /// the behavior when a matching is found. If the - /// flag is set to true then the filter will the - /// logging event, otherwise it will the event. - /// - /// - /// The default is true i.e. to the event. - /// - /// - public bool AcceptOnMatch - { - get { return this.m_acceptOnMatch; } - set { this.m_acceptOnMatch = value; } - } - - /// - /// Gets or sets the that the filter will match. - /// - /// - /// - /// This filter will attempt to match this value against logger name in - /// the following way. The match will be done against the beginning of the - /// logger name (using ). The match is - /// case sensitive. If a match is found then - /// the result depends on the value of . - /// - /// - public string LoggerToMatch - { - get { return this.m_loggerToMatch; } - set { this.m_loggerToMatch = value; } + /// + /// The that the filter will match + /// + /// + /// + /// This filter will attempt to match this value against logger name in + /// the following way. The match will be done against the beginning of the + /// logger name (using ). The match is + /// case sensitive. If a match is found then + /// the result depends on the value of . + /// + /// + public string LoggerToMatch + { + get { return this.m_loggerToMatch; } + set { this.m_loggerToMatch = value; } } - /// - /// Check if this filter should allow the event to be logged. - /// - /// the event being logged. - /// see remarks. - /// - /// - /// The rendered message is matched against the . - /// If the equals the beginning of - /// the incoming () - /// then a match will have occurred. If no match occurs - /// this function will return - /// allowing other filters to check the event. If a match occurs then - /// the value of is checked. If it is - /// true then is returned otherwise - /// is returned. - /// - /// - public override FilterDecision Decide(LoggingEvent loggingEvent) - { - if (loggingEvent == null) - { - throw new ArgumentNullException("loggingEvent"); - } - - // Check if we have been setup to filter - if ((this.m_loggerToMatch != null && this.m_loggerToMatch.Length != 0) && - loggingEvent.LoggerName.StartsWith(this.m_loggerToMatch)) - { - // we've got a match - if (this.m_acceptOnMatch) - { - return FilterDecision.Accept; - } + /// + /// Check if this filter should allow the event to be logged + /// + /// the event being logged + /// see remarks + /// + /// + /// The rendered message is matched against the . + /// If the equals the beginning of + /// the incoming () + /// then a match will have occurred. If no match occurs + /// this function will return + /// allowing other filters to check the event. If a match occurs then + /// the value of is checked. If it is + /// true then is returned otherwise + /// is returned. + /// + /// + public override FilterDecision Decide(LoggingEvent loggingEvent) + { + if (loggingEvent == null) + { + throw new ArgumentNullException("loggingEvent"); + } - return FilterDecision.Deny; - } - else - { - // We cannot filter so allow the filter chain - // to continue processing - return FilterDecision.Neutral; - } + // Check if we have been setup to filter + if ((this.m_loggerToMatch != null && this.m_loggerToMatch.Length != 0) && + loggingEvent.LoggerName.StartsWith(this.m_loggerToMatch)) + { + // we've got a match + if (this.m_acceptOnMatch) + { + return FilterDecision.Accept; + } + return FilterDecision.Deny; + } + else + { + // We cannot filter so allow the filter chain + // to continue processing + return FilterDecision.Neutral; + } } - } -} + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Filter/MdcFilter.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Filter/MdcFilter.cs index 87b97a263bc..f738793e3e2 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Filter/MdcFilter.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Filter/MdcFilter.cs @@ -1,48 +1,48 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.Filter -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; - using System.Text.RegularExpressions; +using System; +using System.Text.RegularExpressions; - using log4net; - using log4net.Core; - using log4net.Util; +using log4net; +using log4net.Core; +using log4net.Util; - /// - /// Simple filter to match a keyed string in the . - /// - /// - /// - /// Simple filter to match a keyed string in the . - /// - /// - /// As the MDC has been replaced with layered properties the - /// should be used instead. - /// - /// - /// Nicko Cadell. - /// Gert Driesen. - [Obsolete("MdcFilter has been replaced by PropertyFilter. Scheduled removal in v10.0.0.")] - public class MdcFilter : PropertyFilter - { - } -} +namespace log4net.Filter +{ + /// + /// Simple filter to match a keyed string in the + /// + /// + /// + /// Simple filter to match a keyed string in the + /// + /// + /// As the MDC has been replaced with layered properties the + /// should be used instead. + /// + /// + /// Nicko Cadell + /// Gert Driesen + /*[Obsolete("MdcFilter has been replaced by PropertyFilter")]*/ + public class MdcFilter : PropertyFilter + { + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Filter/NdcFilter.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Filter/NdcFilter.cs index c29894ecb4d..8aef836d93b 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Filter/NdcFilter.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Filter/NdcFilter.cs @@ -1,62 +1,61 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.Filter -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; - using System.Text.RegularExpressions; +using System; +using System.Text.RegularExpressions; - using log4net; - using log4net.Core; - using log4net.Util; +using log4net; +using log4net.Core; +using log4net.Util; - /// - /// Simple filter to match a string in the . - /// - /// - /// - /// Simple filter to match a string in the . - /// - /// - /// As the MDC has been replaced with named stacks stored in the - /// properties collections the should - /// be used instead. - /// - /// - /// Nicko Cadell. - /// Gert Driesen. - [Obsolete("NdcFilter has been replaced by PropertyFilter. Scheduled removal in v10.0.0.")] - public class NdcFilter : PropertyFilter +namespace log4net.Filter +{ + /// + /// Simple filter to match a string in the + /// + /// + /// + /// Simple filter to match a string in the + /// + /// + /// As the MDC has been replaced with named stacks stored in the + /// properties collections the should + /// be used instead. + /// + /// + /// Nicko Cadell + /// Gert Driesen + /*[Obsolete("NdcFilter has been replaced by PropertyFilter")]*/ + public class NdcFilter : PropertyFilter { /// - /// Initializes a new instance of the class. - /// Default constructor. - /// - /// - /// - /// Sets the to "NDC". - /// - /// - public NdcFilter() - { - this.Key = "NDC"; - } - } -} + /// Default constructor + /// + /// + /// + /// Sets the to "NDC". + /// + /// + public NdcFilter() + { + this.Key = "NDC"; + } + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Filter/PropertyFilter.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Filter/PropertyFilter.cs index aef8997d203..fc4937c219c 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Filter/PropertyFilter.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Filter/PropertyFilter.cs @@ -1,158 +1,154 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.Filter -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; - using System.Text.RegularExpressions; +using System; +using System.Text.RegularExpressions; - using log4net; - using log4net.Core; - using log4net.Util; +using log4net; +using log4net.Core; +using log4net.Util; - /// - /// Simple filter to match a string an event property. - /// - /// - /// - /// Simple filter to match a string in the value for a - /// specific event property. - /// - /// - /// Nicko Cadell. - public class PropertyFilter : StringMatchFilter +namespace log4net.Filter +{ + /// + /// Simple filter to match a string an event property + /// + /// + /// + /// Simple filter to match a string in the value for a + /// specific event property + /// + /// + /// Nicko Cadell + public class PropertyFilter : StringMatchFilter { - /// - /// The key to use to lookup the string from the event properties. - /// + /// + /// The key to use to lookup the string from the event properties + /// private string m_key; /// - /// Initializes a new instance of the class. - /// Default constructor. - /// - public PropertyFilter() - { + /// Default constructor + /// + public PropertyFilter() + { } - /// - /// Gets or sets the key to lookup in the event properties and then match against. - /// - /// - /// - /// The key name to use to lookup in the properties map of the - /// . The match will be performed against - /// the value of this property if it exists. - /// - /// - public string Key - { - get { return this.m_key; } - set { this.m_key = value; } + /// + /// The key to lookup in the event properties and then match against. + /// + /// + /// + /// The key name to use to lookup in the properties map of the + /// . The match will be performed against + /// the value of this property if it exists. + /// + /// + public string Key + { + get { return this.m_key; } + set { this.m_key = value; } } - /// - /// Check if this filter should allow the event to be logged. - /// - /// the event being logged. - /// see remarks. - /// - /// - /// The event property for the is matched against - /// the . - /// If the occurs as a substring within - /// the property value then a match will have occurred. If no match occurs - /// this function will return - /// allowing other filters to check the event. If a match occurs then - /// the value of is checked. If it is - /// true then is returned otherwise - /// is returned. - /// - /// - public override FilterDecision Decide(LoggingEvent loggingEvent) - { - if (loggingEvent == null) - { - throw new ArgumentNullException("loggingEvent"); - } - - // Check if we have a key to lookup the event property value with - if (this.m_key == null) - { - // We cannot filter so allow the filter chain - // to continue processing - return FilterDecision.Neutral; - } - - // Lookup the string to match in from the properties using - // the key specified. - object msgObj = loggingEvent.LookupProperty(this.m_key); - - // Use an ObjectRenderer to convert the property value to a string - string msg = loggingEvent.Repository.RendererMap.FindAndRender(msgObj); - - // Check if we have been setup to filter - if (msg == null || (this.m_stringToMatch == null && this.m_regexToMatch == null)) - { - // We cannot filter so allow the filter chain - // to continue processing - return FilterDecision.Neutral; - } - - // Firstly check if we are matching using a regex - if (this.m_regexToMatch != null) - { - // Check the regex - if (this.m_regexToMatch.Match(msg).Success == false) - { - // No match, continue processing - return FilterDecision.Neutral; - } - - // we've got a match - if (this.m_acceptOnMatch) - { - return FilterDecision.Accept; - } + /// + /// Check if this filter should allow the event to be logged + /// + /// the event being logged + /// see remarks + /// + /// + /// The event property for the is matched against + /// the . + /// If the occurs as a substring within + /// the property value then a match will have occurred. If no match occurs + /// this function will return + /// allowing other filters to check the event. If a match occurs then + /// the value of is checked. If it is + /// true then is returned otherwise + /// is returned. + /// + /// + public override FilterDecision Decide(LoggingEvent loggingEvent) + { + if (loggingEvent == null) + { + throw new ArgumentNullException("loggingEvent"); + } + + // Check if we have a key to lookup the event property value with + if (this.m_key == null) + { + // We cannot filter so allow the filter chain + // to continue processing + return FilterDecision.Neutral; + } + + // Lookup the string to match in from the properties using + // the key specified. + object msgObj = loggingEvent.LookupProperty(this.m_key); + + // Use an ObjectRenderer to convert the property value to a string + string msg = loggingEvent.Repository.RendererMap.FindAndRender(msgObj); - return FilterDecision.Deny; - } - else if (this.m_stringToMatch != null) - { - // Check substring match - if (msg.IndexOf(this.m_stringToMatch) == -1) - { - // No match, continue processing - return FilterDecision.Neutral; - } - - // we've got a match - if (this.m_acceptOnMatch) - { - return FilterDecision.Accept; - } + // Check if we have been setup to filter + if (msg == null || (this.m_stringToMatch == null && this.m_regexToMatch == null)) + { + // We cannot filter so allow the filter chain + // to continue processing + return FilterDecision.Neutral; + } + + // Firstly check if we are matching using a regex + if (this.m_regexToMatch != null) + { + // Check the regex + if (this.m_regexToMatch.Match(msg).Success == false) + { + // No match, continue processing + return FilterDecision.Neutral; + } - return FilterDecision.Deny; - } + // we've got a match + if (this.m_acceptOnMatch) + { + return FilterDecision.Accept; + } + return FilterDecision.Deny; + } + else if (this.m_stringToMatch != null) + { + // Check substring match + if (msg.IndexOf(this.m_stringToMatch) == -1) + { + // No match, continue processing + return FilterDecision.Neutral; + } - return FilterDecision.Neutral; + // we've got a match + if (this.m_acceptOnMatch) + { + return FilterDecision.Accept; + } + return FilterDecision.Deny; + } + return FilterDecision.Neutral; } - } -} + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Filter/StringMatchFilter.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Filter/StringMatchFilter.cs index 39f1c97be5f..c442c7ab72d 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Filter/StringMatchFilter.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Filter/StringMatchFilter.cs @@ -1,233 +1,230 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.Filter -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; - using System.Text.RegularExpressions; - - using log4net; - using log4net.Core; - using log4net.Util; - - /// - /// Simple filter to match a string in the rendered message. - /// - /// - /// - /// Simple filter to match a string in the rendered message. - /// - /// - /// Nicko Cadell. - /// Gert Driesen. - public class StringMatchFilter : FilterSkeleton +using System; +using System.Text.RegularExpressions; + +using log4net; +using log4net.Core; +using log4net.Util; + +namespace log4net.Filter +{ + /// + /// Simple filter to match a string in the rendered message + /// + /// + /// + /// Simple filter to match a string in the rendered message + /// + /// + /// Nicko Cadell + /// Gert Driesen + public class StringMatchFilter : FilterSkeleton { - /// - /// Flag to indicate the behavior when we have a match. - /// - protected bool m_acceptOnMatch = true; - - /// - /// The string to substring match against the message. - /// - protected string m_stringToMatch; - - /// - /// A string regex to match. - /// - protected string m_stringRegexToMatch; - - /// - /// A regex object to match (generated from m_stringRegexToMatch). - /// + /// + /// Flag to indicate the behavior when we have a match + /// + protected bool m_acceptOnMatch = true; + + /// + /// The string to substring match against the message + /// + protected string m_stringToMatch; + + /// + /// A string regex to match + /// + protected string m_stringRegexToMatch; + + /// + /// A regex object to match (generated from m_stringRegexToMatch) + /// protected Regex m_regexToMatch; /// - /// Initializes a new instance of the class. - /// Default constructor. - /// - public StringMatchFilter() - { + /// Default constructor + /// + public StringMatchFilter() + { } - /// - /// Initialize and precompile the Regex if required. - /// - /// - /// - /// This is part of the delayed object - /// activation scheme. The method must - /// be called on this object after the configuration properties have - /// been set. Until is called this - /// object is in an undefined state and must not be used. - /// - /// - /// If any of the configuration properties are modified then - /// must be called again. - /// - /// - public override void ActivateOptions() - { - if (this.m_stringRegexToMatch != null) - { -#if NETSTANDARD1_3 - m_regexToMatch = new Regex(m_stringRegexToMatch); -#else - this.m_regexToMatch = new Regex(this.m_stringRegexToMatch, RegexOptions.Compiled); -#endif - } + /// + /// Initialize and precompile the Regex if required + /// + /// + /// + /// This is part of the delayed object + /// activation scheme. The method must + /// be called on this object after the configuration properties have + /// been set. Until is called this + /// object is in an undefined state and must not be used. + /// + /// + /// If any of the configuration properties are modified then + /// must be called again. + /// + /// + public override void ActivateOptions() + { + if (this.m_stringRegexToMatch != null) + { +#if NETSTANDARD1_3 + m_regexToMatch = new Regex(m_stringRegexToMatch); +#else + this.m_regexToMatch = new Regex(this.m_stringRegexToMatch, RegexOptions.Compiled); +#endif + } } - /// - /// Gets or sets a value indicating whether when matching or . - /// - /// - /// - /// The property is a flag that determines - /// the behavior when a matching is found. If the - /// flag is set to true then the filter will the - /// logging event, otherwise it will the event. - /// - /// - /// The default is true i.e. to the event. - /// - /// - public bool AcceptOnMatch - { - get { return this.m_acceptOnMatch; } - set { this.m_acceptOnMatch = value; } - } - - /// - /// Gets or sets the static string to match. - /// - /// - /// - /// The string that will be substring matched against - /// the rendered message. If the message contains this - /// string then the filter will match. If a match is found then - /// the result depends on the value of . - /// - /// - /// One of or - /// must be specified. - /// - /// - public string StringToMatch - { - get { return this.m_stringToMatch; } - set { this.m_stringToMatch = value; } - } - - /// - /// Gets or sets the regular expression to match. - /// - /// - /// - /// The regular expression pattern that will be matched against - /// the rendered message. If the message matches this - /// pattern then the filter will match. If a match is found then - /// the result depends on the value of . - /// - /// - /// One of or - /// must be specified. - /// - /// - public string RegexToMatch - { - get { return this.m_stringRegexToMatch; } - set { this.m_stringRegexToMatch = value; } + /// + /// when matching or + /// + /// + /// + /// The property is a flag that determines + /// the behavior when a matching is found. If the + /// flag is set to true then the filter will the + /// logging event, otherwise it will the event. + /// + /// + /// The default is true i.e. to the event. + /// + /// + public bool AcceptOnMatch + { + get { return this.m_acceptOnMatch; } + set { this.m_acceptOnMatch = value; } } - /// - /// Check if this filter should allow the event to be logged. - /// - /// the event being logged. - /// see remarks. - /// - /// - /// The rendered message is matched against the . - /// If the occurs as a substring within - /// the message then a match will have occurred. If no match occurs - /// this function will return - /// allowing other filters to check the event. If a match occurs then - /// the value of is checked. If it is - /// true then is returned otherwise - /// is returned. - /// - /// - public override FilterDecision Decide(LoggingEvent loggingEvent) - { - if (loggingEvent == null) - { - throw new ArgumentNullException("loggingEvent"); - } - - string msg = loggingEvent.RenderedMessage; - - // Check if we have been setup to filter - if (msg == null || (this.m_stringToMatch == null && this.m_regexToMatch == null)) - { - // We cannot filter so allow the filter chain - // to continue processing - return FilterDecision.Neutral; - } - - // Firstly check if we are matching using a regex - if (this.m_regexToMatch != null) - { - // Check the regex - if (this.m_regexToMatch.Match(msg).Success == false) - { - // No match, continue processing - return FilterDecision.Neutral; - } - - // we've got a match - if (this.m_acceptOnMatch) - { - return FilterDecision.Accept; - } - - return FilterDecision.Deny; - } - else if (this.m_stringToMatch != null) - { - // Check substring match - if (msg.IndexOf(this.m_stringToMatch) == -1) - { - // No match, continue processing - return FilterDecision.Neutral; - } - - // we've got a match - if (this.m_acceptOnMatch) - { - return FilterDecision.Accept; - } - - return FilterDecision.Deny; - } - - return FilterDecision.Neutral; + /// + /// Sets the static string to match + /// + /// + /// + /// The string that will be substring matched against + /// the rendered message. If the message contains this + /// string then the filter will match. If a match is found then + /// the result depends on the value of . + /// + /// + /// One of or + /// must be specified. + /// + /// + public string StringToMatch + { + get { return this.m_stringToMatch; } + set { this.m_stringToMatch = value; } + } + + /// + /// Sets the regular expression to match + /// + /// + /// + /// The regular expression pattern that will be matched against + /// the rendered message. If the message matches this + /// pattern then the filter will match. If a match is found then + /// the result depends on the value of . + /// + /// + /// One of or + /// must be specified. + /// + /// + public string RegexToMatch + { + get { return this.m_stringRegexToMatch; } + set { this.m_stringRegexToMatch = value; } + } + + /// + /// Check if this filter should allow the event to be logged + /// + /// the event being logged + /// see remarks + /// + /// + /// The rendered message is matched against the . + /// If the occurs as a substring within + /// the message then a match will have occurred. If no match occurs + /// this function will return + /// allowing other filters to check the event. If a match occurs then + /// the value of is checked. If it is + /// true then is returned otherwise + /// is returned. + /// + /// + public override FilterDecision Decide(LoggingEvent loggingEvent) + { + if (loggingEvent == null) + { + throw new ArgumentNullException("loggingEvent"); + } + + string msg = loggingEvent.RenderedMessage; + + // Check if we have been setup to filter + if (msg == null || (this.m_stringToMatch == null && this.m_regexToMatch == null)) + { + // We cannot filter so allow the filter chain + // to continue processing + return FilterDecision.Neutral; + } + + // Firstly check if we are matching using a regex + if (this.m_regexToMatch != null) + { + // Check the regex + if (this.m_regexToMatch.Match(msg).Success == false) + { + // No match, continue processing + return FilterDecision.Neutral; + } + + // we've got a match + if (this.m_acceptOnMatch) + { + return FilterDecision.Accept; + } + return FilterDecision.Deny; + } + else if (this.m_stringToMatch != null) + { + // Check substring match + if (msg.IndexOf(this.m_stringToMatch) == -1) + { + // No match, continue processing + return FilterDecision.Neutral; + } + + // we've got a match + if (this.m_acceptOnMatch) + { + return FilterDecision.Accept; + } + return FilterDecision.Deny; + } + return FilterDecision.Neutral; + } - } -} + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/GlobalContext.cs b/DNN Platform/DotNetNuke.Log4net/log4net/GlobalContext.cs index 5d8326f95d0..b4d826aa403 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/GlobalContext.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/GlobalContext.cs @@ -1,92 +1,91 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; - using System.Collections; +using System; +using System.Collections; - using log4net.Util; +using log4net.Util; - /// - /// The log4net Global Context. - /// - /// - /// - /// The GlobalContext provides a location for global debugging - /// information to be stored. - /// - /// - /// The global context has a properties map and these properties can - /// be included in the output of log messages. The - /// supports selecting and outputing these properties. - /// - /// - /// By default the log4net:HostName property is set to the name of - /// the current machine. - /// - /// - /// - /// - /// GlobalContext.Properties["hostname"] = Environment.MachineName; - /// - /// - /// - /// Nicko Cadell. - public sealed class GlobalContext +namespace log4net +{ + /// + /// The log4net Global Context. + /// + /// + /// + /// The GlobalContext provides a location for global debugging + /// information to be stored. + /// + /// + /// The global context has a properties map and these properties can + /// be included in the output of log messages. The + /// supports selecting and outputing these properties. + /// + /// + /// By default the log4net:HostName property is set to the name of + /// the current machine. + /// + /// + /// + /// + /// GlobalContext.Properties["hostname"] = Environment.MachineName; + /// + /// + /// + /// Nicko Cadell + public sealed class GlobalContext { /// - /// Initializes a new instance of the class. - /// Private Constructor. - /// - /// - /// Uses a private access modifier to prevent instantiation of this class. - /// - private GlobalContext() - { + /// Private Constructor. + /// + /// + /// Uses a private access modifier to prevent instantiation of this class. + /// + private GlobalContext() + { } - static GlobalContext() - { - Properties[log4net.Core.LoggingEvent.HostNameProperty] = SystemInfo.HostName; + static GlobalContext() + { + Properties[Core.LoggingEvent.HostNameProperty] = SystemInfo.HostName; } - /// - /// Gets the global properties map. - /// - /// - /// The global properties map. - /// - /// - /// - /// The global properties map. - /// - /// - public static GlobalContextProperties Properties - { - get { return s_properties; } + /// + /// The global properties map. + /// + /// + /// The global properties map. + /// + /// + /// + /// The global properties map. + /// + /// + public static GlobalContextProperties Properties + { + get { return s_properties; } } - /// - /// The global context properties instance. - /// + /// + /// The global context properties instance + /// private static readonly GlobalContextProperties s_properties = new GlobalContextProperties(); - } -} + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/ILog.cs b/DNN Platform/DotNetNuke.Log4net/log4net/ILog.cs index d882d5e9472..6a358d86d78 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/ILog.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/ILog.cs @@ -1,961 +1,961 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; - using System.Reflection; - - using log4net.Core; - - /// - /// The ILog interface is use by application to log messages into - /// the log4net framework. - /// - /// - /// - /// Use the to obtain logger instances - /// that implement this interface. The - /// static method is used to get logger instances. - /// - /// - /// This class contains methods for logging at different levels and also - /// has properties for determining if those logging levels are - /// enabled in the current configuration. - /// - /// - /// This interface can be implemented in different ways. This documentation - /// specifies reasonable behavior that a caller can expect from the actual - /// implementation, however different implementations reserve the right to - /// do things differently. - /// - /// - /// Simple example of logging messages. - /// - /// ILog log = LogManager.GetLogger("application-log"); - /// - /// log.Info("Application Start"); - /// log.Debug("This is a debug message"); - /// - /// if (log.IsDebugEnabled) - /// { - /// log.Debug("This is another debug message"); - /// } - /// - /// - /// - /// - /// Nicko Cadell. - /// Gert Driesen. - public interface ILog : ILoggerWrapper - { - /// Log a message object with the level. - /// - /// Log a message object with the level. - /// - /// The message object to log. - /// - /// - /// This method first checks if this logger is DEBUG - /// enabled by comparing the level of this logger with the - /// level. If this logger is - /// DEBUG enabled, then it converts the message object - /// (passed as parameter) to a string by invoking the appropriate - /// . It then - /// proceeds to call all the registered appenders in this logger - /// and also higher in the hierarchy depending on the value of - /// the additivity flag. - /// - /// WARNING Note that passing an - /// to this method will print the name of the - /// but no stack trace. To print a stack trace use the - /// form instead. - /// - /// - /// - /// - void Debug(object message); - - /// - /// Log a message object with the level including - /// the stack trace of the passed - /// as a parameter. - /// - /// The message object to log. - /// The exception to log, including its stack trace. - /// - /// - /// See the form for more detailed information. - /// - /// - /// - /// - void Debug(object message, Exception exception); - - /// Log a formatted string with the level. - /// - /// Logs a formatted message string with the level. - /// - /// A String containing zero or more format items. - /// An Object array containing zero or more objects to format. - /// - /// - /// The message is formatted using the String.Format method. See - /// for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - /// - /// - void DebugFormat(string format, params object[] args); - - /// - /// Logs a formatted message string with the level. - /// - /// A String containing zero or more format items. - /// An Object to format. - /// - /// - /// The message is formatted using the String.Format method. See - /// for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - /// - /// - void DebugFormat(string format, object arg0); - - /// - /// Logs a formatted message string with the level. - /// - /// A String containing zero or more format items. - /// An Object to format. - /// An Object to format. - /// - /// - /// The message is formatted using the String.Format method. See - /// for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - /// - /// - void DebugFormat(string format, object arg0, object arg1); - - /// - /// Logs a formatted message string with the level. - /// - /// A String containing zero or more format items. - /// An Object to format. - /// An Object to format. - /// An Object to format. - /// - /// - /// The message is formatted using the String.Format method. See - /// for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - /// - /// - void DebugFormat(string format, object arg0, object arg1, object arg2); - - /// - /// Logs a formatted message string with the level. - /// - /// An that supplies culture-specific formatting information. - /// A String containing zero or more format items. - /// An Object array containing zero or more objects to format. - /// - /// - /// The message is formatted using the String.Format method. See - /// for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - /// - /// - void DebugFormat(IFormatProvider provider, string format, params object[] args); - - /// Log a message object with the level. - /// - /// Logs a message object with the level. - /// - /// - /// - /// This method first checks if this logger is INFO - /// enabled by comparing the level of this logger with the - /// level. If this logger is - /// INFO enabled, then it converts the message object - /// (passed as parameter) to a string by invoking the appropriate - /// . It then - /// proceeds to call all the registered appenders in this logger - /// and also higher in the hierarchy depending on the value of the - /// additivity flag. - /// - /// WARNING Note that passing an - /// to this method will print the name of the - /// but no stack trace. To print a stack trace use the - /// form instead. - /// - /// - /// The message object to log. - /// - /// - void Info(object message); - - /// - /// Logs a message object with the INFO level including - /// the stack trace of the passed - /// as a parameter. - /// - /// The message object to log. - /// The exception to log, including its stack trace. - /// - /// - /// See the form for more detailed information. - /// - /// - /// - /// - void Info(object message, Exception exception); - - /// Log a formatted message string with the level. - /// - /// Logs a formatted message string with the level. - /// - /// A String containing zero or more format items. - /// An Object array containing zero or more objects to format. - /// - /// - /// The message is formatted using the String.Format method. See - /// for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - /// - /// - void InfoFormat(string format, params object[] args); - - /// - /// Logs a formatted message string with the level. - /// - /// A String containing zero or more format items. - /// An Object to format. - /// - /// - /// The message is formatted using the String.Format method. See - /// for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - /// - /// - void InfoFormat(string format, object arg0); - - /// - /// Logs a formatted message string with the level. - /// - /// A String containing zero or more format items. - /// An Object to format. - /// An Object to format. - /// - /// - /// The message is formatted using the String.Format method. See - /// for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - /// - /// - void InfoFormat(string format, object arg0, object arg1); - - /// - /// Logs a formatted message string with the level. - /// - /// A String containing zero or more format items. - /// An Object to format. - /// An Object to format. - /// An Object to format. - /// - /// - /// The message is formatted using the String.Format method. See - /// for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - /// - /// - void InfoFormat(string format, object arg0, object arg1, object arg2); - - /// - /// Logs a formatted message string with the level. - /// - /// An that supplies culture-specific formatting information. - /// A String containing zero or more format items. - /// An Object array containing zero or more objects to format. - /// - /// - /// The message is formatted using the String.Format method. See - /// for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - /// - /// - void InfoFormat(IFormatProvider provider, string format, params object[] args); - - /// Log a message object with the level. - /// - /// Log a message object with the level. - /// - /// - /// - /// This method first checks if this logger is WARN - /// enabled by comparing the level of this logger with the - /// level. If this logger is - /// WARN enabled, then it converts the message object - /// (passed as parameter) to a string by invoking the appropriate - /// . It then - /// proceeds to call all the registered appenders in this logger - /// and also higher in the hierarchy depending on the value of the - /// additivity flag. - /// - /// WARNING Note that passing an - /// to this method will print the name of the - /// but no stack trace. To print a stack trace use the - /// form instead. - /// - /// - /// The message object to log. - /// - /// - void Warn(object message); - - /// - /// Log a message object with the level including - /// the stack trace of the passed - /// as a parameter. - /// - /// The message object to log. - /// The exception to log, including its stack trace. - /// - /// - /// See the form for more detailed information. - /// - /// - /// - /// - void Warn(object message, Exception exception); - - /// Log a formatted message string with the level. - /// - /// Logs a formatted message string with the level. - /// - /// A String containing zero or more format items. - /// An Object array containing zero or more objects to format. - /// - /// - /// The message is formatted using the String.Format method. See - /// for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - /// - /// - void WarnFormat(string format, params object[] args); - - /// - /// Logs a formatted message string with the level. - /// - /// A String containing zero or more format items. - /// An Object to format. - /// - /// - /// The message is formatted using the String.Format method. See - /// for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - /// - /// - void WarnFormat(string format, object arg0); - - /// - /// Logs a formatted message string with the level. - /// - /// A String containing zero or more format items. - /// An Object to format. - /// An Object to format. - /// - /// - /// The message is formatted using the String.Format method. See - /// for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - /// - /// - void WarnFormat(string format, object arg0, object arg1); - - /// - /// Logs a formatted message string with the level. - /// - /// A String containing zero or more format items. - /// An Object to format. - /// An Object to format. - /// An Object to format. - /// - /// - /// The message is formatted using the String.Format method. See - /// for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - /// - /// - void WarnFormat(string format, object arg0, object arg1, object arg2); - - /// - /// Logs a formatted message string with the level. - /// - /// An that supplies culture-specific formatting information. - /// A String containing zero or more format items. - /// An Object array containing zero or more objects to format. - /// - /// - /// The message is formatted using the String.Format method. See - /// for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - /// - /// - void WarnFormat(IFormatProvider provider, string format, params object[] args); - - /// Log a message object with the level. - /// - /// Logs a message object with the level. - /// - /// The message object to log. - /// - /// - /// This method first checks if this logger is ERROR - /// enabled by comparing the level of this logger with the - /// level. If this logger is - /// ERROR enabled, then it converts the message object - /// (passed as parameter) to a string by invoking the appropriate - /// . It then - /// proceeds to call all the registered appenders in this logger - /// and also higher in the hierarchy depending on the value of the - /// additivity flag. - /// - /// WARNING Note that passing an - /// to this method will print the name of the - /// but no stack trace. To print a stack trace use the - /// form instead. - /// - /// - /// - /// - void Error(object message); - - /// - /// Log a message object with the level including - /// the stack trace of the passed - /// as a parameter. - /// - /// The message object to log. - /// The exception to log, including its stack trace. - /// - /// - /// See the form for more detailed information. - /// - /// - /// - /// - void Error(object message, Exception exception); - - /// Log a formatted message string with the level. - /// - /// Logs a formatted message string with the level. - /// - /// A String containing zero or more format items. - /// An Object array containing zero or more objects to format. - /// - /// - /// The message is formatted using the String.Format method. See - /// for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - /// - /// - void ErrorFormat(string format, params object[] args); - - /// - /// Logs a formatted message string with the level. - /// - /// A String containing zero or more format items. - /// An Object to format. - /// - /// - /// The message is formatted using the String.Format method. See - /// for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - /// - /// - void ErrorFormat(string format, object arg0); - - /// - /// Logs a formatted message string with the level. - /// - /// A String containing zero or more format items. - /// An Object to format. - /// An Object to format. - /// - /// - /// The message is formatted using the String.Format method. See - /// for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - /// - /// - void ErrorFormat(string format, object arg0, object arg1); - - /// - /// Logs a formatted message string with the level. - /// - /// A String containing zero or more format items. - /// An Object to format. - /// An Object to format. - /// An Object to format. - /// - /// - /// The message is formatted using the String.Format method. See - /// for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - /// - /// - void ErrorFormat(string format, object arg0, object arg1, object arg2); - - /// - /// Logs a formatted message string with the level. - /// - /// An that supplies culture-specific formatting information. - /// A String containing zero or more format items. - /// An Object array containing zero or more objects to format. - /// - /// - /// The message is formatted using the String.Format method. See - /// for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - /// - /// - void ErrorFormat(IFormatProvider provider, string format, params object[] args); - - /// Log a message object with the level. - /// - /// Log a message object with the level. - /// - /// - /// - /// This method first checks if this logger is FATAL - /// enabled by comparing the level of this logger with the - /// level. If this logger is - /// FATAL enabled, then it converts the message object - /// (passed as parameter) to a string by invoking the appropriate - /// . It then - /// proceeds to call all the registered appenders in this logger - /// and also higher in the hierarchy depending on the value of the - /// additivity flag. - /// - /// WARNING Note that passing an - /// to this method will print the name of the - /// but no stack trace. To print a stack trace use the - /// form instead. - /// - /// - /// The message object to log. - /// - /// - void Fatal(object message); - - /// - /// Log a message object with the level including - /// the stack trace of the passed - /// as a parameter. - /// - /// The message object to log. - /// The exception to log, including its stack trace. - /// - /// - /// See the form for more detailed information. - /// - /// - /// - /// - void Fatal(object message, Exception exception); - - /// Log a formatted message string with the level. - /// - /// Logs a formatted message string with the level. - /// - /// A String containing zero or more format items. - /// An Object array containing zero or more objects to format. - /// - /// - /// The message is formatted using the String.Format method. See - /// for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - /// - /// - void FatalFormat(string format, params object[] args); - - /// - /// Logs a formatted message string with the level. - /// - /// A String containing zero or more format items. - /// An Object to format. - /// - /// - /// The message is formatted using the String.Format method. See - /// for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - /// - /// - void FatalFormat(string format, object arg0); - - /// - /// Logs a formatted message string with the level. - /// - /// A String containing zero or more format items. - /// An Object to format. - /// An Object to format. - /// - /// - /// The message is formatted using the String.Format method. See - /// for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - /// - /// - void FatalFormat(string format, object arg0, object arg1); - - /// - /// Logs a formatted message string with the level. - /// - /// A String containing zero or more format items. - /// An Object to format. - /// An Object to format. - /// An Object to format. - /// - /// - /// The message is formatted using the String.Format method. See - /// for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - /// - /// - void FatalFormat(string format, object arg0, object arg1, object arg2); - - /// - /// Logs a formatted message string with the level. - /// - /// An that supplies culture-specific formatting information. - /// A String containing zero or more format items. - /// An Object array containing zero or more objects to format. - /// - /// - /// The message is formatted using the String.Format method. See - /// for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - /// - /// - void FatalFormat(IFormatProvider provider, string format, params object[] args); - - /// - /// Gets a value indicating whether checks if this logger is enabled for the level. - /// - /// - /// true if this logger is enabled for events, false otherwise. - /// - /// - /// - /// This function is intended to lessen the computational cost of - /// disabled log debug statements. - /// - /// For some ILog interface log, when you write: - /// - /// log.Debug("This is entry number: " + i ); - /// - /// - /// You incur the cost constructing the message, string construction and concatenation in - /// this case, regardless of whether the message is logged or not. - /// - /// - /// If you are worried about speed (who isn't), then you should write: - /// - /// - /// if (log.IsDebugEnabled) - /// { - /// log.Debug("This is entry number: " + i ); - /// } - /// - /// - /// This way you will not incur the cost of parameter - /// construction if debugging is disabled for log. On - /// the other hand, if the log is debug enabled, you - /// will incur the cost of evaluating whether the logger is debug - /// enabled twice. Once in and once in - /// the . This is an insignificant overhead - /// since evaluating a logger takes about 1% of the time it - /// takes to actually log. This is the preferred style of logging. - /// - /// Alternatively if your logger is available statically then the is debug - /// enabled state can be stored in a static variable like this: - /// - /// - /// private static readonly bool isDebugEnabled = log.IsDebugEnabled; - /// - /// - /// Then when you come to log you can write: - /// - /// - /// if (isDebugEnabled) - /// { - /// log.Debug("This is entry number: " + i ); - /// } - /// - /// - /// This way the debug enabled state is only queried once - /// when the class is loaded. Using a private static readonly - /// variable is the most efficient because it is a run time constant - /// and can be heavily optimized by the JIT compiler. - /// - /// - /// Of course if you use a static readonly variable to - /// hold the enabled state of the logger then you cannot - /// change the enabled state at runtime to vary the logging - /// that is produced. You have to decide if you need absolute - /// speed or runtime flexibility. - /// - /// - /// - /// - bool IsDebugEnabled { get; } - - /// - /// Gets a value indicating whether checks if this logger is enabled for the level. - /// - /// - /// true if this logger is enabled for events, false otherwise. - /// - /// - /// For more information see . - /// - /// - /// - /// - bool IsInfoEnabled { get; } - - /// - /// Gets a value indicating whether checks if this logger is enabled for the level. - /// - /// - /// true if this logger is enabled for events, false otherwise. - /// - /// - /// For more information see . - /// - /// - /// - /// - bool IsWarnEnabled { get; } - - /// - /// Gets a value indicating whether checks if this logger is enabled for the level. - /// - /// - /// true if this logger is enabled for events, false otherwise. - /// - /// - /// For more information see . - /// - /// - /// - /// - bool IsErrorEnabled { get; } - - /// - /// Gets a value indicating whether checks if this logger is enabled for the level. - /// - /// - /// true if this logger is enabled for events, false otherwise. - /// - /// - /// For more information see . - /// - /// - /// - /// - bool IsFatalEnabled { get; } - } -} +using System; +using System.Reflection; + +using log4net.Core; + +namespace log4net +{ + /// + /// The ILog interface is use by application to log messages into + /// the log4net framework. + /// + /// + /// + /// Use the to obtain logger instances + /// that implement this interface. The + /// static method is used to get logger instances. + /// + /// + /// This class contains methods for logging at different levels and also + /// has properties for determining if those logging levels are + /// enabled in the current configuration. + /// + /// + /// This interface can be implemented in different ways. This documentation + /// specifies reasonable behavior that a caller can expect from the actual + /// implementation, however different implementations reserve the right to + /// do things differently. + /// + /// + /// Simple example of logging messages + /// + /// ILog log = LogManager.GetLogger("application-log"); + /// + /// log.Info("Application Start"); + /// log.Debug("This is a debug message"); + /// + /// if (log.IsDebugEnabled) + /// { + /// log.Debug("This is another debug message"); + /// } + /// + /// + /// + /// + /// Nicko Cadell + /// Gert Driesen + public interface ILog : ILoggerWrapper + { + /// Log a message object with the level. + /// + /// Log a message object with the level. + /// + /// The message object to log. + /// + /// + /// This method first checks if this logger is DEBUG + /// enabled by comparing the level of this logger with the + /// level. If this logger is + /// DEBUG enabled, then it converts the message object + /// (passed as parameter) to a string by invoking the appropriate + /// . It then + /// proceeds to call all the registered appenders in this logger + /// and also higher in the hierarchy depending on the value of + /// the additivity flag. + /// + /// WARNING Note that passing an + /// to this method will print the name of the + /// but no stack trace. To print a stack trace use the + /// form instead. + /// + /// + /// + /// + void Debug(object message); + + /// + /// Log a message object with the level including + /// the stack trace of the passed + /// as a parameter. + /// + /// The message object to log. + /// The exception to log, including its stack trace. + /// + /// + /// See the form for more detailed information. + /// + /// + /// + /// + void Debug(object message, Exception exception); + + /// Log a formatted string with the level. + /// + /// Logs a formatted message string with the level. + /// + /// A String containing zero or more format items + /// An Object array containing zero or more objects to format + /// + /// + /// The message is formatted using the String.Format method. See + /// for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + /// + /// + void DebugFormat(string format, params object[] args); + + /// + /// Logs a formatted message string with the level. + /// + /// A String containing zero or more format items + /// An Object to format + /// + /// + /// The message is formatted using the String.Format method. See + /// for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + /// + /// + void DebugFormat(string format, object arg0); + + /// + /// Logs a formatted message string with the level. + /// + /// A String containing zero or more format items + /// An Object to format + /// An Object to format + /// + /// + /// The message is formatted using the String.Format method. See + /// for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + /// + /// + void DebugFormat(string format, object arg0, object arg1); + + /// + /// Logs a formatted message string with the level. + /// + /// A String containing zero or more format items + /// An Object to format + /// An Object to format + /// An Object to format + /// + /// + /// The message is formatted using the String.Format method. See + /// for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + /// + /// + void DebugFormat(string format, object arg0, object arg1, object arg2); + + /// + /// Logs a formatted message string with the level. + /// + /// An that supplies culture-specific formatting information + /// A String containing zero or more format items + /// An Object array containing zero or more objects to format + /// + /// + /// The message is formatted using the String.Format method. See + /// for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + /// + /// + void DebugFormat(IFormatProvider provider, string format, params object[] args); + + /// Log a message object with the level. + /// + /// Logs a message object with the level. + /// + /// + /// + /// This method first checks if this logger is INFO + /// enabled by comparing the level of this logger with the + /// level. If this logger is + /// INFO enabled, then it converts the message object + /// (passed as parameter) to a string by invoking the appropriate + /// . It then + /// proceeds to call all the registered appenders in this logger + /// and also higher in the hierarchy depending on the value of the + /// additivity flag. + /// + /// WARNING Note that passing an + /// to this method will print the name of the + /// but no stack trace. To print a stack trace use the + /// form instead. + /// + /// + /// The message object to log. + /// + /// + void Info(object message); + + /// + /// Logs a message object with the INFO level including + /// the stack trace of the passed + /// as a parameter. + /// + /// The message object to log. + /// The exception to log, including its stack trace. + /// + /// + /// See the form for more detailed information. + /// + /// + /// + /// + void Info(object message, Exception exception); + + /// Log a formatted message string with the level. + /// + /// Logs a formatted message string with the level. + /// + /// A String containing zero or more format items + /// An Object array containing zero or more objects to format + /// + /// + /// The message is formatted using the String.Format method. See + /// for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + /// + /// + void InfoFormat(string format, params object[] args); + + /// + /// Logs a formatted message string with the level. + /// + /// A String containing zero or more format items + /// An Object to format + /// + /// + /// The message is formatted using the String.Format method. See + /// for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + /// + /// + void InfoFormat(string format, object arg0); + + /// + /// Logs a formatted message string with the level. + /// + /// A String containing zero or more format items + /// An Object to format + /// An Object to format + /// + /// + /// The message is formatted using the String.Format method. See + /// for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + /// + /// + void InfoFormat(string format, object arg0, object arg1); + + /// + /// Logs a formatted message string with the level. + /// + /// A String containing zero or more format items + /// An Object to format + /// An Object to format + /// An Object to format + /// + /// + /// The message is formatted using the String.Format method. See + /// for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + /// + /// + void InfoFormat(string format, object arg0, object arg1, object arg2); + + /// + /// Logs a formatted message string with the level. + /// + /// An that supplies culture-specific formatting information + /// A String containing zero or more format items + /// An Object array containing zero or more objects to format + /// + /// + /// The message is formatted using the String.Format method. See + /// for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + /// + /// + void InfoFormat(IFormatProvider provider, string format, params object[] args); + + /// Log a message object with the level. + /// + /// Log a message object with the level. + /// + /// + /// + /// This method first checks if this logger is WARN + /// enabled by comparing the level of this logger with the + /// level. If this logger is + /// WARN enabled, then it converts the message object + /// (passed as parameter) to a string by invoking the appropriate + /// . It then + /// proceeds to call all the registered appenders in this logger + /// and also higher in the hierarchy depending on the value of the + /// additivity flag. + /// + /// WARNING Note that passing an + /// to this method will print the name of the + /// but no stack trace. To print a stack trace use the + /// form instead. + /// + /// + /// The message object to log. + /// + /// + void Warn(object message); + + /// + /// Log a message object with the level including + /// the stack trace of the passed + /// as a parameter. + /// + /// The message object to log. + /// The exception to log, including its stack trace. + /// + /// + /// See the form for more detailed information. + /// + /// + /// + /// + void Warn(object message, Exception exception); + + /// Log a formatted message string with the level. + /// + /// Logs a formatted message string with the level. + /// + /// A String containing zero or more format items + /// An Object array containing zero or more objects to format + /// + /// + /// The message is formatted using the String.Format method. See + /// for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + /// + /// + void WarnFormat(string format, params object[] args); + + /// + /// Logs a formatted message string with the level. + /// + /// A String containing zero or more format items + /// An Object to format + /// + /// + /// The message is formatted using the String.Format method. See + /// for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + /// + /// + void WarnFormat(string format, object arg0); + + /// + /// Logs a formatted message string with the level. + /// + /// A String containing zero or more format items + /// An Object to format + /// An Object to format + /// + /// + /// The message is formatted using the String.Format method. See + /// for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + /// + /// + void WarnFormat(string format, object arg0, object arg1); + + /// + /// Logs a formatted message string with the level. + /// + /// A String containing zero or more format items + /// An Object to format + /// An Object to format + /// An Object to format + /// + /// + /// The message is formatted using the String.Format method. See + /// for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + /// + /// + void WarnFormat(string format, object arg0, object arg1, object arg2); + + /// + /// Logs a formatted message string with the level. + /// + /// An that supplies culture-specific formatting information + /// A String containing zero or more format items + /// An Object array containing zero or more objects to format + /// + /// + /// The message is formatted using the String.Format method. See + /// for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + /// + /// + void WarnFormat(IFormatProvider provider, string format, params object[] args); + + /// Log a message object with the level. + /// + /// Logs a message object with the level. + /// + /// The message object to log. + /// + /// + /// This method first checks if this logger is ERROR + /// enabled by comparing the level of this logger with the + /// level. If this logger is + /// ERROR enabled, then it converts the message object + /// (passed as parameter) to a string by invoking the appropriate + /// . It then + /// proceeds to call all the registered appenders in this logger + /// and also higher in the hierarchy depending on the value of the + /// additivity flag. + /// + /// WARNING Note that passing an + /// to this method will print the name of the + /// but no stack trace. To print a stack trace use the + /// form instead. + /// + /// + /// + /// + void Error(object message); + + /// + /// Log a message object with the level including + /// the stack trace of the passed + /// as a parameter. + /// + /// The message object to log. + /// The exception to log, including its stack trace. + /// + /// + /// See the form for more detailed information. + /// + /// + /// + /// + void Error(object message, Exception exception); + + /// Log a formatted message string with the level. + /// + /// Logs a formatted message string with the level. + /// + /// A String containing zero or more format items + /// An Object array containing zero or more objects to format + /// + /// + /// The message is formatted using the String.Format method. See + /// for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + /// + /// + void ErrorFormat(string format, params object[] args); + + /// + /// Logs a formatted message string with the level. + /// + /// A String containing zero or more format items + /// An Object to format + /// + /// + /// The message is formatted using the String.Format method. See + /// for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + /// + /// + void ErrorFormat(string format, object arg0); + + /// + /// Logs a formatted message string with the level. + /// + /// A String containing zero or more format items + /// An Object to format + /// An Object to format + /// + /// + /// The message is formatted using the String.Format method. See + /// for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + /// + /// + void ErrorFormat(string format, object arg0, object arg1); + + /// + /// Logs a formatted message string with the level. + /// + /// A String containing zero or more format items + /// An Object to format + /// An Object to format + /// An Object to format + /// + /// + /// The message is formatted using the String.Format method. See + /// for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + /// + /// + void ErrorFormat(string format, object arg0, object arg1, object arg2); + + /// + /// Logs a formatted message string with the level. + /// + /// An that supplies culture-specific formatting information + /// A String containing zero or more format items + /// An Object array containing zero or more objects to format + /// + /// + /// The message is formatted using the String.Format method. See + /// for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + /// + /// + void ErrorFormat(IFormatProvider provider, string format, params object[] args); + + /// Log a message object with the level. + /// + /// Log a message object with the level. + /// + /// + /// + /// This method first checks if this logger is FATAL + /// enabled by comparing the level of this logger with the + /// level. If this logger is + /// FATAL enabled, then it converts the message object + /// (passed as parameter) to a string by invoking the appropriate + /// . It then + /// proceeds to call all the registered appenders in this logger + /// and also higher in the hierarchy depending on the value of the + /// additivity flag. + /// + /// WARNING Note that passing an + /// to this method will print the name of the + /// but no stack trace. To print a stack trace use the + /// form instead. + /// + /// + /// The message object to log. + /// + /// + void Fatal(object message); + + /// + /// Log a message object with the level including + /// the stack trace of the passed + /// as a parameter. + /// + /// The message object to log. + /// The exception to log, including its stack trace. + /// + /// + /// See the form for more detailed information. + /// + /// + /// + /// + void Fatal(object message, Exception exception); + + /// Log a formatted message string with the level. + /// + /// Logs a formatted message string with the level. + /// + /// A String containing zero or more format items + /// An Object array containing zero or more objects to format + /// + /// + /// The message is formatted using the String.Format method. See + /// for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + /// + /// + void FatalFormat(string format, params object[] args); + + /// + /// Logs a formatted message string with the level. + /// + /// A String containing zero or more format items + /// An Object to format + /// + /// + /// The message is formatted using the String.Format method. See + /// for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + /// + /// + void FatalFormat(string format, object arg0); + + /// + /// Logs a formatted message string with the level. + /// + /// A String containing zero or more format items + /// An Object to format + /// An Object to format + /// + /// + /// The message is formatted using the String.Format method. See + /// for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + /// + /// + void FatalFormat(string format, object arg0, object arg1); + + /// + /// Logs a formatted message string with the level. + /// + /// A String containing zero or more format items + /// An Object to format + /// An Object to format + /// An Object to format + /// + /// + /// The message is formatted using the String.Format method. See + /// for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + /// + /// + void FatalFormat(string format, object arg0, object arg1, object arg2); + + /// + /// Logs a formatted message string with the level. + /// + /// An that supplies culture-specific formatting information + /// A String containing zero or more format items + /// An Object array containing zero or more objects to format + /// + /// + /// The message is formatted using the String.Format method. See + /// for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + /// + /// + void FatalFormat(IFormatProvider provider, string format, params object[] args); + + /// + /// Checks if this logger is enabled for the level. + /// + /// + /// true if this logger is enabled for events, false otherwise. + /// + /// + /// + /// This function is intended to lessen the computational cost of + /// disabled log debug statements. + /// + /// For some ILog interface log, when you write: + /// + /// log.Debug("This is entry number: " + i ); + /// + /// + /// You incur the cost constructing the message, string construction and concatenation in + /// this case, regardless of whether the message is logged or not. + /// + /// + /// If you are worried about speed (who isn't), then you should write: + /// + /// + /// if (log.IsDebugEnabled) + /// { + /// log.Debug("This is entry number: " + i ); + /// } + /// + /// + /// This way you will not incur the cost of parameter + /// construction if debugging is disabled for log. On + /// the other hand, if the log is debug enabled, you + /// will incur the cost of evaluating whether the logger is debug + /// enabled twice. Once in and once in + /// the . This is an insignificant overhead + /// since evaluating a logger takes about 1% of the time it + /// takes to actually log. This is the preferred style of logging. + /// + /// Alternatively if your logger is available statically then the is debug + /// enabled state can be stored in a static variable like this: + /// + /// + /// private static readonly bool isDebugEnabled = log.IsDebugEnabled; + /// + /// + /// Then when you come to log you can write: + /// + /// + /// if (isDebugEnabled) + /// { + /// log.Debug("This is entry number: " + i ); + /// } + /// + /// + /// This way the debug enabled state is only queried once + /// when the class is loaded. Using a private static readonly + /// variable is the most efficient because it is a run time constant + /// and can be heavily optimized by the JIT compiler. + /// + /// + /// Of course if you use a static readonly variable to + /// hold the enabled state of the logger then you cannot + /// change the enabled state at runtime to vary the logging + /// that is produced. You have to decide if you need absolute + /// speed or runtime flexibility. + /// + /// + /// + /// + bool IsDebugEnabled { get; } + + /// + /// Checks if this logger is enabled for the level. + /// + /// + /// true if this logger is enabled for events, false otherwise. + /// + /// + /// For more information see . + /// + /// + /// + /// + bool IsInfoEnabled { get; } + + /// + /// Checks if this logger is enabled for the level. + /// + /// + /// true if this logger is enabled for events, false otherwise. + /// + /// + /// For more information see . + /// + /// + /// + /// + bool IsWarnEnabled { get; } + + /// + /// Checks if this logger is enabled for the level. + /// + /// + /// true if this logger is enabled for events, false otherwise. + /// + /// + /// For more information see . + /// + /// + /// + /// + bool IsErrorEnabled { get; } + + /// + /// Checks if this logger is enabled for the level. + /// + /// + /// true if this logger is enabled for events, false otherwise. + /// + /// + /// For more information see . + /// + /// + /// + /// + bool IsFatalEnabled { get; } + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/DynamicPatternLayout.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/DynamicPatternLayout.cs index 62cc3a05982..68f280b8ab8 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/DynamicPatternLayout.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/DynamicPatternLayout.cs @@ -1,141 +1,137 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.Layout -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; - using System.Collections; - using System.IO; +using System; +using System.Collections; +using System.IO; - using log4net.Core; - using log4net.Layout.Pattern; - using log4net.Util; +using log4net.Core; +using log4net.Layout.Pattern; +using log4net.Util; - /// - /// A flexible layout configurable with pattern string that re-evaluates on each call. - /// - /// - /// This class is built on and provides all the - /// features and capabilities of PatternLayout. PatternLayout is a 'static' class - /// in that its layout is done once at configuration time. This class will recreate - /// the layout on each reference. - /// One important difference between PatternLayout and DynamicPatternLayout is the - /// treatment of the Header and Footer parameters in the configuration. The Header and Footer - /// parameters for DynamicPatternLayout must be syntactically in the form of a PatternString, - /// but should not be marked as type log4net.Util.PatternString. Doing so causes the - /// pattern to be statically converted at configuration time and causes DynamicPatternLayout - /// to perform the same as PatternLayout. - /// Please see for complete documentation. - /// - /// <layout type="log4net.Layout.DynamicPatternLayout"> - /// <param name="Header" value="%newline**** Trace Opened Local: %date{yyyy-MM-dd HH:mm:ss.fff} UTC: %utcdate{yyyy-MM-dd HH:mm:ss.fff} ****%newline" /> - /// <param name="Footer" value="**** Trace Closed %date{yyyy-MM-dd HH:mm:ss.fff} ****%newline" /> - /// </layout> - /// - /// - public class DynamicPatternLayout : PatternLayout +namespace log4net.Layout +{ + /// + /// A flexible layout configurable with pattern string that re-evaluates on each call. + /// + /// + /// This class is built on and provides all the + /// features and capabilities of PatternLayout. PatternLayout is a 'static' class + /// in that its layout is done once at configuration time. This class will recreate + /// the layout on each reference. + /// One important difference between PatternLayout and DynamicPatternLayout is the + /// treatment of the Header and Footer parameters in the configuration. The Header and Footer + /// parameters for DynamicPatternLayout must be syntactically in the form of a PatternString, + /// but should not be marked as type log4net.Util.PatternString. Doing so causes the + /// pattern to be statically converted at configuration time and causes DynamicPatternLayout + /// to perform the same as PatternLayout. + /// Please see for complete documentation. + /// + /// <layout type="log4net.Layout.DynamicPatternLayout"> + /// <param name="Header" value="%newline**** Trace Opened Local: %date{yyyy-MM-dd HH:mm:ss.fff} UTC: %utcdate{yyyy-MM-dd HH:mm:ss.fff} ****%newline" /> + /// <param name="Footer" value="**** Trace Closed %date{yyyy-MM-dd HH:mm:ss.fff} ****%newline" /> + /// </layout> + /// + /// + public class DynamicPatternLayout: PatternLayout { - /// - /// The header PatternString. - /// - private PatternString m_headerPatternString = new PatternString(string.Empty); - - /// - /// The footer PatternString. - /// - private PatternString m_footerPatternString = new PatternString(string.Empty); + /// + /// The header PatternString + /// + private PatternString m_headerPatternString = new PatternString(string.Empty); /// - /// Initializes a new instance of the class. - /// Constructs a DynamicPatternLayout using the DefaultConversionPattern. - /// - /// - /// - /// The default pattern just produces the application supplied message. - /// - /// - public DynamicPatternLayout() - : base() - { - } + /// The footer PatternString + /// + private PatternString m_footerPatternString = new PatternString(string.Empty); /// - /// Initializes a new instance of the class. - /// Constructs a DynamicPatternLayout using the supplied conversion pattern. - /// - /// the pattern to use. - /// - /// - public DynamicPatternLayout(string pattern) - : base(pattern) - { + /// Constructs a DynamicPatternLayout using the DefaultConversionPattern + /// + /// + /// + /// The default pattern just produces the application supplied message. + /// + /// + public DynamicPatternLayout() + : base() + { } - /// - /// Gets or sets the header for the layout format. - /// - /// the layout header. - /// - /// - /// The Header text will be appended before any logging events - /// are formatted and appended. - /// - /// The pattern will be formatted on each get operation. - /// - public override string Header - { - get - { - return this.m_headerPatternString.Format(); - } + /// + /// Constructs a DynamicPatternLayout using the supplied conversion pattern + /// + /// the pattern to use + /// + /// + public DynamicPatternLayout (string pattern) + : base(pattern) + { + } - set - { - base.Header = value; - this.m_headerPatternString = new PatternString(value); - } - } /* property DynamicPatternLayout Header */ - - /// - /// Gets or sets the footer for the layout format. - /// - /// the layout footer. - /// - /// - /// The Footer text will be appended after all the logging events - /// have been formatted and appended. - /// - /// The pattern will be formatted on each get operation. - /// - public override string Footer - { - get - { - return this.m_footerPatternString.Format(); - } + /// + /// The header for the layout format. + /// + /// the layout header + /// + /// + /// The Header text will be appended before any logging events + /// are formatted and appended. + /// + /// The pattern will be formatted on each get operation. + /// + public override string Header + { + get + { + return this.m_headerPatternString.Format(); + } + set + { + base.Header = value; + this.m_headerPatternString = new PatternString(value); + } + } /* property DynamicPatternLayout Header */ - set - { - base.Footer = value; - this.m_footerPatternString = new PatternString(value); - } - } /* property DynamicPatternLayout Footer */ - } /* class DynamicPatternLayout */ -} /* namespace log4net.Layout */ + /// + /// The footer for the layout format. + /// + /// the layout footer + /// + /// + /// The Footer text will be appended after all the logging events + /// have been formatted and appended. + /// + /// The pattern will be formatted on each get operation. + /// + public override string Footer + { + get + { + return this.m_footerPatternString.Format(); + } + set + { + base.Footer = value; + this.m_footerPatternString = new PatternString(value); + } + } /* property DynamicPatternLayout Footer */ + } /* class DynamicPatternLayout */ +} /* namespace log4net.Layout */ diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/ExceptionLayout.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/ExceptionLayout.cs index b2fcf0d61d4..340cf68613d 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/ExceptionLayout.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/ExceptionLayout.cs @@ -1,98 +1,97 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.Layout -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; - using System.IO; - using System.Text; +using System; +using System.IO; +using System.Text; - using log4net.Core; - using log4net.Util; +using log4net.Util; +using log4net.Core; - /// - /// A Layout that renders only the Exception text from the logging event. - /// - /// - /// - /// A Layout that renders only the Exception text from the logging event. - /// - /// - /// This Layout should only be used with appenders that utilize multiple - /// layouts (e.g. ). - /// - /// - /// Nicko Cadell. - /// Gert Driesen. - public class ExceptionLayout : LayoutSkeleton +namespace log4net.Layout +{ + /// + /// A Layout that renders only the Exception text from the logging event + /// + /// + /// + /// A Layout that renders only the Exception text from the logging event. + /// + /// + /// This Layout should only be used with appenders that utilize multiple + /// layouts (e.g. ). + /// + /// + /// Nicko Cadell + /// Gert Driesen + public class ExceptionLayout : LayoutSkeleton { /// - /// Initializes a new instance of the class. - /// Default constructor. - /// - /// - /// - /// Constructs a ExceptionLayout. - /// - /// - public ExceptionLayout() - { - this.IgnoresException = false; + /// Default constructor + /// + /// + /// + /// Constructs a ExceptionLayout + /// + /// + public ExceptionLayout() + { + this.IgnoresException = false; } - /// - /// Activate component options. - /// - /// - /// - /// Part of the component activation - /// framework. - /// - /// - /// This method does nothing as options become effective immediately. - /// - /// - public override void ActivateOptions() - { - // nothing to do. + /// + /// Activate component options + /// + /// + /// + /// Part of the component activation + /// framework. + /// + /// + /// This method does nothing as options become effective immediately. + /// + /// + public override void ActivateOptions() + { + // nothing to do. } - /// - /// Gets the exception text from the logging event. - /// - /// The TextWriter to write the formatted event to. - /// the event being logged. - /// - /// - /// Write the exception string to the . - /// The exception string is retrieved from . - /// - /// - public override void Format(TextWriter writer, LoggingEvent loggingEvent) - { - if (loggingEvent == null) - { - throw new ArgumentNullException("loggingEvent"); - } - - writer.Write(loggingEvent.GetExceptionString()); + /// + /// Gets the exception text from the logging event + /// + /// The TextWriter to write the formatted event to + /// the event being logged + /// + /// + /// Write the exception string to the . + /// The exception string is retrieved from . + /// + /// + public override void Format(TextWriter writer, LoggingEvent loggingEvent) + { + if (loggingEvent == null) + { + throw new ArgumentNullException("loggingEvent"); + } + + writer.Write(loggingEvent.GetExceptionString()); } - } -} + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/ILayout.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/ILayout.cs index 7e0a8af4bdb..f800b0fd234 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/ILayout.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/ILayout.cs @@ -1,122 +1,122 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.Layout -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; - using System.IO; +using System; +using System.IO; - using log4net; - using log4net.Core; +using log4net; +using log4net.Core; - /// - /// Interface implemented by layout objects. - /// - /// - /// - /// An object is used to format a - /// as text. The method is called by an - /// appender to transform the into a string. - /// - /// - /// The layout can also supply and - /// text that is appender before any events and after all the events respectively. - /// - /// - /// Nicko Cadell. - /// Gert Driesen. - public interface ILayout - { - /// - /// Implement this method to create your own layout format. - /// - /// The TextWriter to write the formatted event to. - /// The event to format. - /// - /// - /// This method is called by an appender to format - /// the as text and output to a writer. - /// - /// - /// If the caller does not have a and prefers the - /// event to be formatted as a then the following - /// code can be used to format the event into a . - /// - /// - /// StringWriter writer = new StringWriter(); - /// Layout.Format(writer, loggingEvent); - /// string formattedEvent = writer.ToString(); - /// - /// - void Format(TextWriter writer, LoggingEvent loggingEvent); - - /// - /// Gets the content type output by this layout. - /// - /// The content type. - /// - /// - /// The content type output by this layout. - /// - /// - /// This is a MIME type e.g. "text/plain". - /// - /// - string ContentType { get; } - - /// - /// Gets the header for the layout format. - /// - /// the layout header. - /// - /// - /// The Header text will be appended before any logging events - /// are formatted and appended. - /// - /// - string Header { get; } - - /// - /// Gets the footer for the layout format. - /// - /// the layout footer. - /// - /// - /// The Footer text will be appended after all the logging events - /// have been formatted and appended. - /// - /// - string Footer { get; } - - /// - /// Gets a value indicating whether flag indicating if this layout handle exceptions. - /// - /// false if this layout handles exceptions. - /// - /// - /// If this layout handles the exception object contained within - /// , then the layout should return - /// false. Otherwise, if the layout ignores the exception - /// object, then the layout should return true. - /// - /// - bool IgnoresException { get; } - } -} +namespace log4net.Layout +{ + /// + /// Interface implemented by layout objects + /// + /// + /// + /// An object is used to format a + /// as text. The method is called by an + /// appender to transform the into a string. + /// + /// + /// The layout can also supply and + /// text that is appender before any events and after all the events respectively. + /// + /// + /// Nicko Cadell + /// Gert Driesen + public interface ILayout + { + /// + /// Implement this method to create your own layout format. + /// + /// The TextWriter to write the formatted event to + /// The event to format + /// + /// + /// This method is called by an appender to format + /// the as text and output to a writer. + /// + /// + /// If the caller does not have a and prefers the + /// event to be formatted as a then the following + /// code can be used to format the event into a . + /// + /// + /// StringWriter writer = new StringWriter(); + /// Layout.Format(writer, loggingEvent); + /// string formattedEvent = writer.ToString(); + /// + /// + void Format(TextWriter writer, LoggingEvent loggingEvent); + + /// + /// The content type output by this layout. + /// + /// The content type + /// + /// + /// The content type output by this layout. + /// + /// + /// This is a MIME type e.g. "text/plain". + /// + /// + string ContentType { get; } + + /// + /// The header for the layout format. + /// + /// the layout header + /// + /// + /// The Header text will be appended before any logging events + /// are formatted and appended. + /// + /// + string Header { get; } + + /// + /// The footer for the layout format. + /// + /// the layout footer + /// + /// + /// The Footer text will be appended after all the logging events + /// have been formatted and appended. + /// + /// + string Footer { get; } + + /// + /// Flag indicating if this layout handle exceptions + /// + /// false if this layout handles exceptions + /// + /// + /// If this layout handles the exception object contained within + /// , then the layout should return + /// false. Otherwise, if the layout ignores the exception + /// object, then the layout should return true. + /// + /// + bool IgnoresException { get; } + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/IRawLayout.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/IRawLayout.cs index 6108b51b31f..b0f874adc49 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/IRawLayout.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/IRawLayout.cs @@ -1,62 +1,62 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.Layout -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; +using System; - using log4net; - using log4net.Core; - using log4net.Util.TypeConverters; +using log4net; +using log4net.Core; +using log4net.Util.TypeConverters; - /// - /// Interface for raw layout objects. - /// - /// - /// - /// Interface used to format a - /// to an object. - /// - /// - /// This interface should not be confused with the - /// interface. This interface is used in - /// only certain specialized situations where a raw object is - /// required rather than a formatted string. The - /// is not generally useful than this interface. - /// - /// - /// Nicko Cadell. - /// Gert Driesen. - [TypeConverter(typeof(RawLayoutConverter))] - public interface IRawLayout - { - /// - /// Implement this method to create your own layout format. - /// - /// The event to format. - /// returns the formatted event. - /// - /// - /// Implement this method to create your own layout format. - /// - /// - object Format(LoggingEvent loggingEvent); - } -} +namespace log4net.Layout +{ + /// + /// Interface for raw layout objects + /// + /// + /// + /// Interface used to format a + /// to an object. + /// + /// + /// This interface should not be confused with the + /// interface. This interface is used in + /// only certain specialized situations where a raw object is + /// required rather than a formatted string. The + /// is not generally useful than this interface. + /// + /// + /// Nicko Cadell + /// Gert Driesen + [TypeConverter(typeof(RawLayoutConverter))] + public interface IRawLayout + { + /// + /// Implement this method to create your own layout format. + /// + /// The event to format + /// returns the formatted event + /// + /// + /// Implement this method to create your own layout format. + /// + /// + object Format(LoggingEvent loggingEvent); + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Layout2RawLayoutAdapter.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Layout2RawLayoutAdapter.cs index 4cd73055f51..7b827eed302 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Layout2RawLayoutAdapter.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Layout2RawLayoutAdapter.cs @@ -1,83 +1,84 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.Layout -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; - using System.IO; +using System; +using System.IO; - using log4net; - using log4net.Core; +using log4net; +using log4net.Core; - /// - /// Adapts any to a . - /// - /// - /// - /// Where an is required this adapter - /// allows a to be specified. - /// - /// - /// Nicko Cadell. - /// Gert Driesen. - public class Layout2RawLayoutAdapter : IRawLayout +namespace log4net.Layout +{ + /// + /// Adapts any to a + /// + /// + /// + /// Where an is required this adapter + /// allows a to be specified. + /// + /// + /// Nicko Cadell + /// Gert Driesen + public class Layout2RawLayoutAdapter : IRawLayout { - /// - /// The layout to adapt. - /// + /// + /// The layout to adapt + /// private ILayout m_layout; /// - /// Initializes a new instance of the class. - /// Construct a new adapter. - /// - /// the layout to adapt. - /// - /// - /// Create the adapter for the specified . - /// - /// - public Layout2RawLayoutAdapter(ILayout layout) - { - this.m_layout = layout; + /// Construct a new adapter + /// + /// the layout to adapt + /// + /// + /// Create the adapter for the specified . + /// + /// + public Layout2RawLayoutAdapter(ILayout layout) + { + this.m_layout = layout; } - /// - /// Format the logging event as an object. - /// - /// The event to format. - /// returns the formatted event. - /// - /// - /// Format the logging event as an object. - /// - /// - /// Uses the object supplied to - /// the constructor to perform the formatting. - /// - /// - public virtual object Format(LoggingEvent loggingEvent) - { - StringWriter writer = new StringWriter(System.Globalization.CultureInfo.InvariantCulture); - this.m_layout.Format(writer, loggingEvent); - return writer.ToString(); + /// + /// Format the logging event as an object. + /// + /// The event to format + /// returns the formatted event + /// + /// + /// Format the logging event as an object. + /// + /// + /// Uses the object supplied to + /// the constructor to perform the formatting. + /// + /// + public virtual object Format(LoggingEvent loggingEvent) + { + using (var writer = new StringWriter(System.Globalization.CultureInfo.InvariantCulture)) + { + this.m_layout.Format(writer, loggingEvent); + return writer.ToString(); + } } - } -} + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/LayoutSkeleton.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/LayoutSkeleton.cs index 0760b6e3567..b8cf17af6ad 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/LayoutSkeleton.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/LayoutSkeleton.cs @@ -1,219 +1,219 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.Layout -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; - using System.IO; +using System; +using System.IO; - using log4net; - using log4net.Core; +using log4net; +using log4net.Core; - /// - /// Extend this abstract class to create your own log layout format. - /// - /// - /// - /// This is the base implementation of the - /// interface. Most layout objects should extend this class. - /// - /// - /// - /// - /// - /// Subclasses must implement the - /// method. - /// - /// - /// Subclasses should set the in their default - /// constructor. - /// - /// - /// - /// Nicko Cadell. - /// Gert Driesen. - public abstract class LayoutSkeleton : ILayout, IOptionHandler +namespace log4net.Layout +{ + /// + /// Extend this abstract class to create your own log layout format. + /// + /// + /// + /// This is the base implementation of the + /// interface. Most layout objects should extend this class. + /// + /// + /// + /// + /// + /// Subclasses must implement the + /// method. + /// + /// + /// Subclasses should set the in their default + /// constructor. + /// + /// + /// + /// Nicko Cadell + /// Gert Driesen + public abstract class LayoutSkeleton : ILayout, IOptionHandler { - /// - /// The header text. - /// - /// - /// - /// See for more information. - /// - /// - private string m_header = null; - - /// - /// The footer text. - /// - /// - /// - /// See for more information. - /// - /// - private string m_footer = null; - - /// - /// Flag indicating if this layout handles exceptions. - /// - /// - /// - /// false if this layout handles exceptions. - /// - /// + /// + /// The header text + /// + /// + /// + /// See for more information. + /// + /// + private string m_header = null; + + /// + /// The footer text + /// + /// + /// + /// See for more information. + /// + /// + private string m_footer = null; + + /// + /// Flag indicating if this layout handles exceptions + /// + /// + /// + /// false if this layout handles exceptions + /// + /// private bool m_ignoresException = true; /// - /// Initializes a new instance of the class. - /// Empty default constructor. - /// - /// - /// - /// Empty default constructor. - /// - /// - protected LayoutSkeleton() - { + /// Empty default constructor + /// + /// + /// + /// Empty default constructor + /// + /// + protected LayoutSkeleton() + { } - /// - /// Activate component options. - /// - /// - /// - /// This is part of the delayed object - /// activation scheme. The method must - /// be called on this object after the configuration properties have - /// been set. Until is called this - /// object is in an undefined state and must not be used. - /// - /// - /// If any of the configuration properties are modified then - /// must be called again. - /// - /// - /// This method must be implemented by the subclass. - /// - /// + /// + /// Activate component options + /// + /// + /// + /// This is part of the delayed object + /// activation scheme. The method must + /// be called on this object after the configuration properties have + /// been set. Until is called this + /// object is in an undefined state and must not be used. + /// + /// + /// If any of the configuration properties are modified then + /// must be called again. + /// + /// + /// This method must be implemented by the subclass. + /// + /// public abstract void ActivateOptions(); - /// - /// Implement this method to create your own layout format. - /// - /// The TextWriter to write the formatted event to. - /// The event to format. - /// - /// - /// This method is called by an appender to format - /// the as text. - /// - /// - public abstract void Format(TextWriter writer, LoggingEvent loggingEvent); - - /// - /// Convenience method for easily formatting the logging event into a string variable. - /// - /// - /// - /// Creates a new StringWriter instance to store the formatted logging event. + /// + /// Implement this method to create your own layout format. + /// + /// The TextWriter to write the formatted event to + /// The event to format + /// + /// + /// This method is called by an appender to format + /// the as text. + /// + /// + public abstract void Format(TextWriter writer, LoggingEvent loggingEvent); + + /// + /// Convenience method for easily formatting the logging event into a string variable. + /// + /// + /// + /// Creates a new StringWriter instance to store the formatted logging event. + /// + public string Format(LoggingEvent loggingEvent) + { + using (var writer = new StringWriter(System.Globalization.CultureInfo.InvariantCulture)) + { + this.Format(writer, loggingEvent); + return writer.ToString(); + } + } + + /// + /// The content type output by this layout. + /// + /// The content type is "text/plain" + /// + /// + /// The content type output by this layout. + /// + /// + /// This base class uses the value "text/plain". + /// To change this value a subclass must override this + /// property. + /// + /// + public virtual string ContentType + { + get { return "text/plain"; } + } + + /// + /// The header for the layout format. + /// + /// the layout header + /// + /// + /// The Header text will be appended before any logging events + /// are formatted and appended. + /// + /// + public virtual string Header + { + get { return this.m_header; } + set { this.m_header = value; } + } + + /// + /// The footer for the layout format. + /// + /// the layout footer + /// + /// + /// The Footer text will be appended after all the logging events + /// have been formatted and appended. + /// + /// + public virtual string Footer + { + get { return this.m_footer; } + set { this.m_footer = value; } + } + + /// + /// Flag indicating if this layout handles exceptions + /// + /// false if this layout handles exceptions + /// + /// + /// If this layout handles the exception object contained within + /// , then the layout should return + /// false. Otherwise, if the layout ignores the exception + /// object, then the layout should return true. + /// + /// + /// Set this value to override a this default setting. The default + /// value is true, this layout does not handle the exception. + /// /// - /// - public string Format(LoggingEvent loggingEvent) - { - StringWriter writer = new StringWriter(System.Globalization.CultureInfo.InvariantCulture); - this.Format(writer, loggingEvent); - return writer.ToString(); - } - - /// - /// Gets the content type output by this layout. - /// - /// The content type is "text/plain". - /// - /// - /// The content type output by this layout. - /// - /// - /// This base class uses the value "text/plain". - /// To change this value a subclass must override this - /// property. - /// - /// - public virtual string ContentType - { - get { return "text/plain"; } - } - - /// - /// Gets or sets the header for the layout format. - /// - /// the layout header. - /// - /// - /// The Header text will be appended before any logging events - /// are formatted and appended. - /// - /// - public virtual string Header - { - get { return this.m_header; } - set { this.m_header = value; } - } - - /// - /// Gets or sets the footer for the layout format. - /// - /// the layout footer. - /// - /// - /// The Footer text will be appended after all the logging events - /// have been formatted and appended. - /// - /// - public virtual string Footer - { - get { return this.m_footer; } - set { this.m_footer = value; } - } - - /// - /// Gets or sets a value indicating whether flag indicating if this layout handles exceptions. - /// - /// false if this layout handles exceptions. - /// - /// - /// If this layout handles the exception object contained within - /// , then the layout should return - /// false. Otherwise, if the layout ignores the exception - /// object, then the layout should return true. - /// - /// - /// Set this value to override a this default setting. The default - /// value is true, this layout does not handle the exception. - /// - /// - public virtual bool IgnoresException - { - get { return this.m_ignoresException; } - set { this.m_ignoresException = value; } + public virtual bool IgnoresException + { + get { return this.m_ignoresException; } + set { this.m_ignoresException = value; } } - } -} + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/AppDomainPatternConverter.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/AppDomainPatternConverter.cs index 409e8404b41..c66f3399730 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/AppDomainPatternConverter.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/AppDomainPatternConverter.cs @@ -1,56 +1,56 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.Layout.Pattern -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; - using System.IO; - using System.Text; +using System; +using System.Text; +using System.IO; - using log4net.Core; +using log4net.Core; - /// - /// Write the event appdomain name to the output. - /// - /// - /// - /// Writes the to the output writer. - /// - /// - /// Daniel Cazzulino. - /// Nicko Cadell. - internal sealed class AppDomainPatternConverter : PatternLayoutConverter - { - /// - /// Write the event appdomain name to the output. - /// - /// that will receive the formatted result. - /// the event being logged. - /// - /// - /// Writes the to the output . - /// - /// - protected override void Convert(TextWriter writer, LoggingEvent loggingEvent) - { - writer.Write(loggingEvent.Domain); - } - } -} +namespace log4net.Layout.Pattern +{ + /// + /// Write the event appdomain name to the output + /// + /// + /// + /// Writes the to the output writer. + /// + /// + /// Daniel Cazzulino + /// Nicko Cadell + internal sealed class AppDomainPatternConverter : PatternLayoutConverter + { + /// + /// Write the event appdomain name to the output + /// + /// that will receive the formatted result. + /// the event being logged + /// + /// + /// Writes the to the output . + /// + /// + protected override void Convert(TextWriter writer, LoggingEvent loggingEvent) + { + writer.Write(loggingEvent.Domain); + } + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/AspNetCachePatternConverter.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/AspNetCachePatternConverter.cs index 9db599177e1..a0f5652b623 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/AspNetCachePatternConverter.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/AspNetCachePatternConverter.cs @@ -1,80 +1,80 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -// .NET Compact Framework 1.0 has no support for ASP.NET -// SSCLI 1.0 has no support for ASP.NET -#if !NETCF && !SSCLI && !CLIENT_PROFILE - -using System.IO; -using System.Web; +#if NET_2_0 +// .NET Compact Framework 1.0 has no support for ASP.NET +// SSCLI 1.0 has no support for ASP.NET +#if !NETCF && !SSCLI && !CLIENT_PROFILE -using log4net.Core; -using log4net.Util; - -namespace log4net.Layout.Pattern -{ - /// - /// Converter for items in the ASP.Net Cache. - /// - /// - /// - /// Outputs an item from the . - /// - /// - /// Ron Grabowski. - internal sealed class AspNetCachePatternConverter : AspNetPatternLayoutConverter - { - /// - /// Write the ASP.Net Cache item to the output. - /// - /// that will receive the formatted result. - /// The on which the pattern converter should be executed. - /// The under which the ASP.Net request is running. - /// - /// - /// Writes out the value of a named property. The property name - /// should be set in the - /// property. If no property has been set, all key value pairs from the Cache will - /// be written to the output. - /// - /// - protected override void Convert(TextWriter writer, LoggingEvent loggingEvent, HttpContext httpContext) - { - if (HttpRuntime.Cache != null) - { - if (this.Option != null) - { - WriteObject(writer, loggingEvent.Repository, HttpRuntime.Cache[this.Option]); - } - else - { - WriteObject(writer, loggingEvent.Repository, HttpRuntime.Cache.GetEnumerator()); - } - } - else - { - writer.Write(SystemInfo.NotAvailableText); - } - } - } -} - -#endif +using System.IO; +using System.Web; +using log4net.Core; +using log4net.Util; + +namespace log4net.Layout.Pattern +{ + /// + /// Converter for items in the ASP.Net Cache. + /// + /// + /// + /// Outputs an item from the . + /// + /// + /// Ron Grabowski + internal sealed class AspNetCachePatternConverter : AspNetPatternLayoutConverter + { + /// + /// Write the ASP.Net Cache item to the output + /// + /// that will receive the formatted result. + /// The on which the pattern converter should be executed. + /// The under which the ASP.Net request is running. + /// + /// + /// Writes out the value of a named property. The property name + /// should be set in the + /// property. If no property has been set, all key value pairs from the Cache will + /// be written to the output. + /// + /// + protected override void Convert(TextWriter writer, LoggingEvent loggingEvent, HttpContext httpContext) + { + if (HttpRuntime.Cache != null) + { + if (this.Option != null) + { + WriteObject(writer, loggingEvent.Repository, HttpRuntime.Cache[this.Option]); + } + else + { + WriteObject(writer, loggingEvent.Repository, HttpRuntime.Cache.GetEnumerator()); + } + } + else + { + writer.Write(SystemInfo.NotAvailableText); + } + } + } +} + +#endif // !NETCF && !SSCLI && !CLIENT_PROFILE +#endif // NET_2_0 diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/AspNetContextPatternConverter.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/AspNetContextPatternConverter.cs index dcfc9761bdb..7bb743bc6d6 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/AspNetContextPatternConverter.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/AspNetContextPatternConverter.cs @@ -1,71 +1,71 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -// .NET Compact Framework 1.0 has no support for ASP.NET -// SSCLI 1.0 has no support for ASP.NET -#if !NETCF && !SSCLI && !CLIENT_PROFILE - -using System.IO; -using System.Web; +#if NET_2_0 +// .NET Compact Framework 1.0 has no support for ASP.NET +// SSCLI 1.0 has no support for ASP.NET +#if !NETCF && !SSCLI && !CLIENT_PROFILE -using log4net.Core; - -namespace log4net.Layout.Pattern -{ - /// - /// Converter for items in the . - /// - /// - /// - /// Outputs an item from the . - /// - /// - /// Ron Grabowski. - internal sealed class AspNetContextPatternConverter : AspNetPatternLayoutConverter - { - /// - /// Write the ASP.Net HttpContext item to the output. - /// - /// that will receive the formatted result. - /// The on which the pattern converter should be executed. - /// The under which the ASP.Net request is running. - /// - /// - /// Writes out the value of a named property. The property name - /// should be set in the - /// property. - /// - /// - protected override void Convert(TextWriter writer, LoggingEvent loggingEvent, HttpContext httpContext) - { - if (this.Option != null) - { - WriteObject(writer, loggingEvent.Repository, httpContext.Items[this.Option]); - } - else - { - WriteObject(writer, loggingEvent.Repository, httpContext.Items); - } - } - } -} - -#endif +using System.IO; +using System.Web; +using log4net.Core; + +namespace log4net.Layout.Pattern +{ + /// + /// Converter for items in the . + /// + /// + /// + /// Outputs an item from the . + /// + /// + /// Ron Grabowski + internal sealed class AspNetContextPatternConverter : AspNetPatternLayoutConverter + { + /// + /// Write the ASP.Net HttpContext item to the output + /// + /// that will receive the formatted result. + /// The on which the pattern converter should be executed. + /// The under which the ASP.Net request is running. + /// + /// + /// Writes out the value of a named property. The property name + /// should be set in the + /// property. + /// + /// + protected override void Convert(TextWriter writer, LoggingEvent loggingEvent, HttpContext httpContext) + { + if (this.Option != null) + { + WriteObject(writer, loggingEvent.Repository, httpContext.Items[this.Option]); + } + else + { + WriteObject(writer, loggingEvent.Repository, httpContext.Items); + } + } + } +} + +#endif // !NETCF && !SSCLI && !CLIENT_PROFILE +#endif // NET_2_0 diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/AspNetPatternConverter.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/AspNetPatternConverter.cs index c25bf8a0c10..0651139a233 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/AspNetPatternConverter.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/AspNetPatternConverter.cs @@ -1,68 +1,85 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -// .NET Compact Framework 1.0 has no support for ASP.NET -// SSCLI 1.0 has no support for ASP.NET -#if !NETCF && !SSCLI && !CLIENT_PROFILE - -using System.IO; -using System.Web; +#if NET_2_0 +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -using log4net.Core; -using log4net.Util; - -namespace log4net.Layout.Pattern -{ - /// - /// Abstract class that provides access to the current HttpContext () that - /// derived classes need. - /// - /// - /// This class handles the case when HttpContext.Current is null by writing - /// to the writer. - /// - /// Ron Grabowski. - internal abstract class AspNetPatternLayoutConverter : PatternLayoutConverter - { - protected override void Convert(TextWriter writer, LoggingEvent loggingEvent) - { - if (HttpContext.Current == null) - { - writer.Write(SystemInfo.NotAvailableText); - } - else - { - this.Convert(writer, loggingEvent, HttpContext.Current); - } - } - - /// - /// Derived pattern converters must override this method in order to - /// convert conversion specifiers in the correct way. - /// - /// that will receive the formatted result. - /// The on which the pattern converter should be executed. - /// The under which the ASP.Net request is running. - protected abstract void Convert(TextWriter writer, LoggingEvent loggingEvent, HttpContext httpContext); - } -} - -#endif +// .NET Compact Framework 1.0 has no support for ASP.NET +// SSCLI 1.0 has no support for ASP.NET +#if !NETCF && !SSCLI && !CLIENT_PROFILE + +using System.IO; +using System.Web; +using log4net.Core; +using log4net.Util; + +namespace log4net.Layout.Pattern +{ + /// + /// Abstract class that provides access to the current HttpContext () that + /// derived classes need. + /// + /// + /// This class handles the case when HttpContext.Current is null by writing + /// to the writer. + /// + /// Ron Grabowski + internal abstract class AspNetPatternLayoutConverter : PatternLayoutConverter + { + protected override void Convert(TextWriter writer, LoggingEvent loggingEvent) + { + if (HttpContext.Current == null) + { + writer.Write(SystemInfo.NotAvailableText); + } + else + { + this.Convert(writer, loggingEvent, HttpContext.Current); + } + } + + /// + /// Derived pattern converters must override this method in order to + /// convert conversion specifiers in the correct way. + /// + /// that will receive the formatted result. + /// The on which the pattern converter should be executed. + /// The under which the ASP.Net request is running. + protected abstract void Convert(TextWriter writer, LoggingEvent loggingEvent, HttpContext httpContext); + } +} + +#endif // !NETCF && !SSCLI && !CLIENT_PROFILE +#endif // NET_2_0 diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/AspNetRequestPatternConverter.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/AspNetRequestPatternConverter.cs index 47e9e445d1b..858d50080ec 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/AspNetRequestPatternConverter.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/AspNetRequestPatternConverter.cs @@ -1,92 +1,92 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -// .NET Compact Framework 1.0 has no support for ASP.NET -// SSCLI 1.0 has no support for ASP.NET -#if !NETCF && !SSCLI && !CLIENT_PROFILE - -using System.IO; -using System.Web; +#if NET_2_0 +// .NET Compact Framework 1.0 has no support for ASP.NET +// SSCLI 1.0 has no support for ASP.NET +#if !NETCF && !SSCLI && !CLIENT_PROFILE -using log4net.Core; -using log4net.Util; - -namespace log4net.Layout.Pattern -{ - /// - /// Converter for items in the ASP.Net Cache. - /// - /// - /// - /// Outputs an item from the . - /// - /// - /// Ron Grabowski. - internal sealed class AspNetRequestPatternConverter : AspNetPatternLayoutConverter - { - /// - /// Write the ASP.Net Cache item to the output. - /// - /// that will receive the formatted result. - /// The on which the pattern converter should be executed. - /// The under which the ASP.Net request is running. - /// - /// - /// Writes out the value of a named property. The property name - /// should be set in the - /// property. - /// - /// - protected override void Convert(TextWriter writer, LoggingEvent loggingEvent, HttpContext httpContext) - { - HttpRequest request = null; - try +using System.IO; +using System.Web; +using log4net.Core; +using log4net.Util; + +namespace log4net.Layout.Pattern +{ + /// + /// Converter for items in the ASP.Net Cache. + /// + /// + /// + /// Outputs an item from the . + /// + /// + /// Ron Grabowski + internal sealed class AspNetRequestPatternConverter : AspNetPatternLayoutConverter + { + /// + /// Write the ASP.Net Cache item to the output + /// + /// that will receive the formatted result. + /// The on which the pattern converter should be executed. + /// The under which the ASP.Net request is running. + /// + /// + /// Writes out the value of a named property. The property name + /// should be set in the + /// property. + /// + /// + protected override void Convert(TextWriter writer, LoggingEvent loggingEvent, HttpContext httpContext) + { + HttpRequest request = null; + try { - request = httpContext.Request; - } + request = httpContext.Request; + } catch (HttpException) { - // likely a case of running in IIS integrated mode - // when inside an Application_Start event. - // treat it like a case of the Request - // property returning null - } - - if (request != null) - { - if (this.Option != null) - { - WriteObject(writer, loggingEvent.Repository, httpContext.Request.Params[this.Option]); - } - else - { - WriteObject(writer, loggingEvent.Repository, httpContext.Request.Params); - } - } - else - { - writer.Write(SystemInfo.NotAvailableText); - } - } - } -} - -#endif + // likely a case of running in IIS integrated mode + // when inside an Application_Start event. + // treat it like a case of the Request + // property returning null + } + + if (request != null) + { + if (this.Option != null) + { + WriteObject(writer, loggingEvent.Repository, httpContext.Request.Params[this.Option]); + } + else + { + WriteObject(writer, loggingEvent.Repository, httpContext.Request.Params); + } + } + else + { + writer.Write(SystemInfo.NotAvailableText); + } + } + } +} + +#endif // !NETCF && !SSCLI && !CLIENT_PROFILE +#endif // NET_2_0 diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/AspNetSessionPatternConverter.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/AspNetSessionPatternConverter.cs index fee7e38a709..0e15f04542e 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/AspNetSessionPatternConverter.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/AspNetSessionPatternConverter.cs @@ -1,80 +1,80 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -// .NET Compact Framework 1.0 has no support for ASP.NET -// SSCLI 1.0 has no support for ASP.NET -#if !NETCF && !SSCLI && !CLIENT_PROFILE - -using System.IO; -using System.Web; +#if NET_2_0 +// .NET Compact Framework 1.0 has no support for ASP.NET +// SSCLI 1.0 has no support for ASP.NET +#if !NETCF && !SSCLI && !CLIENT_PROFILE -using log4net.Core; -using log4net.Util; - -namespace log4net.Layout.Pattern -{ - /// - /// Converter for items in the ASP.Net Cache. - /// - /// - /// - /// Outputs an item from the . - /// - /// - /// Ron Grabowski. - internal sealed class AspNetSessionPatternConverter : AspNetPatternLayoutConverter - { - /// - /// Write the ASP.Net Cache item to the output. - /// - /// that will receive the formatted result. - /// The on which the pattern converter should be executed. - /// The under which the ASP.Net request is running. - /// - /// - /// Writes out the value of a named property. The property name - /// should be set in the - /// property. If no property has been set, all key value pairs from the Session will - /// be written to the output. - /// - /// - protected override void Convert(TextWriter writer, LoggingEvent loggingEvent, HttpContext httpContext) - { - if (httpContext.Session != null) - { - if (this.Option != null) - { - WriteObject(writer, loggingEvent.Repository, httpContext.Session.Contents[this.Option]); - } - else - { - WriteObject(writer, loggingEvent.Repository, httpContext.Session); - } - } - else - { - writer.Write(SystemInfo.NotAvailableText); - } - } - } -} - -#endif +using System.IO; +using System.Web; +using log4net.Core; +using log4net.Util; + +namespace log4net.Layout.Pattern +{ + /// + /// Converter for items in the ASP.Net Cache. + /// + /// + /// + /// Outputs an item from the . + /// + /// + /// Ron Grabowski + internal sealed class AspNetSessionPatternConverter : AspNetPatternLayoutConverter + { + /// + /// Write the ASP.Net Cache item to the output + /// + /// that will receive the formatted result. + /// The on which the pattern converter should be executed. + /// The under which the ASP.Net request is running. + /// + /// + /// Writes out the value of a named property. The property name + /// should be set in the + /// property. If no property has been set, all key value pairs from the Session will + /// be written to the output. + /// + /// + protected override void Convert(TextWriter writer, LoggingEvent loggingEvent, HttpContext httpContext) + { + if (httpContext.Session != null) + { + if (this.Option != null) + { + WriteObject(writer, loggingEvent.Repository, httpContext.Session.Contents[this.Option]); + } + else + { + WriteObject(writer, loggingEvent.Repository, httpContext.Session); + } + } + else + { + writer.Write(SystemInfo.NotAvailableText); + } + } + } +} + +#endif // !NETCF && !SSCLI && !CLIENT_PROFILE +#endif // NET_2_0 diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/DatePatternConverter.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/DatePatternConverter.cs index 96de18914cb..3aa2cdd2150 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/DatePatternConverter.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/DatePatternConverter.cs @@ -1,182 +1,182 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.Layout.Pattern -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; - using System.IO; +using System; +using System.IO; - using log4net.Core; - using log4net.DateFormatter; - using log4net.Util; +using log4net.Core; +using log4net.Util; +using log4net.DateFormatter; - /// - /// Date pattern converter, uses a to format - /// the date of a . - /// - /// - /// - /// Render the to the writer as a string. - /// - /// - /// The value of the determines - /// the formatting of the date. The following values are allowed: - /// - /// - /// Option value - /// Output - /// - /// - /// ISO8601 - /// - /// Uses the formatter. - /// Formats using the "yyyy-MM-dd HH:mm:ss,fff" pattern. - /// - /// - /// - /// DATE - /// - /// Uses the formatter. - /// Formats using the "dd MMM yyyy HH:mm:ss,fff" for example, "06 Nov 1994 15:49:37,459". - /// - /// - /// - /// ABSOLUTE - /// - /// Uses the formatter. - /// Formats using the "HH:mm:ss,yyyy" for example, "15:49:37,459". - /// - /// - /// - /// other - /// - /// Any other pattern string uses the formatter. - /// This formatter passes the pattern string to the - /// method. - /// For details on valid patterns see - /// DateTimeFormatInfo Class. - /// - /// - /// - /// - /// - /// The is in the local time zone and is rendered in that zone. - /// To output the time in Universal time see . - /// - /// - /// Nicko Cadell. - internal class DatePatternConverter : PatternLayoutConverter, IOptionHandler - { - /// - /// The used to render the date to a string. - /// - /// - /// - /// The used to render the date to a string. - /// - /// +namespace log4net.Layout.Pattern +{ + /// + /// Date pattern converter, uses a to format + /// the date of a . + /// + /// + /// + /// Render the to the writer as a string. + /// + /// + /// The value of the determines + /// the formatting of the date. The following values are allowed: + /// + /// + /// Option value + /// Output + /// + /// + /// ISO8601 + /// + /// Uses the formatter. + /// Formats using the "yyyy-MM-dd HH:mm:ss,fff" pattern. + /// + /// + /// + /// DATE + /// + /// Uses the formatter. + /// Formats using the "dd MMM yyyy HH:mm:ss,fff" for example, "06 Nov 1994 15:49:37,459". + /// + /// + /// + /// ABSOLUTE + /// + /// Uses the formatter. + /// Formats using the "HH:mm:ss,yyyy" for example, "15:49:37,459". + /// + /// + /// + /// other + /// + /// Any other pattern string uses the formatter. + /// This formatter passes the pattern string to the + /// method. + /// For details on valid patterns see + /// DateTimeFormatInfo Class. + /// + /// + /// + /// + /// + /// The is in the local time zone and is rendered in that zone. + /// To output the time in Universal time see . + /// + /// + /// Nicko Cadell + internal class DatePatternConverter : PatternLayoutConverter, IOptionHandler + { + /// + /// The used to render the date to a string + /// + /// + /// + /// The used to render the date to a string + /// + /// protected IDateFormatter m_dateFormatter; - /// - /// Initialize the converter pattern based on the property. - /// - /// - /// - /// This is part of the delayed object - /// activation scheme. The method must - /// be called on this object after the configuration properties have - /// been set. Until is called this - /// object is in an undefined state and must not be used. - /// - /// - /// If any of the configuration properties are modified then - /// must be called again. - /// - /// - public void ActivateOptions() - { - string dateFormatStr = this.Option; - if (dateFormatStr == null) - { - dateFormatStr = AbsoluteTimeDateFormatter.Iso8601TimeDateFormat; - } - - if (SystemInfo.EqualsIgnoringCase(dateFormatStr, AbsoluteTimeDateFormatter.Iso8601TimeDateFormat)) - { - this.m_dateFormatter = new Iso8601DateFormatter(); - } - else if (SystemInfo.EqualsIgnoringCase(dateFormatStr, AbsoluteTimeDateFormatter.AbsoluteTimeDateFormat)) - { - this.m_dateFormatter = new AbsoluteTimeDateFormatter(); - } - else if (SystemInfo.EqualsIgnoringCase(dateFormatStr, AbsoluteTimeDateFormatter.DateAndTimeDateFormat)) - { - this.m_dateFormatter = new DateTimeDateFormatter(); - } - else - { - try - { - this.m_dateFormatter = new SimpleDateFormatter(dateFormatStr); - } - catch (Exception e) - { - LogLog.Error(declaringType, "Could not instantiate SimpleDateFormatter with [" + dateFormatStr + "]", e); - this.m_dateFormatter = new Iso8601DateFormatter(); - } - } + /// + /// Initialize the converter pattern based on the property. + /// + /// + /// + /// This is part of the delayed object + /// activation scheme. The method must + /// be called on this object after the configuration properties have + /// been set. Until is called this + /// object is in an undefined state and must not be used. + /// + /// + /// If any of the configuration properties are modified then + /// must be called again. + /// + /// + public void ActivateOptions() + { + string dateFormatStr = this.Option; + if (dateFormatStr == null) + { + dateFormatStr = AbsoluteTimeDateFormatter.Iso8601TimeDateFormat; + } + + if (SystemInfo.EqualsIgnoringCase(dateFormatStr, AbsoluteTimeDateFormatter.Iso8601TimeDateFormat)) + { + this.m_dateFormatter = new Iso8601DateFormatter(); + } + else if (SystemInfo.EqualsIgnoringCase(dateFormatStr, AbsoluteTimeDateFormatter.AbsoluteTimeDateFormat)) + { + this.m_dateFormatter = new AbsoluteTimeDateFormatter(); + } + else if (SystemInfo.EqualsIgnoringCase(dateFormatStr, AbsoluteTimeDateFormatter.DateAndTimeDateFormat)) + { + this.m_dateFormatter = new DateTimeDateFormatter(); + } + else + { + try + { + this.m_dateFormatter = new SimpleDateFormatter(dateFormatStr); + } + catch (Exception e) + { + LogLog.Error(declaringType, "Could not instantiate SimpleDateFormatter with [" + dateFormatStr + "]", e); + this.m_dateFormatter = new Iso8601DateFormatter(); + } + } } - /// - /// Convert the pattern into the rendered message. - /// - /// that will receive the formatted result. - /// the event being logged. - /// - /// - /// Pass the to the - /// for it to render it to the writer. - /// - /// - /// The passed is in the local time zone. - /// - /// - protected override void Convert(TextWriter writer, LoggingEvent loggingEvent) - { - try - { - this.m_dateFormatter.FormatDate(loggingEvent.TimeStamp, writer); - } - catch (Exception ex) - { - LogLog.Error(declaringType, "Error occurred while converting date.", ex); - } + /// + /// Convert the pattern into the rendered message + /// + /// that will receive the formatted result. + /// the event being logged + /// + /// + /// Pass the to the + /// for it to render it to the writer. + /// + /// + /// The passed is in the local time zone. + /// + /// + protected override void Convert(TextWriter writer, LoggingEvent loggingEvent) + { + try + { + this.m_dateFormatter.FormatDate(loggingEvent.TimeStamp, writer); + } + catch (Exception ex) + { + LogLog.Error(declaringType, "Error occurred while converting date.", ex); + } } - /// - /// The fully qualified type of the DatePatternConverter class. - /// - /// - /// Used by the internal logger to record the Type of the - /// log message. - /// + /// + /// The fully qualified type of the DatePatternConverter class. + /// + /// + /// Used by the internal logger to record the Type of the + /// log message. + /// private static readonly Type declaringType = typeof(DatePatternConverter); - } -} + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/ExceptionPatternConverter.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/ExceptionPatternConverter.cs index c8b5ea1cbaa..c9f257563c5 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/ExceptionPatternConverter.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/ExceptionPatternConverter.cs @@ -1,140 +1,138 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.Layout.Pattern -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System.Diagnostics; - using System.IO; +using System.Diagnostics; +using System.IO; +using log4net.Core; - using log4net.Core; - - /// - /// Write the exception text to the output. - /// - /// - /// - /// If an exception object is stored in the logging event - /// it will be rendered into the pattern output with a - /// trailing newline. - /// - /// - /// If there is no exception then nothing will be output - /// and no trailing newline will be appended. - /// It is typical to put a newline before the exception - /// and to have the exception as the last data in the pattern. - /// - /// - /// Nicko Cadell. - internal sealed class ExceptionPatternConverter : PatternLayoutConverter +namespace log4net.Layout.Pattern +{ + /// + /// Write the exception text to the output + /// + /// + /// + /// If an exception object is stored in the logging event + /// it will be rendered into the pattern output with a + /// trailing newline. + /// + /// + /// If there is no exception then nothing will be output + /// and no trailing newline will be appended. + /// It is typical to put a newline before the exception + /// and to have the exception as the last data in the pattern. + /// + /// + /// Nicko Cadell + internal sealed class ExceptionPatternConverter : PatternLayoutConverter { /// - /// Initializes a new instance of the class. - /// Default constructor. - /// - public ExceptionPatternConverter() - { - // This converter handles the exception - this.IgnoresException = false; - } - - /// - /// Write the exception text to the output. - /// - /// that will receive the formatted result. - /// the event being logged. - /// - /// - /// If an exception object is stored in the logging event - /// it will be rendered into the pattern output with a - /// trailing newline. - /// - /// - /// If there is no exception or the exception property specified - /// by the Option value does not exist then nothing will be output - /// and no trailing newline will be appended. - /// It is typical to put a newline before the exception - /// and to have the exception as the last data in the pattern. - /// - /// - /// Recognized values for the Option parameter are: - /// - /// - /// - /// Message - /// - /// - /// Source - /// - /// - /// StackTrace - /// - /// - /// TargetSite - /// - /// - /// HelpLink - /// - /// - /// - protected override void Convert(TextWriter writer, LoggingEvent loggingEvent) - { - if (loggingEvent.ExceptionObject != null && this.Option != null && this.Option.Length > 0) - { - switch (this.Option.ToLower()) - { - case "message": - WriteObject(writer, loggingEvent.Repository, loggingEvent.ExceptionObject.Message); - break; -#if !NETCF - case "source": - WriteObject(writer, loggingEvent.Repository, loggingEvent.ExceptionObject.Source); - break; - case "stacktrace": - WriteObject(writer, loggingEvent.Repository, loggingEvent.ExceptionObject.StackTrace); - break; -#if !NETSTANDARD1_3 - case "targetsite": - WriteObject(writer, loggingEvent.Repository, loggingEvent.ExceptionObject.TargetSite); - break; -#endif - case "helplink": - WriteObject(writer, loggingEvent.Repository, loggingEvent.ExceptionObject.HelpLink); - break; -#endif - default: - // do not output SystemInfo.NotAvailableText - break; - } - } - else - { - string exceptionString = loggingEvent.GetExceptionString(); - if (exceptionString != null && exceptionString.Length > 0) - { - writer.WriteLine(exceptionString); - } - else - { - // do not output SystemInfo.NotAvailableText - } - } - } - } -} + /// Default constructor + /// + public ExceptionPatternConverter() + { + // This converter handles the exception + this.IgnoresException = false; + } + + /// + /// Write the exception text to the output + /// + /// that will receive the formatted result. + /// the event being logged + /// + /// + /// If an exception object is stored in the logging event + /// it will be rendered into the pattern output with a + /// trailing newline. + /// + /// + /// If there is no exception or the exception property specified + /// by the Option value does not exist then nothing will be output + /// and no trailing newline will be appended. + /// It is typical to put a newline before the exception + /// and to have the exception as the last data in the pattern. + /// + /// + /// Recognized values for the Option parameter are: + /// + /// + /// + /// Message + /// + /// + /// Source + /// + /// + /// StackTrace + /// + /// + /// TargetSite + /// + /// + /// HelpLink + /// + /// + /// + protected override void Convert(TextWriter writer, LoggingEvent loggingEvent) + { + if (loggingEvent.ExceptionObject != null && this.Option != null && this.Option.Length > 0) + { + switch (this.Option.ToLower()) + { + case "message": + WriteObject(writer, loggingEvent.Repository, loggingEvent.ExceptionObject.Message); + break; +#if !NETCF + case "source": + WriteObject(writer, loggingEvent.Repository, loggingEvent.ExceptionObject.Source); + break; + case "stacktrace": + WriteObject(writer, loggingEvent.Repository, loggingEvent.ExceptionObject.StackTrace); + break; +#if !NETSTANDARD + case "targetsite": + WriteObject(writer, loggingEvent.Repository, loggingEvent.ExceptionObject.TargetSite); + break; +#endif + case "helplink": + WriteObject(writer, loggingEvent.Repository, loggingEvent.ExceptionObject.HelpLink); + break; +#endif + default: + // do not output SystemInfo.NotAvailableText + break; + } + } + else + { + string exceptionString = loggingEvent.GetExceptionString(); + if (exceptionString != null && exceptionString.Length > 0) + { + writer.WriteLine(exceptionString); + } + else + { + // do not output SystemInfo.NotAvailableText + } + } + } + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/FileLocationPatternConverter.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/FileLocationPatternConverter.cs index 894610563d8..edbdf449b3f 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/FileLocationPatternConverter.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/FileLocationPatternConverter.cs @@ -1,57 +1,57 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.Layout.Pattern -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; - using System.IO; - using System.Text; +using System; +using System.Text; +using System.IO; - using log4net.Core; +using log4net.Core; - /// - /// Writes the caller location file name to the output. - /// - /// - /// - /// Writes the value of the for - /// the event to the output writer. - /// - /// - /// Nicko Cadell. - internal sealed class FileLocationPatternConverter : PatternLayoutConverter - { - /// - /// Write the caller location file name to the output. - /// - /// that will receive the formatted result. - /// the event being logged. - /// - /// - /// Writes the value of the for - /// the to the output . - /// - /// - protected override void Convert(TextWriter writer, LoggingEvent loggingEvent) - { - writer.Write(loggingEvent.LocationInformation.FileName); - } - } -} +namespace log4net.Layout.Pattern +{ + /// + /// Writes the caller location file name to the output + /// + /// + /// + /// Writes the value of the for + /// the event to the output writer. + /// + /// + /// Nicko Cadell + internal sealed class FileLocationPatternConverter : PatternLayoutConverter + { + /// + /// Write the caller location file name to the output + /// + /// that will receive the formatted result. + /// the event being logged + /// + /// + /// Writes the value of the for + /// the to the output . + /// + /// + protected override void Convert(TextWriter writer, LoggingEvent loggingEvent) + { + writer.Write(loggingEvent.LocationInformation.FileName); + } + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/FullLocationPatternConverter.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/FullLocationPatternConverter.cs index fa487fbff1b..4896947073d 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/FullLocationPatternConverter.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/FullLocationPatternConverter.cs @@ -1,55 +1,55 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.Layout.Pattern -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; - using System.IO; - using System.Text; +using System; +using System.Text; +using System.IO; - using log4net.Core; +using log4net.Core; - /// - /// Write the caller location info to the output. - /// - /// - /// - /// Writes the to the output writer. - /// - /// - /// Nicko Cadell. - internal sealed class FullLocationPatternConverter : PatternLayoutConverter - { - /// - /// Write the caller location info to the output. - /// - /// that will receive the formatted result. - /// the event being logged. - /// - /// - /// Writes the to the output writer. - /// - /// - protected override void Convert(TextWriter writer, LoggingEvent loggingEvent) - { - writer.Write(loggingEvent.LocationInformation.FullInfo); - } - } -} +namespace log4net.Layout.Pattern +{ + /// + /// Write the caller location info to the output + /// + /// + /// + /// Writes the to the output writer. + /// + /// + /// Nicko Cadell + internal sealed class FullLocationPatternConverter : PatternLayoutConverter + { + /// + /// Write the caller location info to the output + /// + /// that will receive the formatted result. + /// the event being logged + /// + /// + /// Writes the to the output writer. + /// + /// + protected override void Convert(TextWriter writer, LoggingEvent loggingEvent) + { + writer.Write(loggingEvent.LocationInformation.FullInfo); + } + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/IdentityPatternConverter.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/IdentityPatternConverter.cs index 9f316651005..fd173868bf7 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/IdentityPatternConverter.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/IdentityPatternConverter.cs @@ -1,59 +1,59 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.Layout.Pattern -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; - using System.IO; - using System.Text; +using System; +using System.Text; +using System.IO; - using log4net.Core; +using log4net.Core; - /// - /// Writes the event identity to the output. - /// - /// - /// - /// Writes the value of the to - /// the output writer. - /// - /// - /// Daniel Cazzulino. - /// Nicko Cadell. - internal sealed class IdentityPatternConverter : PatternLayoutConverter - { - /// - /// Writes the event identity to the output. - /// - /// that will receive the formatted result. - /// the event being logged. - /// - /// - /// Writes the value of the - /// to - /// the output . - /// - /// - protected override void Convert(TextWriter writer, LoggingEvent loggingEvent) - { - writer.Write(loggingEvent.Identity); - } - } -} +namespace log4net.Layout.Pattern +{ + /// + /// Writes the event identity to the output + /// + /// + /// + /// Writes the value of the to + /// the output writer. + /// + /// + /// Daniel Cazzulino + /// Nicko Cadell + internal sealed class IdentityPatternConverter : PatternLayoutConverter + { + /// + /// Writes the event identity to the output + /// + /// that will receive the formatted result. + /// the event being logged + /// + /// + /// Writes the value of the + /// to + /// the output . + /// + /// + protected override void Convert(TextWriter writer, LoggingEvent loggingEvent) + { + writer.Write(loggingEvent.Identity); + } + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/LevelPatternConverter.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/LevelPatternConverter.cs index b7b2d95654d..6f89aaf866f 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/LevelPatternConverter.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/LevelPatternConverter.cs @@ -1,57 +1,57 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.Layout.Pattern -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; - using System.IO; - using System.Text; +using System; +using System.Text; +using System.IO; - using log4net.Core; +using log4net.Core; - /// - /// Write the event level to the output. - /// - /// - /// - /// Writes the display name of the event - /// to the writer. - /// - /// - /// Nicko Cadell. - internal sealed class LevelPatternConverter : PatternLayoutConverter - { - /// - /// Write the event level to the output. - /// - /// that will receive the formatted result. - /// the event being logged. - /// - /// - /// Writes the of the - /// to the . - /// - /// - protected override void Convert(TextWriter writer, LoggingEvent loggingEvent) - { - writer.Write(loggingEvent.Level.DisplayName); - } - } -} +namespace log4net.Layout.Pattern +{ + /// + /// Write the event level to the output + /// + /// + /// + /// Writes the display name of the event + /// to the writer. + /// + /// + /// Nicko Cadell + internal sealed class LevelPatternConverter : PatternLayoutConverter + { + /// + /// Write the event level to the output + /// + /// that will receive the formatted result. + /// the event being logged + /// + /// + /// Writes the of the + /// to the . + /// + /// + protected override void Convert(TextWriter writer, LoggingEvent loggingEvent) + { + writer.Write(loggingEvent.Level.DisplayName); + } + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/LineLocationPatternConverter.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/LineLocationPatternConverter.cs index d7d24fda223..692e58cc5ac 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/LineLocationPatternConverter.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/LineLocationPatternConverter.cs @@ -1,57 +1,57 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.Layout.Pattern -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; - using System.IO; - using System.Text; +using System; +using System.Text; +using System.IO; - using log4net.Core; +using log4net.Core; - /// - /// Write the caller location line number to the output. - /// - /// - /// - /// Writes the value of the for - /// the event to the output writer. - /// - /// - /// Nicko Cadell. - internal sealed class LineLocationPatternConverter : PatternLayoutConverter - { - /// - /// Write the caller location line number to the output. - /// - /// that will receive the formatted result. - /// the event being logged. - /// - /// - /// Writes the value of the for - /// the to the output . - /// - /// - protected override void Convert(TextWriter writer, LoggingEvent loggingEvent) - { - writer.Write(loggingEvent.LocationInformation.LineNumber); - } - } -} +namespace log4net.Layout.Pattern +{ + /// + /// Write the caller location line number to the output + /// + /// + /// + /// Writes the value of the for + /// the event to the output writer. + /// + /// + /// Nicko Cadell + internal sealed class LineLocationPatternConverter : PatternLayoutConverter + { + /// + /// Write the caller location line number to the output + /// + /// that will receive the formatted result. + /// the event being logged + /// + /// + /// Writes the value of the for + /// the to the output . + /// + /// + protected override void Convert(TextWriter writer, LoggingEvent loggingEvent) + { + writer.Write(loggingEvent.LocationInformation.LineNumber); + } + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/LoggerPatternConverter.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/LoggerPatternConverter.cs index 311b5150c26..d34291d8d99 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/LoggerPatternConverter.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/LoggerPatternConverter.cs @@ -1,55 +1,55 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.Layout.Pattern -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; - using System.IO; - using System.Text; +using System; +using System.Text; +using System.IO; - using log4net.Core; +using log4net.Core; - /// - /// Converter for logger name. - /// - /// - /// - /// Outputs the of the event. - /// - /// - /// Nicko Cadell. - internal sealed class LoggerPatternConverter : NamedPatternConverter - { - /// - /// Gets the fully qualified name of the logger. - /// - /// the event being logged. - /// The fully qualified logger name. - /// - /// - /// Returns the of the . - /// - /// - protected override string GetFullyQualifiedName(LoggingEvent loggingEvent) - { - return loggingEvent.LoggerName; - } - } -} +namespace log4net.Layout.Pattern +{ + /// + /// Converter for logger name + /// + /// + /// + /// Outputs the of the event. + /// + /// + /// Nicko Cadell + internal sealed class LoggerPatternConverter : NamedPatternConverter + { + /// + /// Gets the fully qualified name of the logger + /// + /// the event being logged + /// The fully qualified logger name + /// + /// + /// Returns the of the . + /// + /// + protected override string GetFullyQualifiedName(LoggingEvent loggingEvent) + { + return loggingEvent.LoggerName; + } + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/MessagePatternConverter.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/MessagePatternConverter.cs index 79e70453b33..9ef6cc9dfa9 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/MessagePatternConverter.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/MessagePatternConverter.cs @@ -1,57 +1,57 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.Layout.Pattern -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; - using System.IO; - using System.Text; +using System; +using System.Text; +using System.IO; - using log4net.Core; +using log4net.Core; - /// - /// Writes the event message to the output. - /// - /// - /// - /// Uses the method - /// to write out the event message. - /// - /// - /// Nicko Cadell. - internal sealed class MessagePatternConverter : PatternLayoutConverter - { - /// - /// Writes the event message to the output. - /// - /// that will receive the formatted result. - /// the event being logged. - /// - /// - /// Uses the method - /// to write out the event message. - /// - /// - protected override void Convert(TextWriter writer, LoggingEvent loggingEvent) - { - loggingEvent.WriteRenderedMessage(writer); - } - } -} +namespace log4net.Layout.Pattern +{ + /// + /// Writes the event message to the output + /// + /// + /// + /// Uses the method + /// to write out the event message. + /// + /// + /// Nicko Cadell + internal sealed class MessagePatternConverter : PatternLayoutConverter + { + /// + /// Writes the event message to the output + /// + /// that will receive the formatted result. + /// the event being logged + /// + /// + /// Uses the method + /// to write out the event message. + /// + /// + protected override void Convert(TextWriter writer, LoggingEvent loggingEvent) + { + loggingEvent.WriteRenderedMessage(writer); + } + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/MethodLocationPatternConverter.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/MethodLocationPatternConverter.cs index 8e3ffa64e3f..102e4e71d08 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/MethodLocationPatternConverter.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/MethodLocationPatternConverter.cs @@ -1,57 +1,57 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.Layout.Pattern -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; - using System.IO; - using System.Text; +using System; +using System.Text; +using System.IO; - using log4net.Core; +using log4net.Core; - /// - /// Write the method name to the output. - /// - /// - /// - /// Writes the caller location to - /// the output. - /// - /// - /// Nicko Cadell. - internal sealed class MethodLocationPatternConverter : PatternLayoutConverter - { - /// - /// Write the method name to the output. - /// - /// that will receive the formatted result. - /// the event being logged. - /// - /// - /// Writes the caller location to - /// the output. - /// - /// - protected override void Convert(TextWriter writer, LoggingEvent loggingEvent) - { - writer.Write(loggingEvent.LocationInformation.MethodName); - } - } -} +namespace log4net.Layout.Pattern +{ + /// + /// Write the method name to the output + /// + /// + /// + /// Writes the caller location to + /// the output. + /// + /// + /// Nicko Cadell + internal sealed class MethodLocationPatternConverter : PatternLayoutConverter + { + /// + /// Write the method name to the output + /// + /// that will receive the formatted result. + /// the event being logged + /// + /// + /// Writes the caller location to + /// the output. + /// + /// + protected override void Convert(TextWriter writer, LoggingEvent loggingEvent) + { + writer.Write(loggingEvent.LocationInformation.MethodName); + } + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/NamedPatternConverter.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/NamedPatternConverter.cs index c3119090971..cd06db0bbc5 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/NamedPatternConverter.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/NamedPatternConverter.cs @@ -1,166 +1,165 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.Layout.Pattern -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; - using System.Globalization; - using System.IO; - using System.Text; +using System; +using System.Globalization; +using System.Text; +using System.IO; - using log4net.Core; - using log4net.Util; +using log4net.Core; +using log4net.Util; - /// - /// Converter to output and truncate '.' separated strings. - /// - /// - /// - /// This abstract class supports truncating a '.' separated string - /// to show a specified number of elements from the right hand side. - /// This is used to truncate class names that are fully qualified. - /// - /// - /// Subclasses should override the method to - /// return the fully qualified string. - /// - /// - /// Nicko Cadell. - public abstract class NamedPatternConverter : PatternLayoutConverter, IOptionHandler - { +namespace log4net.Layout.Pattern +{ + /// + /// Converter to output and truncate '.' separated strings + /// + /// + /// + /// This abstract class supports truncating a '.' separated string + /// to show a specified number of elements from the right hand side. + /// This is used to truncate class names that are fully qualified. + /// + /// + /// Subclasses should override the method to + /// return the fully qualified string. + /// + /// + /// Nicko Cadell + public abstract class NamedPatternConverter : PatternLayoutConverter, IOptionHandler + { private int m_precision = 0; - /// - /// Initialize the converter. - /// - /// - /// - /// This is part of the delayed object - /// activation scheme. The method must - /// be called on this object after the configuration properties have - /// been set. Until is called this - /// object is in an undefined state and must not be used. - /// - /// - /// If any of the configuration properties are modified then - /// must be called again. - /// - /// - public void ActivateOptions() - { - this.m_precision = 0; - - if (this.Option != null) - { - string optStr = this.Option.Trim(); - if (optStr.Length > 0) - { - int precisionVal; - if (SystemInfo.TryParse(optStr, out precisionVal)) - { - if (precisionVal <= 0) - { - LogLog.Error(declaringType, "NamedPatternConverter: Precision option (" + optStr + ") isn't a positive integer."); - } - else - { - this.m_precision = precisionVal; - } - } - else - { - LogLog.Error(declaringType, "NamedPatternConverter: Precision option \"" + optStr + "\" not a decimal integer."); - } - } - } + /// + /// Initialize the converter + /// + /// + /// + /// This is part of the delayed object + /// activation scheme. The method must + /// be called on this object after the configuration properties have + /// been set. Until is called this + /// object is in an undefined state and must not be used. + /// + /// + /// If any of the configuration properties are modified then + /// must be called again. + /// + /// + public void ActivateOptions() + { + this.m_precision = 0; + + if (this.Option != null) + { + string optStr = this.Option.Trim(); + if (optStr.Length > 0) + { + int precisionVal; + if (SystemInfo.TryParse(optStr, out precisionVal)) + { + if (precisionVal <= 0) + { + LogLog.Error(declaringType, "NamedPatternConverter: Precision option (" + optStr + ") isn't a positive integer."); + } + else + { + this.m_precision = precisionVal; + } + } + else + { + LogLog.Error(declaringType, "NamedPatternConverter: Precision option \"" + optStr + "\" not a decimal integer."); + } + } + } } - /// - /// Get the fully qualified string data. - /// - /// the event being logged. - /// the fully qualified name. - /// - /// - /// Overridden by subclasses to get the fully qualified name before the - /// precision is applied to it. - /// - /// - /// Return the fully qualified '.' (dot/period) separated string. - /// - /// - protected abstract string GetFullyQualifiedName(LoggingEvent loggingEvent); - - /// - /// Convert the pattern to the rendered message. - /// - /// that will receive the formatted result. - /// the event being logged. - /// - /// Render the to the precision - /// specified by the property. - /// - protected sealed override void Convert(TextWriter writer, LoggingEvent loggingEvent) - { - string name = this.GetFullyQualifiedName(loggingEvent); - if (this.m_precision <= 0 || name == null || name.Length < 2) - { - writer.Write(name); - } - else - { - int len = name.Length; - string trailingDot = string.Empty; - if (name.EndsWith(DOT)) - { - trailingDot = DOT; - name = name.Substring(0, len - 1); - len--; - } - - int end = name.LastIndexOf(DOT); - for (int i = 1; end > 0 && i < this.m_precision; i++) - { - end = name.LastIndexOf('.', end - 1); - } + /// + /// Get the fully qualified string data + /// + /// the event being logged + /// the fully qualified name + /// + /// + /// Overridden by subclasses to get the fully qualified name before the + /// precision is applied to it. + /// + /// + /// Return the fully qualified '.' (dot/period) separated string. + /// + /// + protected abstract string GetFullyQualifiedName(LoggingEvent loggingEvent); + + /// + /// Convert the pattern to the rendered message + /// + /// that will receive the formatted result. + /// the event being logged + /// + /// Render the to the precision + /// specified by the property. + /// + protected sealed override void Convert(TextWriter writer, LoggingEvent loggingEvent) + { + string name = this.GetFullyQualifiedName(loggingEvent); + if (this.m_precision <= 0 || name == null || name.Length < 2) + { + writer.Write(name); + } + else + { + int len = name.Length; + string trailingDot = string.Empty; + if (name.EndsWith(DOT)) + { + trailingDot = DOT; + name = name.Substring(0, len - 1); + len--; + } - if (end == -1) - { - writer.Write(name + trailingDot); - } - else - { - writer.Write(name.Substring(end + 1, len - end - 1) + trailingDot); - } - } + int end = name.LastIndexOf(DOT); + for(int i = 1; end > 0 && i < this.m_precision; i++) + { + end = name.LastIndexOf('.', end - 1); + } + if (end == -1) + { + writer.Write(name + trailingDot); + } + else + { + writer.Write(name.Substring(end + 1, len - end - 1) + trailingDot); + } + } } - /// - /// The fully qualified type of the NamedPatternConverter class. - /// - /// - /// Used by the internal logger to record the Type of the - /// log message. - /// - private static readonly Type declaringType = typeof(NamedPatternConverter); - + /// + /// The fully qualified type of the NamedPatternConverter class. + /// + /// + /// Used by the internal logger to record the Type of the + /// log message. + /// + private static readonly Type declaringType = typeof(NamedPatternConverter); + private const string DOT = "."; - } -} + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/NdcPatternConverter.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/NdcPatternConverter.cs index ca7dbb01461..3850b54fb50 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/NdcPatternConverter.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/NdcPatternConverter.cs @@ -1,63 +1,63 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.Layout.Pattern -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; - using System.IO; - using System.Text; +using System; +using System.Text; +using System.IO; - using log4net.Core; +using log4net.Core; - /// - /// Converter to include event NDC. - /// - /// - /// - /// Outputs the value of the event property named NDC. - /// - /// - /// The should be used instead. - /// - /// - /// Nicko Cadell. - internal sealed class NdcPatternConverter : PatternLayoutConverter - { - /// - /// Write the event NDC to the output. - /// - /// that will receive the formatted result. - /// the event being logged. - /// - /// - /// As the thread context stacks are now stored in named event properties - /// this converter simply looks up the value of the NDC property. - /// - /// - /// The should be used instead. - /// - /// - protected override void Convert(TextWriter writer, LoggingEvent loggingEvent) - { - // Write the value for the specified key - WriteObject(writer, loggingEvent.Repository, loggingEvent.LookupProperty("NDC")); - } - } -} +namespace log4net.Layout.Pattern +{ + /// + /// Converter to include event NDC + /// + /// + /// + /// Outputs the value of the event property named NDC. + /// + /// + /// The should be used instead. + /// + /// + /// Nicko Cadell + internal sealed class NdcPatternConverter : PatternLayoutConverter + { + /// + /// Write the event NDC to the output + /// + /// that will receive the formatted result. + /// the event being logged + /// + /// + /// As the thread context stacks are now stored in named event properties + /// this converter simply looks up the value of the NDC property. + /// + /// + /// The should be used instead. + /// + /// + protected override void Convert(TextWriter writer, LoggingEvent loggingEvent) + { + // Write the value for the specified key + WriteObject(writer, loggingEvent.Repository, loggingEvent.LookupProperty("NDC")); + } + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/PatternLayoutConverter.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/PatternLayoutConverter.cs index 71abd6f5f37..a19b6c46e2f 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/PatternLayoutConverter.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/PatternLayoutConverter.cs @@ -1,108 +1,108 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.Layout.Pattern -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; - using System.Collections; - using System.IO; - using System.Text; +using System; +using System.Text; +using System.IO; +using System.Collections; - using log4net.Core; - using log4net.Repository; - using log4net.Util; +using log4net.Core; +using log4net.Util; +using log4net.Repository; - /// - /// Abstract class that provides the formatting functionality that - /// derived classes need. - /// - /// - /// Conversion specifiers in a conversion patterns are parsed to - /// individual PatternConverters. Each of which is responsible for - /// converting a logging event in a converter specific manner. - /// - /// Nicko Cadell. - public abstract class PatternLayoutConverter : PatternConverter +namespace log4net.Layout.Pattern +{ + /// + /// Abstract class that provides the formatting functionality that + /// derived classes need. + /// + /// + /// Conversion specifiers in a conversion patterns are parsed to + /// individual PatternConverters. Each of which is responsible for + /// converting a logging event in a converter specific manner. + /// + /// Nicko Cadell + public abstract class PatternLayoutConverter : PatternConverter { - /// - /// Initializes a new instance of the class. - /// - protected PatternLayoutConverter() - { + /// + /// Initializes a new instance of the class. + /// + protected PatternLayoutConverter() + { } - /// - /// Gets or sets a value indicating whether flag indicating if this converter handles the logging event exception. - /// - /// false if this converter handles the logging event exception. - /// - /// - /// If this converter handles the exception object contained within - /// , then this property should be set to - /// false. Otherwise, if the layout ignores the exception - /// object, then the property should be set to true. - /// - /// - /// Set this value to override a this default setting. The default - /// value is true, this converter does not handle the exception. - /// - /// - public virtual bool IgnoresException - { - get { return this.m_ignoresException; } - set { this.m_ignoresException = value; } + /// + /// Flag indicating if this converter handles the logging event exception + /// + /// false if this converter handles the logging event exception + /// + /// + /// If this converter handles the exception object contained within + /// , then this property should be set to + /// false. Otherwise, if the layout ignores the exception + /// object, then the property should be set to true. + /// + /// + /// Set this value to override a this default setting. The default + /// value is true, this converter does not handle the exception. + /// + /// + public virtual bool IgnoresException + { + get { return this.m_ignoresException; } + set { this.m_ignoresException = value; } } - /// - /// Derived pattern converters must override this method in order to - /// convert conversion specifiers in the correct way. - /// - /// that will receive the formatted result. - /// The on which the pattern converter should be executed. + /// + /// Derived pattern converters must override this method in order to + /// convert conversion specifiers in the correct way. + /// + /// that will receive the formatted result. + /// The on which the pattern converter should be executed. protected abstract void Convert(TextWriter writer, LoggingEvent loggingEvent); - /// - /// Derived pattern converters must override this method in order to - /// convert conversion specifiers in the correct way. - /// - /// that will receive the formatted result. - /// The state object on which the pattern converter should be executed. - protected override void Convert(TextWriter writer, object state) - { - LoggingEvent loggingEvent = state as LoggingEvent; - if (loggingEvent != null) - { - this.Convert(writer, loggingEvent); - } - else - { - throw new ArgumentException("state must be of type [" + typeof(LoggingEvent).FullName + "]", "state"); - } + /// + /// Derived pattern converters must override this method in order to + /// convert conversion specifiers in the correct way. + /// + /// that will receive the formatted result. + /// The state object on which the pattern converter should be executed. + protected override void Convert(TextWriter writer, object state) + { + LoggingEvent loggingEvent = state as LoggingEvent; + if (loggingEvent != null) + { + this.Convert(writer, loggingEvent); + } + else + { + throw new ArgumentException("state must be of type [" + typeof(LoggingEvent).FullName + "]", "state"); + } } - /// - /// Flag indicating if this converter handles exceptions. - /// - /// - /// false if this converter handles exceptions. - /// - private bool m_ignoresException = true; - } -} + /// + /// Flag indicating if this converter handles exceptions + /// + /// + /// false if this converter handles exceptions + /// + private bool m_ignoresException = true; + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/PropertyPatternConverter.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/PropertyPatternConverter.cs index 8959edac5b9..0205c8c2e82 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/PropertyPatternConverter.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/PropertyPatternConverter.cs @@ -1,78 +1,78 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.Layout.Pattern -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; - using System.Collections; - using System.IO; - using System.Text; +using System; +using System.Text; +using System.IO; +using System.Collections; - using log4net.Core; - using log4net.Repository; +using log4net.Core; +using log4net.Repository; - /// - /// Property pattern converter. - /// - /// - /// - /// Writes out the value of a named property. The property name - /// should be set in the - /// property. - /// - /// - /// If the is set to null - /// then all the properties are written as key value pairs. - /// - /// - /// Nicko Cadell. - internal sealed class PropertyPatternConverter : PatternLayoutConverter - { - /// - /// Write the property value to the output. - /// - /// that will receive the formatted result. - /// the event being logged. - /// - /// - /// Writes out the value of a named property. The property name - /// should be set in the - /// property. - /// - /// - /// If the is set to null - /// then all the properties are written as key value pairs. - /// - /// - protected override void Convert(TextWriter writer, LoggingEvent loggingEvent) - { - if (this.Option != null) - { - // Write the value for the specified key - WriteObject(writer, loggingEvent.Repository, loggingEvent.LookupProperty(this.Option)); - } - else - { - // Write all the key value pairs - WriteDictionary(writer, loggingEvent.Repository, loggingEvent.GetProperties()); - } - } - } -} +namespace log4net.Layout.Pattern +{ + /// + /// Property pattern converter + /// + /// + /// + /// Writes out the value of a named property. The property name + /// should be set in the + /// property. + /// + /// + /// If the is set to null + /// then all the properties are written as key value pairs. + /// + /// + /// Nicko Cadell + internal sealed class PropertyPatternConverter : PatternLayoutConverter + { + /// + /// Write the property value to the output + /// + /// that will receive the formatted result. + /// the event being logged + /// + /// + /// Writes out the value of a named property. The property name + /// should be set in the + /// property. + /// + /// + /// If the is set to null + /// then all the properties are written as key value pairs. + /// + /// + protected override void Convert(TextWriter writer, LoggingEvent loggingEvent) + { + if (this.Option != null) + { + // Write the value for the specified key + WriteObject(writer, loggingEvent.Repository, loggingEvent.LookupProperty(this.Option)); + } + else + { + // Write all the key value pairs + WriteDictionary(writer, loggingEvent.Repository, loggingEvent.GetProperties()); + } + } + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/RelativeTimePatternConverter.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/RelativeTimePatternConverter.cs index 413610007ba..985710791cd 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/RelativeTimePatternConverter.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/RelativeTimePatternConverter.cs @@ -1,71 +1,71 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.Layout.Pattern -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; - using System.IO; - using System.Text; +using System; +using System.Text; +using System.IO; - using log4net.Core; +using log4net.Core; - /// - /// Converter to output the relative time of the event. - /// - /// - /// - /// Converter to output the time of the event relative to the start of the program. - /// - /// - /// Nicko Cadell. - internal sealed class RelativeTimePatternConverter : PatternLayoutConverter - { - /// - /// Write the relative time to the output. - /// - /// that will receive the formatted result. - /// the event being logged. - /// - /// - /// Writes out the relative time of the event in milliseconds. - /// That is the number of milliseconds between the event - /// and the . - /// - /// - protected override void Convert(TextWriter writer, LoggingEvent loggingEvent) - { - writer.Write(TimeDifferenceInMillis(LoggingEvent.StartTimeUtc, loggingEvent.TimeStampUtc).ToString(System.Globalization.NumberFormatInfo.InvariantInfo)); - } - - /// - /// Helper method to get the time difference between two DateTime objects. - /// - /// start time (in the current local time zone). - /// end time (in the current local time zone). - /// the time difference in milliseconds. - private static long TimeDifferenceInMillis(DateTime start, DateTime end) - { - // We must convert all times to UTC before performing any mathematical - // operations on them. This allows use to take into account discontinuities - // caused by daylight savings time transitions. - return (long)(end.ToUniversalTime() - start.ToUniversalTime()).TotalMilliseconds; - } - } -} +namespace log4net.Layout.Pattern +{ + /// + /// Converter to output the relative time of the event + /// + /// + /// + /// Converter to output the time of the event relative to the start of the program. + /// + /// + /// Nicko Cadell + internal sealed class RelativeTimePatternConverter : PatternLayoutConverter + { + /// + /// Write the relative time to the output + /// + /// that will receive the formatted result. + /// the event being logged + /// + /// + /// Writes out the relative time of the event in milliseconds. + /// That is the number of milliseconds between the event + /// and the . + /// + /// + protected override void Convert(TextWriter writer, LoggingEvent loggingEvent) + { + writer.Write(TimeDifferenceInMillis(LoggingEvent.StartTimeUtc, loggingEvent.TimeStampUtc).ToString(System.Globalization.NumberFormatInfo.InvariantInfo)); + } + + /// + /// Helper method to get the time difference between two DateTime objects + /// + /// start time (in the current local time zone) + /// end time (in the current local time zone) + /// the time difference in milliseconds + private static long TimeDifferenceInMillis(DateTime start, DateTime end) + { + // We must convert all times to UTC before performing any mathematical + // operations on them. This allows use to take into account discontinuities + // caused by daylight savings time transitions. + return (long)(end.ToUniversalTime() - start.ToUniversalTime()).TotalMilliseconds; + } + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/StackTraceDetailPatternConverter.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/StackTraceDetailPatternConverter.cs index 857dc95c99a..a04ad38ae00 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/StackTraceDetailPatternConverter.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/StackTraceDetailPatternConverter.cs @@ -1,91 +1,86 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * -*/ -#if !NETCF - -using System; -using System.Collections; -using System.Text; +#if !NETCF && (NET_2_0 || NETSTANDARD2_0) -using log4net.Core; -using log4net.Util; - -namespace log4net.Layout.Pattern -{ - /// - /// Write the caller stack frames to the output. - /// - /// - /// - /// Writes the to the output writer, using format: - /// type3.MethodCall3(type param,...) > type2.MethodCall2(type param,...) > type1.MethodCall1(type param,...) - /// - /// - /// Adam Davies. - internal class StackTraceDetailPatternConverter : StackTracePatternConverter - { - internal override string GetMethodInformation(MethodItem method) - { - string returnValue = string.Empty; - - try - { - string param = string.Empty; - string[] names = method.Parameters; - StringBuilder sb = new StringBuilder(); - if (names != null && names.GetUpperBound(0) > 0) - { - for (int i = 0; i <= names.GetUpperBound(0); i++) - { - sb.AppendFormat("{0}, ", names[i]); - } - } - - if (sb.Length > 0) - { - sb.Remove(sb.Length - 2, 2); - param = sb.ToString(); - } - - returnValue = base.GetMethodInformation(method) + "(" + param + ")"; - } - catch (Exception ex) - { - LogLog.Error(declaringType, "An exception ocurred while retreiving method information.", ex); - } - - return returnValue; +using System; +using System.Text; + +using log4net.Util; +using log4net.Core; + +namespace log4net.Layout.Pattern +{ + /// + /// Write the caller stack frames to the output + /// + /// + /// + /// Writes the to the output writer, using format: + /// type3.MethodCall3(type param,...) > type2.MethodCall2(type param,...) > type1.MethodCall1(type param,...) + /// + /// + /// Adam Davies + internal class StackTraceDetailPatternConverter : StackTracePatternConverter + { + internal override string GetMethodInformation(MethodItem method) + { + string returnValue = string.Empty; + + try + { + string param = string.Empty; + string[] names = method.Parameters; + StringBuilder sb = new StringBuilder(); + if (names != null && names.GetUpperBound(0) > 0) + { + for (int i = 0; i <= names.GetUpperBound(0); i++) + { + sb.AppendFormat("{0}, ", names[i]); + } + } + + if (sb.Length > 0) + { + sb.Remove(sb.Length - 2, 2); + param = sb.ToString(); + } + + returnValue = base.GetMethodInformation(method) + "(" + param + ")"; + } + catch (Exception ex) + { + LogLog.Error(declaringType, "An exception ocurred while retreiving method information.", ex); + } + + return returnValue; } - /// - /// The fully qualified type of the StackTraceDetailPatternConverter class. - /// - /// - /// Used by the internal logger to record the Type of the - /// log message. - /// + /// + /// The fully qualified type of the StackTraceDetailPatternConverter class. + /// + /// + /// Used by the internal logger to record the Type of the + /// log message. + /// private static readonly Type declaringType = typeof(StackTracePatternConverter); - } -} -#endif + } +} +#endif // !NETCF && NET_2_0 diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/StackTracePatternConverter.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/StackTracePatternConverter.cs index cbf7a1339dd..0d18b5e15ae 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/StackTracePatternConverter.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/StackTracePatternConverter.cs @@ -1,151 +1,149 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#if !NETCF -using System; -using System.Diagnostics; -using System.IO; +#if !NETCF && (NET_2_0 || NETSTANDARD2_0) +using System; +using System.IO; -using log4net.Core; -using log4net.Util; - -namespace log4net.Layout.Pattern -{ - /// - /// Write the caller stack frames to the output. - /// - /// - /// - /// Writes the to the output writer, using format: - /// type3.MethodCall3 > type2.MethodCall2 > type1.MethodCall1. - /// - /// - /// Michael Cromwell. - internal class StackTracePatternConverter : PatternLayoutConverter, IOptionHandler - { - private int m_stackFrameLevel = 1; - - /// - /// Initialize the converter. - /// - /// - /// - /// This is part of the delayed object - /// activation scheme. The method must - /// be called on this object after the configuration properties have - /// been set. Until is called this - /// object is in an undefined state and must not be used. - /// - /// - /// If any of the configuration properties are modified then - /// must be called again. - /// - /// - public void ActivateOptions() - { +using log4net.Util; +using log4net.Core; + +namespace log4net.Layout.Pattern +{ + /// + /// Write the caller stack frames to the output + /// + /// + /// + /// Writes the to the output writer, using format: + /// type3.MethodCall3 > type2.MethodCall2 > type1.MethodCall1 + /// + /// + /// Michael Cromwell + internal class StackTracePatternConverter : PatternLayoutConverter, IOptionHandler + { + private int m_stackFrameLevel = 1; + + /// + /// Initialize the converter + /// + /// + /// + /// This is part of the delayed object + /// activation scheme. The method must + /// be called on this object after the configuration properties have + /// been set. Until is called this + /// object is in an undefined state and must not be used. + /// + /// + /// If any of the configuration properties are modified then + /// must be called again. + /// + /// + public void ActivateOptions() + { if (this.Option == null) { return; } - string optStr = this.Option.Trim(); - if (optStr.Length != 0) - { - int stackLevelVal; - if (SystemInfo.TryParse(optStr, out stackLevelVal)) - { - if (stackLevelVal <= 0) - { - LogLog.Error(declaringType, "StackTracePatternConverter: StackeFrameLevel option (" + optStr + ") isn't a positive integer."); - } - else - { - this.m_stackFrameLevel = stackLevelVal; - } - } - else - { - LogLog.Error(declaringType, "StackTracePatternConverter: StackFrameLevel option \"" + optStr + "\" not a decimal integer."); - } - } - } - - /// - /// Write the strack frames to the output. - /// - /// that will receive the formatted result. - /// the event being logged. - /// - /// - /// Writes the to the output writer. - /// - /// - protected override void Convert(TextWriter writer, LoggingEvent loggingEvent) - { - StackFrameItem[] stackframes = loggingEvent.LocationInformation.StackFrames; - if ((stackframes == null) || (stackframes.Length <= 0)) - { - LogLog.Error(declaringType, "loggingEvent.LocationInformation.StackFrames was null or empty."); - return; - } - - int stackFrameIndex = this.m_stackFrameLevel - 1; - while (stackFrameIndex >= 0) - { - if (stackFrameIndex >= stackframes.Length) - { - stackFrameIndex--; - continue; - } - - StackFrameItem stackFrame = stackframes[stackFrameIndex]; - writer.Write("{0}.{1}", stackFrame.ClassName, this.GetMethodInformation(stackFrame.Method)); - if (stackFrameIndex > 0) - { - // TODO: make this user settable? - writer.Write(" > "); - } - - stackFrameIndex--; - } + string optStr = this.Option.Trim(); + if (optStr.Length != 0) + { + int stackLevelVal; + if (SystemInfo.TryParse(optStr, out stackLevelVal)) + { + if (stackLevelVal <= 0) + { + LogLog.Error(declaringType, "StackTracePatternConverter: StackeFrameLevel option (" + optStr + ") isn't a positive integer."); + } + else + { + this.m_stackFrameLevel = stackLevelVal; + } + } + else + { + LogLog.Error(declaringType, "StackTracePatternConverter: StackFrameLevel option \"" + optStr + "\" not a decimal integer."); + } + } + } + + /// + /// Write the strack frames to the output + /// + /// that will receive the formatted result. + /// the event being logged + /// + /// + /// Writes the to the output writer. + /// + /// + protected override void Convert(TextWriter writer, LoggingEvent loggingEvent) + { + StackFrameItem[] stackframes = loggingEvent.LocationInformation.StackFrames; + if ((stackframes == null) || (stackframes.Length <= 0)) + { + LogLog.Error(declaringType, "loggingEvent.LocationInformation.StackFrames was null or empty."); + return; + } + + int stackFrameIndex = this.m_stackFrameLevel - 1; + while (stackFrameIndex >= 0) + { + if (stackFrameIndex >= stackframes.Length) + { + stackFrameIndex--; + continue; + } + + StackFrameItem stackFrame = stackframes[stackFrameIndex]; + writer.Write("{0}.{1}", stackFrame.ClassName, this.GetMethodInformation(stackFrame.Method)); + if (stackFrameIndex > 0) + { + // TODO: make this user settable? + writer.Write(" > "); + } + stackFrameIndex--; + } } - /// - /// Returns the Name of the method. - /// - /// - /// This method was created, so this class could be used as a base class for StackTraceDetailPatternConverter. - /// string. - internal virtual string GetMethodInformation(MethodItem method) - { - return method.Name; + /// + /// Returns the Name of the method + /// + /// + /// This method was created, so this class could be used as a base class for StackTraceDetailPatternConverter + /// string + internal virtual string GetMethodInformation(MethodItem method) + { + return method.Name; } - /// - /// The fully qualified type of the StackTracePatternConverter class. - /// - /// - /// Used by the internal logger to record the Type of the - /// log message. - /// + /// + /// The fully qualified type of the StackTracePatternConverter class. + /// + /// + /// Used by the internal logger to record the Type of the + /// log message. + /// private static readonly Type declaringType = typeof(StackTracePatternConverter); - } -} -#endif + } +} +#endif // !NETCF && NET_2_0 diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/ThreadPatternConverter.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/ThreadPatternConverter.cs index 5134f6439dc..cec2788da45 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/ThreadPatternConverter.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/ThreadPatternConverter.cs @@ -1,55 +1,55 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.Layout.Pattern -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; - using System.IO; - using System.Text; +using System; +using System.Text; +using System.IO; - using log4net.Core; +using log4net.Core; - /// - /// Converter to include event thread name. - /// - /// - /// - /// Writes the to the output. - /// - /// - /// Nicko Cadell. - internal sealed class ThreadPatternConverter : PatternLayoutConverter - { - /// - /// Write the ThreadName to the output. - /// - /// that will receive the formatted result. - /// the event being logged. - /// - /// - /// Writes the to the . - /// - /// - protected override void Convert(TextWriter writer, LoggingEvent loggingEvent) - { - writer.Write(loggingEvent.ThreadName); - } - } -} +namespace log4net.Layout.Pattern +{ + /// + /// Converter to include event thread name + /// + /// + /// + /// Writes the to the output. + /// + /// + /// Nicko Cadell + internal sealed class ThreadPatternConverter : PatternLayoutConverter + { + /// + /// Write the ThreadName to the output + /// + /// that will receive the formatted result. + /// the event being logged + /// + /// + /// Writes the to the . + /// + /// + protected override void Convert(TextWriter writer, LoggingEvent loggingEvent) + { + writer.Write(loggingEvent.ThreadName); + } + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/TypeNamePatternConverter.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/TypeNamePatternConverter.cs index 90cee1df9a0..e9dbe282e02 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/TypeNamePatternConverter.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/TypeNamePatternConverter.cs @@ -1,55 +1,65 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.Layout.Pattern -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; - using System.IO; - using System.Text; +using System; +using System.Text; +using System.IO; - using log4net.Core; +using log4net.Core; - /// - /// Pattern converter for the class name. - /// - /// - /// - /// Outputs the of the event. - /// - /// - /// Nicko Cadell. - internal sealed class TypeNamePatternConverter : NamedPatternConverter - { - /// - /// Gets the fully qualified name of the class. - /// - /// the event being logged. - /// The fully qualified type name for the caller location. - /// - /// - /// Returns the of the . - /// - /// - protected override string GetFullyQualifiedName(LoggingEvent loggingEvent) - { - return loggingEvent.LocationInformation.ClassName; - } - } -} +namespace log4net.Layout.Pattern +{ + /// + /// Pattern converter for the class name + /// + /// + /// + /// Outputs the of the event. + /// + /// + /// Nicko Cadell + internal sealed class TypeNamePatternConverter : NamedPatternConverter + { + /// + /// Gets the fully qualified name of the class + /// + /// the event being logged + /// The fully qualified type name for the caller location + /// + /// + /// Returns the of the . + /// + /// + protected override string GetFullyQualifiedName(LoggingEvent loggingEvent) + { + if (loggingEvent == null) + { + return string.Empty; + } + + if (loggingEvent.LocationInformation == null) + { + return string.Empty; + } + + return loggingEvent.LocationInformation.ClassName; + } + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/UserNamePatternConverter.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/UserNamePatternConverter.cs index 71b4079887a..bfb98fe3658 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/UserNamePatternConverter.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/UserNamePatternConverter.cs @@ -1,46 +1,46 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.Layout.Pattern -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; - using System.IO; - using System.Text; +using System; +using System.Text; +using System.IO; - using log4net.Core; +using log4net.Core; - /// - /// Converter to include event user name. - /// - /// Douglas de la Torre. - /// Nicko Cadell. - internal sealed class UserNamePatternConverter : PatternLayoutConverter - { - /// - /// Convert the pattern to the rendered message. - /// - /// that will receive the formatted result. - /// the event being logged. - protected override void Convert(TextWriter writer, LoggingEvent loggingEvent) - { - writer.Write(loggingEvent.UserName); - } - } -} +namespace log4net.Layout.Pattern +{ + /// + /// Converter to include event user name + /// + /// Douglas de la Torre + /// Nicko Cadell + internal sealed class UserNamePatternConverter : PatternLayoutConverter + { + /// + /// Convert the pattern to the rendered message + /// + /// that will receive the formatted result. + /// the event being logged + protected override void Convert(TextWriter writer, LoggingEvent loggingEvent) + { + writer.Write(loggingEvent.UserName); + } + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/UtcDatePatternConverter.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/UtcDatePatternConverter.cs index b40f978b4ae..51f710dcacb 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/UtcDatePatternConverter.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/Pattern/UtcDatePatternConverter.cs @@ -1,88 +1,88 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.Layout.Pattern -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; - using System.IO; - using System.Text; +using System; +using System.Text; +using System.IO; - using log4net.Core; - using log4net.DateFormatter; - using log4net.Util; +using log4net.Core; +using log4net.Util; +using log4net.DateFormatter; - /// - /// Write the TimeStamp to the output. - /// - /// - /// - /// Date pattern converter, uses a to format - /// the date of a . - /// - /// - /// Uses a to format the - /// in Universal time. - /// - /// - /// See the for details on the date pattern syntax. - /// - /// - /// - /// Nicko Cadell. - internal class UtcDatePatternConverter : DatePatternConverter - { - /// - /// Write the TimeStamp to the output. - /// - /// that will receive the formatted result. - /// the event being logged. - /// - /// - /// Pass the to the - /// for it to render it to the writer. - /// - /// - /// The passed is in the local time zone, this is converted - /// to Universal time before it is rendered. - /// - /// - /// - protected override void Convert(TextWriter writer, LoggingEvent loggingEvent) - { - try - { - this.m_dateFormatter.FormatDate(loggingEvent.TimeStampUtc, writer); - } - catch (Exception ex) - { - LogLog.Error(declaringType, "Error occurred while converting date.", ex); - } +namespace log4net.Layout.Pattern +{ + /// + /// Write the TimeStamp to the output + /// + /// + /// + /// Date pattern converter, uses a to format + /// the date of a . + /// + /// + /// Uses a to format the + /// in Universal time. + /// + /// + /// See the for details on the date pattern syntax. + /// + /// + /// + /// Nicko Cadell + internal class UtcDatePatternConverter : DatePatternConverter + { + /// + /// Write the TimeStamp to the output + /// + /// that will receive the formatted result. + /// the event being logged + /// + /// + /// Pass the to the + /// for it to render it to the writer. + /// + /// + /// The passed is in the local time zone, this is converted + /// to Universal time before it is rendered. + /// + /// + /// + protected override void Convert(TextWriter writer, LoggingEvent loggingEvent) + { + try + { + this.m_dateFormatter.FormatDate(loggingEvent.TimeStampUtc, writer); + } + catch (Exception ex) + { + LogLog.Error(declaringType, "Error occurred while converting date.", ex); + } } - /// - /// The fully qualified type of the UtcDatePatternConverter class. - /// - /// - /// Used by the internal logger to record the Type of the - /// log message. - /// + /// + /// The fully qualified type of the UtcDatePatternConverter class. + /// + /// + /// Used by the internal logger to record the Type of the + /// log message. + /// private static readonly Type declaringType = typeof(UtcDatePatternConverter); - } -} + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/PatternLayout.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/PatternLayout.cs index cec1ccf6230..bfdaae8591a 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/PatternLayout.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/PatternLayout.cs @@ -1,1151 +1,1139 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -#if NETSTANDARD1_3 -using System.Reflection; -#endif - -using log4net.Core; -using log4net.Layout.Pattern; -using log4net.Util; -using log4net.Util.PatternStringConverters; +using System; +using System.Collections; +using System.IO; -using AppDomainPatternConverter = log4net.Layout.Pattern.AppDomainPatternConverter; -using DatePatternConverter = log4net.Layout.Pattern.DatePatternConverter; -using IdentityPatternConverter = log4net.Layout.Pattern.IdentityPatternConverter; -using PropertyPatternConverter = log4net.Layout.Pattern.PropertyPatternConverter; -using UserNamePatternConverter = log4net.Layout.Pattern.UserNamePatternConverter; -using UtcDatePatternConverter = log4net.Layout.Pattern.UtcDatePatternConverter; - -namespace log4net.Layout -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; - using System.Collections; - using System.IO; +using log4net.Core; +using log4net.Layout.Pattern; +using log4net.Util; +using log4net.Util.PatternStringConverters; +using AppDomainPatternConverter = log4net.Layout.Pattern.AppDomainPatternConverter; +using DatePatternConverter = log4net.Layout.Pattern.DatePatternConverter; +using IdentityPatternConverter = log4net.Layout.Pattern.IdentityPatternConverter; +using PropertyPatternConverter = log4net.Layout.Pattern.PropertyPatternConverter; +using UserNamePatternConverter = log4net.Layout.Pattern.UserNamePatternConverter; +using UtcDatePatternConverter = log4net.Layout.Pattern.UtcDatePatternConverter; - /// - /// A flexible layout configurable with pattern string. - /// - /// - /// - /// The goal of this class is to a - /// as a string. The results - /// depend on the conversion pattern. - /// - /// - /// The conversion pattern is closely related to the conversion - /// pattern of the printf function in C. A conversion pattern is - /// composed of literal text and format control expressions called - /// conversion specifiers. - /// - /// - /// You are free to insert any literal text within the conversion - /// pattern. - /// - /// - /// Each conversion specifier starts with a percent sign (%) and is - /// followed by optional format modifiers and a conversion - /// pattern name. The conversion pattern name specifies the type of - /// data, e.g. logger, level, date, thread name. The format - /// modifiers control such things as field width, padding, left and - /// right justification. The following is a simple example. - /// - /// - /// Let the conversion pattern be "%-5level [%thread]: %message%newline" and assume - /// that the log4net environment was set to use a PatternLayout. Then the - /// statements. - /// - /// - /// ILog log = LogManager.GetLogger(typeof(TestApp)); - /// log.Debug("Message 1"); - /// log.Warn("Message 2"); - /// - /// would yield the output. - /// - /// DEBUG [main]: Message 1 - /// WARN [main]: Message 2 - /// - /// - /// Note that there is no explicit separator between text and - /// conversion specifiers. The pattern parser knows when it has reached - /// the end of a conversion specifier when it reads a conversion - /// character. In the example above the conversion specifier - /// %-5level means the level of the logging event should be left - /// justified to a width of five characters. - /// - /// - /// The recognized conversion pattern names are: - /// - /// - /// - /// Conversion Pattern Name - /// Effect - /// - /// - /// a - /// Equivalent to appdomain - /// - /// - /// appdomain - /// - /// Used to output the friendly name of the AppDomain where the - /// logging event was generated. - /// - /// - /// - /// aspnet-cache - /// - /// - /// Used to output all cache items in the case of %aspnet-cache or just one named item if used as %aspnet-cache{key} - /// - /// - /// This pattern is not available for Compact Framework or Client Profile assemblies. - /// - /// - /// - /// - /// aspnet-context - /// - /// - /// Used to output all context items in the case of %aspnet-context or just one named item if used as %aspnet-context{key} - /// - /// - /// This pattern is not available for Compact Framework or Client Profile assemblies. - /// - /// - /// - /// - /// aspnet-request - /// - /// - /// Used to output all request parameters in the case of %aspnet-request or just one named param if used as %aspnet-request{key} - /// - /// - /// This pattern is not available for Compact Framework or Client Profile assemblies. - /// - /// - /// - /// - /// aspnet-session - /// - /// - /// Used to output all session items in the case of %aspnet-session or just one named item if used as %aspnet-session{key} - /// - /// - /// This pattern is not available for Compact Framework or Client Profile assemblies. - /// - /// - /// - /// - /// c - /// Equivalent to logger - /// - /// - /// C - /// Equivalent to type - /// - /// - /// class - /// Equivalent to type - /// - /// - /// d - /// Equivalent to date - /// - /// - /// date - /// - /// - /// Used to output the date of the logging event in the local time zone. - /// To output the date in universal time use the %utcdate pattern. - /// The date conversion - /// specifier may be followed by a date format specifier enclosed - /// between braces. For example, %date{HH:mm:ss,fff} or - /// %date{dd MMM yyyy HH:mm:ss,fff}. If no date format specifier is - /// given then ISO8601 format is - /// assumed (). - /// - /// - /// The date format specifier admits the same syntax as the - /// time pattern string of the . - /// - /// - /// For better results it is recommended to use the log4net date - /// formatters. These can be specified using one of the strings - /// "ABSOLUTE", "DATE" and "ISO8601" for specifying - /// , - /// and respectively - /// . For example, - /// %date{ISO8601} or %date{ABSOLUTE}. - /// - /// - /// These dedicated date formatters perform significantly - /// better than . - /// - /// - /// - /// - /// exception - /// - /// - /// Used to output the exception passed in with the log message. - /// - /// - /// If an exception object is stored in the logging event - /// it will be rendered into the pattern output with a - /// trailing newline. - /// If there is no exception then nothing will be output - /// and no trailing newline will be appended. - /// It is typical to put a newline before the exception - /// and to have the exception as the last data in the pattern. - /// - /// - /// - /// - /// F - /// Equivalent to file - /// - /// - /// file - /// - /// - /// Used to output the file name where the logging request was - /// issued. - /// - /// - /// WARNING Generating caller location information is - /// extremely slow. Its use should be avoided unless execution speed - /// is not an issue. - /// - /// - /// See the note below on the availability of caller location information. - /// - /// - /// - /// - /// identity - /// - /// - /// Used to output the user name for the currently active user - /// (Principal.Identity.Name). - /// - /// - /// WARNING Generating caller information is - /// extremely slow. Its use should be avoided unless execution speed - /// is not an issue. - /// - /// - /// - /// - /// l - /// Equivalent to location - /// - /// - /// L - /// Equivalent to line - /// - /// - /// location - /// - /// - /// Used to output location information of the caller which generated - /// the logging event. - /// - /// - /// The location information depends on the CLI implementation but - /// usually consists of the fully qualified name of the calling - /// method followed by the callers source the file name and line - /// number between parentheses. - /// - /// - /// The location information can be very useful. However, its - /// generation is extremely slow. Its use should be avoided - /// unless execution speed is not an issue. - /// - /// - /// See the note below on the availability of caller location information. - /// - /// - /// - /// - /// level - /// - /// - /// Used to output the level of the logging event. - /// - /// - /// - /// - /// line - /// - /// - /// Used to output the line number from where the logging request - /// was issued. - /// - /// - /// WARNING Generating caller location information is - /// extremely slow. Its use should be avoided unless execution speed - /// is not an issue. - /// - /// - /// See the note below on the availability of caller location information. - /// - /// - /// - /// - /// logger - /// - /// - /// Used to output the logger of the logging event. The - /// logger conversion specifier can be optionally followed by - /// precision specifier, that is a decimal constant in - /// brackets. - /// - /// - /// If a precision specifier is given, then only the corresponding - /// number of right most components of the logger name will be - /// printed. By default the logger name is printed in full. - /// - /// - /// For example, for the logger name "a.b.c" the pattern - /// %logger{2} will output "b.c". - /// - /// - /// - /// - /// m - /// Equivalent to message - /// - /// - /// M - /// Equivalent to method - /// - /// - /// message - /// - /// - /// Used to output the application supplied message associated with - /// the logging event. - /// - /// - /// - /// - /// mdc - /// - /// - /// The MDC (old name for the ThreadContext.Properties) is now part of the - /// combined event properties. This pattern is supported for compatibility - /// but is equivalent to property. - /// - /// - /// - /// - /// method - /// - /// - /// Used to output the method name where the logging request was - /// issued. - /// - /// - /// WARNING Generating caller location information is - /// extremely slow. Its use should be avoided unless execution speed - /// is not an issue. - /// - /// - /// See the note below on the availability of caller location information. - /// - /// - /// - /// - /// n - /// Equivalent to newline - /// - /// - /// newline - /// - /// - /// Outputs the platform dependent line separator character or - /// characters. - /// - /// - /// This conversion pattern offers the same performance as using - /// non-portable line separator strings such as "\n", or "\r\n". - /// Thus, it is the preferred way of specifying a line separator. - /// - /// - /// - /// - /// ndc - /// - /// - /// Used to output the NDC (nested diagnostic context) associated - /// with the thread that generated the logging event. - /// - /// - /// - /// - /// p - /// Equivalent to level - /// - /// - /// P - /// Equivalent to property - /// - /// - /// properties - /// Equivalent to property - /// - /// - /// property - /// - /// - /// Used to output the an event specific property. The key to - /// lookup must be specified within braces and directly following the - /// pattern specifier, e.g. %property{user} would include the value - /// from the property that is keyed by the string 'user'. Each property value - /// that is to be included in the log must be specified separately. - /// Properties are added to events by loggers or appenders. By default - /// the log4net:HostName property is set to the name of machine on - /// which the event was originally logged. - /// - /// - /// If no key is specified, e.g. %property then all the keys and their - /// values are printed in a comma separated list. - /// - /// - /// The properties of an event are combined from a number of different - /// contexts. These are listed below in the order in which they are searched. - /// - /// - /// - /// the event properties - /// - /// The event has that can be set. These - /// properties are specific to this event only. - /// - /// - /// - /// the thread properties - /// - /// The that are set on the current - /// thread. These properties are shared by all events logged on this thread. - /// - /// - /// - /// the global properties - /// - /// The that are set globally. These - /// properties are shared by all the threads in the AppDomain. - /// - /// - /// - /// - /// - /// - /// - /// r - /// Equivalent to timestamp - /// - /// - /// stacktrace - /// - /// - /// Used to output the stack trace of the logging event - /// The stack trace level specifier may be enclosed - /// between braces. For example, %stacktrace{level}. - /// If no stack trace level specifier is given then 1 is assumed - /// - /// - /// Output uses the format: - /// type3.MethodCall3 > type2.MethodCall2 > type1.MethodCall1 - /// - /// - /// This pattern is not available for Compact Framework assemblies. - /// - /// - /// - /// - /// stacktracedetail - /// - /// - /// Used to output the stack trace of the logging event - /// The stack trace level specifier may be enclosed - /// between braces. For example, %stacktracedetail{level}. - /// If no stack trace level specifier is given then 1 is assumed - /// - /// - /// Output uses the format: - /// type3.MethodCall3(type param,...) > type2.MethodCall2(type param,...) > type1.MethodCall1(type param,...) - /// - /// - /// This pattern is not available for Compact Framework assemblies. - /// - /// - /// - /// - /// t - /// Equivalent to thread - /// - /// - /// timestamp - /// - /// - /// Used to output the number of milliseconds elapsed since the start - /// of the application until the creation of the logging event. - /// - /// - /// - /// - /// thread - /// - /// - /// Used to output the name of the thread that generated the - /// logging event. Uses the thread number if no name is available. - /// - /// - /// - /// - /// type - /// - /// - /// Used to output the fully qualified type name of the caller - /// issuing the logging request. This conversion specifier - /// can be optionally followed by precision specifier, that - /// is a decimal constant in brackets. - /// - /// - /// If a precision specifier is given, then only the corresponding - /// number of right most components of the class name will be - /// printed. By default the class name is output in fully qualified form. - /// - /// - /// For example, for the class name "log4net.Layout.PatternLayout", the - /// pattern %type{1} will output "PatternLayout". - /// - /// - /// WARNING Generating the caller class information is - /// slow. Thus, its use should be avoided unless execution speed is - /// not an issue. - /// - /// - /// See the note below on the availability of caller location information. - /// - /// - /// - /// - /// u - /// Equivalent to identity - /// - /// - /// username - /// - /// - /// Used to output the WindowsIdentity for the currently - /// active user. - /// - /// - /// WARNING Generating caller WindowsIdentity information is - /// extremely slow. Its use should be avoided unless execution speed - /// is not an issue. - /// - /// - /// - /// - /// utcdate - /// - /// - /// Used to output the date of the logging event in universal time. - /// The date conversion - /// specifier may be followed by a date format specifier enclosed - /// between braces. For example, %utcdate{HH:mm:ss,fff} or - /// %utcdate{dd MMM yyyy HH:mm:ss,fff}. If no date format specifier is - /// given then ISO8601 format is - /// assumed (). - /// - /// - /// The date format specifier admits the same syntax as the - /// time pattern string of the . - /// - /// - /// For better results it is recommended to use the log4net date - /// formatters. These can be specified using one of the strings - /// "ABSOLUTE", "DATE" and "ISO8601" for specifying - /// , - /// and respectively - /// . For example, - /// %utcdate{ISO8601} or %utcdate{ABSOLUTE}. - /// - /// - /// These dedicated date formatters perform significantly - /// better than . - /// - /// - /// - /// - /// w - /// Equivalent to username - /// - /// - /// x - /// Equivalent to ndc - /// - /// - /// X - /// Equivalent to mdc - /// - /// - /// % - /// - /// - /// The sequence %% outputs a single percent sign. - /// - /// - /// - /// - /// - /// The single letter patterns are deprecated in favor of the - /// longer more descriptive pattern names. - /// - /// - /// By default the relevant information is output as is. However, - /// with the aid of format modifiers it is possible to change the - /// minimum field width, the maximum field width and justification. - /// - /// - /// The optional format modifier is placed between the percent sign - /// and the conversion pattern name. - /// - /// - /// The first optional format modifier is the left justification - /// flag which is just the minus (-) character. Then comes the - /// optional minimum field width modifier. This is a decimal - /// constant that represents the minimum number of characters to - /// output. If the data item requires fewer characters, it is padded on - /// either the left or the right until the minimum width is - /// reached. The default is to pad on the left (right justify) but you - /// can specify right padding with the left justification flag. The - /// padding character is space. If the data item is larger than the - /// minimum field width, the field is expanded to accommodate the - /// data. The value is never truncated. - /// - /// - /// This behavior can be changed using the maximum field - /// width modifier which is designated by a period followed by a - /// decimal constant. If the data item is longer than the maximum - /// field, then the extra characters are removed from the - /// beginning of the data item and not from the end. For - /// example, it the maximum field width is eight and the data item is - /// ten characters long, then the first two characters of the data item - /// are dropped. This behavior deviates from the printf function in C - /// where truncation is done from the end. - /// - /// - /// Below are various format modifier examples for the logger - /// conversion specifier. - /// - ///
- /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - ///
Format modifierleft justifyminimum widthmaximum widthcomment
%20loggerfalse20none - /// - /// Left pad with spaces if the logger name is less than 20 - /// characters long. - /// - ///
%-20loggertrue20none - /// - /// Right pad with spaces if the logger - /// name is less than 20 characters long. - /// - ///
%.30loggerNAnone30 - /// - /// Truncate from the beginning if the logger - /// name is longer than 30 characters. - /// - ///
%20.30loggerfalse2030 - /// - /// Left pad with spaces if the logger name is shorter than 20 - /// characters. However, if logger name is longer than 30 characters, - /// then truncate from the beginning. - /// - ///
%-20.30loggertrue2030 - /// - /// Right pad with spaces if the logger name is shorter than 20 - /// characters. However, if logger name is longer than 30 characters, - /// then truncate from the beginning. - /// - ///
- ///
- /// - /// Note about caller location information.
- /// The following patterns %type %file %line %method %location %class %C %F %L %l %M - /// all generate caller location information. - /// Location information uses the System.Diagnostics.StackTrace class to generate - /// a call stack. The caller's information is then extracted from this stack. - ///
- /// - /// - /// The System.Diagnostics.StackTrace class is not supported on the - /// .NET Compact Framework 1.0 therefore caller location information is not - /// available on that framework. - /// - /// - /// - /// - /// The System.Diagnostics.StackTrace class has this to say about Release builds: - /// - /// - /// "StackTrace information will be most informative with Debug build configurations. - /// By default, Debug builds include debug symbols, while Release builds do not. The - /// debug symbols contain most of the file, method name, line number, and column - /// information used in constructing StackFrame and StackTrace objects. StackTrace - /// might not report as many method calls as expected, due to code transformations - /// that occur during optimization.". - /// - /// - /// This means that in a Release build the caller information may be incomplete or may - /// not exist at all! Therefore caller location information cannot be relied upon in a Release build. - /// - /// - /// - /// Additional pattern converters may be registered with a specific - /// instance using the method. - /// - ///
- /// - /// This is a more detailed pattern. - /// %timestamp [%thread] %level %logger %ndc - %message%newline - /// - /// - /// A similar pattern except that the relative time is - /// right padded if less than 6 digits, thread name is right padded if - /// less than 15 characters and truncated if longer and the logger - /// name is left padded if shorter than 30 characters and truncated if - /// longer. - /// %-6timestamp [%15.15thread] %-5level %30.30logger %ndc - %message%newline - /// - /// Nicko Cadell. - /// Gert Driesen. - /// Douglas de la Torre. - /// Daniel Cazzulino. - public class PatternLayout : LayoutSkeleton +namespace log4net.Layout +{ + /// + /// A flexible layout configurable with pattern string. + /// + /// + /// + /// The goal of this class is to a + /// as a string. The results + /// depend on the conversion pattern. + /// + /// + /// The conversion pattern is closely related to the conversion + /// pattern of the printf function in C. A conversion pattern is + /// composed of literal text and format control expressions called + /// conversion specifiers. + /// + /// + /// You are free to insert any literal text within the conversion + /// pattern. + /// + /// + /// Each conversion specifier starts with a percent sign (%) and is + /// followed by optional format modifiers and a conversion + /// pattern name. The conversion pattern name specifies the type of + /// data, e.g. logger, level, date, thread name. The format + /// modifiers control such things as field width, padding, left and + /// right justification. The following is a simple example. + /// + /// + /// Let the conversion pattern be "%-5level [%thread]: %message%newline" and assume + /// that the log4net environment was set to use a PatternLayout. Then the + /// statements + /// + /// + /// ILog log = LogManager.GetLogger(typeof(TestApp)); + /// log.Debug("Message 1"); + /// log.Warn("Message 2"); + /// + /// would yield the output + /// + /// DEBUG [main]: Message 1 + /// WARN [main]: Message 2 + /// + /// + /// Note that there is no explicit separator between text and + /// conversion specifiers. The pattern parser knows when it has reached + /// the end of a conversion specifier when it reads a conversion + /// character. In the example above the conversion specifier + /// %-5level means the level of the logging event should be left + /// justified to a width of five characters. + /// + /// + /// The recognized conversion pattern names are: + /// + /// + /// + /// Conversion Pattern Name + /// Effect + /// + /// + /// a + /// Equivalent to appdomain + /// + /// + /// appdomain + /// + /// Used to output the friendly name of the AppDomain where the + /// logging event was generated. + /// + /// + /// + /// aspnet-cache + /// + /// + /// Used to output all cache items in the case of %aspnet-cache or just one named item if used as %aspnet-cache{key} + /// + /// + /// This pattern is not available for Compact Framework or Client Profile assemblies. + /// + /// + /// + /// + /// aspnet-context + /// + /// + /// Used to output all context items in the case of %aspnet-context or just one named item if used as %aspnet-context{key} + /// + /// + /// This pattern is not available for Compact Framework or Client Profile assemblies. + /// + /// + /// + /// + /// aspnet-request + /// + /// + /// Used to output all request parameters in the case of %aspnet-request or just one named param if used as %aspnet-request{key} + /// + /// + /// This pattern is not available for Compact Framework or Client Profile assemblies. + /// + /// + /// + /// + /// aspnet-session + /// + /// + /// Used to output all session items in the case of %aspnet-session or just one named item if used as %aspnet-session{key} + /// + /// + /// This pattern is not available for Compact Framework or Client Profile assemblies. + /// + /// + /// + /// + /// c + /// Equivalent to logger + /// + /// + /// C + /// Equivalent to type + /// + /// + /// class + /// Equivalent to type + /// + /// + /// d + /// Equivalent to date + /// + /// + /// date + /// + /// + /// Used to output the date of the logging event in the local time zone. + /// To output the date in universal time use the %utcdate pattern. + /// The date conversion + /// specifier may be followed by a date format specifier enclosed + /// between braces. For example, %date{HH:mm:ss,fff} or + /// %date{dd MMM yyyy HH:mm:ss,fff}. If no date format specifier is + /// given then ISO8601 format is + /// assumed (). + /// + /// + /// The date format specifier admits the same syntax as the + /// time pattern string of the . + /// + /// + /// For better results it is recommended to use the log4net date + /// formatters. These can be specified using one of the strings + /// "ABSOLUTE", "DATE" and "ISO8601" for specifying + /// , + /// and respectively + /// . For example, + /// %date{ISO8601} or %date{ABSOLUTE}. + /// + /// + /// These dedicated date formatters perform significantly + /// better than . + /// + /// + /// + /// + /// exception + /// + /// + /// Used to output the exception passed in with the log message. + /// + /// + /// If an exception object is stored in the logging event + /// it will be rendered into the pattern output with a + /// trailing newline. + /// If there is no exception then nothing will be output + /// and no trailing newline will be appended. + /// It is typical to put a newline before the exception + /// and to have the exception as the last data in the pattern. + /// + /// + /// + /// + /// F + /// Equivalent to file + /// + /// + /// file + /// + /// + /// Used to output the file name where the logging request was + /// issued. + /// + /// + /// WARNING Generating caller location information is + /// extremely slow. Its use should be avoided unless execution speed + /// is not an issue. + /// + /// + /// See the note below on the availability of caller location information. + /// + /// + /// + /// + /// identity + /// + /// + /// Used to output the user name for the currently active user + /// (Principal.Identity.Name). + /// + /// + /// WARNING Generating caller information is + /// extremely slow. Its use should be avoided unless execution speed + /// is not an issue. + /// + /// + /// + /// + /// l + /// Equivalent to location + /// + /// + /// L + /// Equivalent to line + /// + /// + /// location + /// + /// + /// Used to output location information of the caller which generated + /// the logging event. + /// + /// + /// The location information depends on the CLI implementation but + /// usually consists of the fully qualified name of the calling + /// method followed by the callers source the file name and line + /// number between parentheses. + /// + /// + /// The location information can be very useful. However, its + /// generation is extremely slow. Its use should be avoided + /// unless execution speed is not an issue. + /// + /// + /// See the note below on the availability of caller location information. + /// + /// + /// + /// + /// level + /// + /// + /// Used to output the level of the logging event. + /// + /// + /// + /// + /// line + /// + /// + /// Used to output the line number from where the logging request + /// was issued. + /// + /// + /// WARNING Generating caller location information is + /// extremely slow. Its use should be avoided unless execution speed + /// is not an issue. + /// + /// + /// See the note below on the availability of caller location information. + /// + /// + /// + /// + /// logger + /// + /// + /// Used to output the logger of the logging event. The + /// logger conversion specifier can be optionally followed by + /// precision specifier, that is a decimal constant in + /// brackets. + /// + /// + /// If a precision specifier is given, then only the corresponding + /// number of right most components of the logger name will be + /// printed. By default the logger name is printed in full. + /// + /// + /// For example, for the logger name "a.b.c" the pattern + /// %logger{2} will output "b.c". + /// + /// + /// + /// + /// m + /// Equivalent to message + /// + /// + /// M + /// Equivalent to method + /// + /// + /// message + /// + /// + /// Used to output the application supplied message associated with + /// the logging event. + /// + /// + /// + /// + /// mdc + /// + /// + /// The MDC (old name for the ThreadContext.Properties) is now part of the + /// combined event properties. This pattern is supported for compatibility + /// but is equivalent to property. + /// + /// + /// + /// + /// method + /// + /// + /// Used to output the method name where the logging request was + /// issued. + /// + /// + /// WARNING Generating caller location information is + /// extremely slow. Its use should be avoided unless execution speed + /// is not an issue. + /// + /// + /// See the note below on the availability of caller location information. + /// + /// + /// + /// + /// n + /// Equivalent to newline + /// + /// + /// newline + /// + /// + /// Outputs the platform dependent line separator character or + /// characters. + /// + /// + /// This conversion pattern offers the same performance as using + /// non-portable line separator strings such as "\n", or "\r\n". + /// Thus, it is the preferred way of specifying a line separator. + /// + /// + /// + /// + /// ndc + /// + /// + /// Used to output the NDC (nested diagnostic context) associated + /// with the thread that generated the logging event. + /// + /// + /// + /// + /// p + /// Equivalent to level + /// + /// + /// P + /// Equivalent to property + /// + /// + /// properties + /// Equivalent to property + /// + /// + /// property + /// + /// + /// Used to output the an event specific property. The key to + /// lookup must be specified within braces and directly following the + /// pattern specifier, e.g. %property{user} would include the value + /// from the property that is keyed by the string 'user'. Each property value + /// that is to be included in the log must be specified separately. + /// Properties are added to events by loggers or appenders. By default + /// the log4net:HostName property is set to the name of machine on + /// which the event was originally logged. + /// + /// + /// If no key is specified, e.g. %property then all the keys and their + /// values are printed in a comma separated list. + /// + /// + /// The properties of an event are combined from a number of different + /// contexts. These are listed below in the order in which they are searched. + /// + /// + /// + /// the event properties + /// + /// The event has that can be set. These + /// properties are specific to this event only. + /// + /// + /// + /// the thread properties + /// + /// The that are set on the current + /// thread. These properties are shared by all events logged on this thread. + /// + /// + /// + /// the global properties + /// + /// The that are set globally. These + /// properties are shared by all the threads in the AppDomain. + /// + /// + /// + /// + /// + /// + /// + /// r + /// Equivalent to timestamp + /// + /// + /// stacktrace + /// + /// + /// Used to output the stack trace of the logging event + /// The stack trace level specifier may be enclosed + /// between braces. For example, %stacktrace{level}. + /// If no stack trace level specifier is given then 1 is assumed + /// + /// + /// Output uses the format: + /// type3.MethodCall3 > type2.MethodCall2 > type1.MethodCall1 + /// + /// + /// This pattern is not available for Compact Framework assemblies. + /// + /// + /// + /// + /// stacktracedetail + /// + /// + /// Used to output the stack trace of the logging event + /// The stack trace level specifier may be enclosed + /// between braces. For example, %stacktracedetail{level}. + /// If no stack trace level specifier is given then 1 is assumed + /// + /// + /// Output uses the format: + /// type3.MethodCall3(type param,...) > type2.MethodCall2(type param,...) > type1.MethodCall1(type param,...) + /// + /// + /// This pattern is not available for Compact Framework assemblies. + /// + /// + /// + /// + /// t + /// Equivalent to thread + /// + /// + /// timestamp + /// + /// + /// Used to output the number of milliseconds elapsed since the start + /// of the application until the creation of the logging event. + /// + /// + /// + /// + /// thread + /// + /// + /// Used to output the name of the thread that generated the + /// logging event. Uses the thread number if no name is available. + /// + /// + /// + /// + /// type + /// + /// + /// Used to output the fully qualified type name of the caller + /// issuing the logging request. This conversion specifier + /// can be optionally followed by precision specifier, that + /// is a decimal constant in brackets. + /// + /// + /// If a precision specifier is given, then only the corresponding + /// number of right most components of the class name will be + /// printed. By default the class name is output in fully qualified form. + /// + /// + /// For example, for the class name "log4net.Layout.PatternLayout", the + /// pattern %type{1} will output "PatternLayout". + /// + /// + /// WARNING Generating the caller class information is + /// slow. Thus, its use should be avoided unless execution speed is + /// not an issue. + /// + /// + /// See the note below on the availability of caller location information. + /// + /// + /// + /// + /// u + /// Equivalent to identity + /// + /// + /// username + /// + /// + /// Used to output the WindowsIdentity for the currently + /// active user. + /// + /// + /// WARNING Generating caller WindowsIdentity information is + /// extremely slow. Its use should be avoided unless execution speed + /// is not an issue. + /// + /// + /// + /// + /// utcdate + /// + /// + /// Used to output the date of the logging event in universal time. + /// The date conversion + /// specifier may be followed by a date format specifier enclosed + /// between braces. For example, %utcdate{HH:mm:ss,fff} or + /// %utcdate{dd MMM yyyy HH:mm:ss,fff}. If no date format specifier is + /// given then ISO8601 format is + /// assumed (). + /// + /// + /// The date format specifier admits the same syntax as the + /// time pattern string of the . + /// + /// + /// For better results it is recommended to use the log4net date + /// formatters. These can be specified using one of the strings + /// "ABSOLUTE", "DATE" and "ISO8601" for specifying + /// , + /// and respectively + /// . For example, + /// %utcdate{ISO8601} or %utcdate{ABSOLUTE}. + /// + /// + /// These dedicated date formatters perform significantly + /// better than . + /// + /// + /// + /// + /// w + /// Equivalent to username + /// + /// + /// x + /// Equivalent to ndc + /// + /// + /// X + /// Equivalent to mdc + /// + /// + /// % + /// + /// + /// The sequence %% outputs a single percent sign. + /// + /// + /// + /// + /// + /// The single letter patterns are deprecated in favor of the + /// longer more descriptive pattern names. + /// + /// + /// By default the relevant information is output as is. However, + /// with the aid of format modifiers it is possible to change the + /// minimum field width, the maximum field width and justification. + /// + /// + /// The optional format modifier is placed between the percent sign + /// and the conversion pattern name. + /// + /// + /// The first optional format modifier is the left justification + /// flag which is just the minus (-) character. Then comes the + /// optional minimum field width modifier. This is a decimal + /// constant that represents the minimum number of characters to + /// output. If the data item requires fewer characters, it is padded on + /// either the left or the right until the minimum width is + /// reached. The default is to pad on the left (right justify) but you + /// can specify right padding with the left justification flag. The + /// padding character is space. If the data item is larger than the + /// minimum field width, the field is expanded to accommodate the + /// data. The value is never truncated. + /// + /// + /// This behavior can be changed using the maximum field + /// width modifier which is designated by a period followed by a + /// decimal constant. If the data item is longer than the maximum + /// field, then the extra characters are removed from the + /// beginning of the data item and not from the end. For + /// example, it the maximum field width is eight and the data item is + /// ten characters long, then the first two characters of the data item + /// are dropped. This behavior deviates from the printf function in C + /// where truncation is done from the end. + /// + /// + /// Below are various format modifier examples for the logger + /// conversion specifier. + /// + ///
+ /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + ///
Format modifierleft justifyminimum widthmaximum widthcomment
%20loggerfalse20none + /// + /// Left pad with spaces if the logger name is less than 20 + /// characters long. + /// + ///
%-20loggertrue20none + /// + /// Right pad with spaces if the logger + /// name is less than 20 characters long. + /// + ///
%.30loggerNAnone30 + /// + /// Truncate from the beginning if the logger + /// name is longer than 30 characters. + /// + ///
%20.30loggerfalse2030 + /// + /// Left pad with spaces if the logger name is shorter than 20 + /// characters. However, if logger name is longer than 30 characters, + /// then truncate from the beginning. + /// + ///
%-20.30loggertrue2030 + /// + /// Right pad with spaces if the logger name is shorter than 20 + /// characters. However, if logger name is longer than 30 characters, + /// then truncate from the beginning. + /// + ///
+ ///
+ /// + /// Note about caller location information.
+ /// The following patterns %type %file %line %method %location %class %C %F %L %l %M + /// all generate caller location information. + /// Location information uses the System.Diagnostics.StackTrace class to generate + /// a call stack. The caller's information is then extracted from this stack. + ///
+ /// + /// + /// The System.Diagnostics.StackTrace class is not supported on the + /// .NET Compact Framework 1.0 therefore caller location information is not + /// available on that framework. + /// + /// + /// + /// + /// The System.Diagnostics.StackTrace class has this to say about Release builds: + /// + /// + /// "StackTrace information will be most informative with Debug build configurations. + /// By default, Debug builds include debug symbols, while Release builds do not. The + /// debug symbols contain most of the file, method name, line number, and column + /// information used in constructing StackFrame and StackTrace objects. StackTrace + /// might not report as many method calls as expected, due to code transformations + /// that occur during optimization." + /// + /// + /// This means that in a Release build the caller information may be incomplete or may + /// not exist at all! Therefore caller location information cannot be relied upon in a Release build. + /// + /// + /// + /// Additional pattern converters may be registered with a specific + /// instance using the method. + /// + ///
+ /// + /// This is a more detailed pattern. + /// %timestamp [%thread] %level %logger %ndc - %message%newline + /// + /// + /// A similar pattern except that the relative time is + /// right padded if less than 6 digits, thread name is right padded if + /// less than 15 characters and truncated if longer and the logger + /// name is left padded if shorter than 30 characters and truncated if + /// longer. + /// %-6timestamp [%15.15thread] %-5level %30.30logger %ndc - %message%newline + /// + /// Nicko Cadell + /// Gert Driesen + /// Douglas de la Torre + /// Daniel Cazzulino + public class PatternLayout : LayoutSkeleton { - /// - /// Default pattern string for log output. - /// - /// - /// - /// Default pattern string for log output. - /// Currently set to the string "%message%newline" - /// which just prints the application supplied message. - /// - /// - public const string DefaultConversionPattern = "%message%newline"; - - /// - /// A detailed conversion pattern. - /// - /// - /// - /// A conversion pattern which includes Time, Thread, Logger, and Nested Context. - /// Current value is %timestamp [%thread] %level %logger %ndc - %message%newline. - /// - /// + /// + /// Default pattern string for log output. + /// + /// + /// + /// Default pattern string for log output. + /// Currently set to the string "%message%newline" + /// which just prints the application supplied message. + /// + /// + public const string DefaultConversionPattern ="%message%newline"; + + /// + /// A detailed conversion pattern + /// + /// + /// + /// A conversion pattern which includes Time, Thread, Logger, and Nested Context. + /// Current value is %timestamp [%thread] %level %logger %ndc - %message%newline. + /// + /// public const string DetailConversionPattern = "%timestamp [%thread] %level %logger %ndc - %message%newline"; - /// - /// Internal map of converter identifiers to converter types. - /// - /// - /// - /// This static map is overridden by the m_converterRegistry instance map. - /// - /// + /// + /// Internal map of converter identifiers to converter types. + /// + /// + /// + /// This static map is overridden by the m_converterRegistry instance map + /// + /// private static Hashtable s_globalRulesRegistry; - /// - /// the pattern. - /// - private string m_pattern; - - /// - /// the head of the pattern converter chain. - /// - private PatternConverter m_head; - - /// - /// patterns defined on this PatternLayout only. - /// + /// + /// the pattern + /// + private string m_pattern; + + /// + /// the head of the pattern converter chain + /// + private PatternConverter m_head; + + /// + /// patterns defined on this PatternLayout only + /// private Hashtable m_instanceRulesRegistry = new Hashtable(); /// - /// Initializes static members of the class. - /// Initialize the global registry. - /// - /// - /// - /// Defines the builtin global rules. - /// - /// - static PatternLayout() - { - s_globalRulesRegistry = new Hashtable(45); - - s_globalRulesRegistry.Add("literal", typeof(LiteralPatternConverter)); - s_globalRulesRegistry.Add("newline", typeof(NewLinePatternConverter)); + /// Initialize the global registry + /// + /// + /// + /// Defines the builtin global rules. + /// + /// + static PatternLayout() + { + s_globalRulesRegistry = new Hashtable(45); + + s_globalRulesRegistry.Add("literal", typeof(LiteralPatternConverter)); + s_globalRulesRegistry.Add("newline", typeof(NewLinePatternConverter)); s_globalRulesRegistry.Add("n", typeof(NewLinePatternConverter)); - // .NET Compact Framework 1.0 has no support for ASP.NET - // SSCLI 1.0 has no support for ASP.NET -#if !NETCF && !SSCLI && !CLIENT_PROFILE && !NETSTANDARD1_3 - s_globalRulesRegistry.Add("aspnet-cache", typeof(AspNetCachePatternConverter)); - s_globalRulesRegistry.Add("aspnet-context", typeof(AspNetContextPatternConverter)); - s_globalRulesRegistry.Add("aspnet-request", typeof(AspNetRequestPatternConverter)); - s_globalRulesRegistry.Add("aspnet-session", typeof(AspNetSessionPatternConverter)); -#endif - - s_globalRulesRegistry.Add("c", typeof(LoggerPatternConverter)); - s_globalRulesRegistry.Add("logger", typeof(LoggerPatternConverter)); - - s_globalRulesRegistry.Add("C", typeof(TypeNamePatternConverter)); - s_globalRulesRegistry.Add("class", typeof(TypeNamePatternConverter)); - s_globalRulesRegistry.Add("type", typeof(TypeNamePatternConverter)); - - s_globalRulesRegistry.Add("d", typeof(DatePatternConverter)); - s_globalRulesRegistry.Add("date", typeof(DatePatternConverter)); - - s_globalRulesRegistry.Add("exception", typeof(ExceptionPatternConverter)); - - s_globalRulesRegistry.Add("F", typeof(FileLocationPatternConverter)); - s_globalRulesRegistry.Add("file", typeof(FileLocationPatternConverter)); - - s_globalRulesRegistry.Add("l", typeof(FullLocationPatternConverter)); - s_globalRulesRegistry.Add("location", typeof(FullLocationPatternConverter)); - - s_globalRulesRegistry.Add("L", typeof(LineLocationPatternConverter)); - s_globalRulesRegistry.Add("line", typeof(LineLocationPatternConverter)); - - s_globalRulesRegistry.Add("m", typeof(MessagePatternConverter)); - s_globalRulesRegistry.Add("message", typeof(MessagePatternConverter)); - - s_globalRulesRegistry.Add("M", typeof(MethodLocationPatternConverter)); - s_globalRulesRegistry.Add("method", typeof(MethodLocationPatternConverter)); - - s_globalRulesRegistry.Add("p", typeof(LevelPatternConverter)); - s_globalRulesRegistry.Add("level", typeof(LevelPatternConverter)); - - s_globalRulesRegistry.Add("P", typeof(PropertyPatternConverter)); - s_globalRulesRegistry.Add("property", typeof(PropertyPatternConverter)); - s_globalRulesRegistry.Add("properties", typeof(PropertyPatternConverter)); - - s_globalRulesRegistry.Add("r", typeof(RelativeTimePatternConverter)); - s_globalRulesRegistry.Add("timestamp", typeof(RelativeTimePatternConverter)); - -#if !(NETCF || NETSTANDARD1_3) - s_globalRulesRegistry.Add("stacktrace", typeof(StackTracePatternConverter)); - s_globalRulesRegistry.Add("stacktracedetail", typeof(StackTraceDetailPatternConverter)); -#endif - - s_globalRulesRegistry.Add("t", typeof(ThreadPatternConverter)); - s_globalRulesRegistry.Add("thread", typeof(ThreadPatternConverter)); - - // For backwards compatibility the NDC patterns - s_globalRulesRegistry.Add("x", typeof(NdcPatternConverter)); - s_globalRulesRegistry.Add("ndc", typeof(NdcPatternConverter)); - - // For backwards compatibility the MDC patterns just do a property lookup - s_globalRulesRegistry.Add("X", typeof(PropertyPatternConverter)); - s_globalRulesRegistry.Add("mdc", typeof(PropertyPatternConverter)); - - s_globalRulesRegistry.Add("a", typeof(AppDomainPatternConverter)); - s_globalRulesRegistry.Add("appdomain", typeof(AppDomainPatternConverter)); - - s_globalRulesRegistry.Add("u", typeof(IdentityPatternConverter)); - s_globalRulesRegistry.Add("identity", typeof(IdentityPatternConverter)); - - s_globalRulesRegistry.Add("utcdate", typeof(UtcDatePatternConverter)); - s_globalRulesRegistry.Add("utcDate", typeof(UtcDatePatternConverter)); - s_globalRulesRegistry.Add("UtcDate", typeof(UtcDatePatternConverter)); - - s_globalRulesRegistry.Add("w", typeof(UserNamePatternConverter)); - s_globalRulesRegistry.Add("username", typeof(UserNamePatternConverter)); +// .NET Compact Framework 1.0 has no support for ASP.NET +// SSCLI 1.0 has no support for ASP.NET +#if !NETCF && !SSCLI && !CLIENT_PROFILE && !NETSTANDARD + s_globalRulesRegistry.Add("aspnet-cache", typeof(AspNetCachePatternConverter)); + s_globalRulesRegistry.Add("aspnet-context", typeof(AspNetContextPatternConverter)); + s_globalRulesRegistry.Add("aspnet-request", typeof(AspNetRequestPatternConverter)); + s_globalRulesRegistry.Add("aspnet-session", typeof(AspNetSessionPatternConverter)); +#endif + + s_globalRulesRegistry.Add("c", typeof(LoggerPatternConverter)); + s_globalRulesRegistry.Add("logger", typeof(LoggerPatternConverter)); + + s_globalRulesRegistry.Add("C", typeof(TypeNamePatternConverter)); + s_globalRulesRegistry.Add("class", typeof(TypeNamePatternConverter)); + s_globalRulesRegistry.Add("type", typeof(TypeNamePatternConverter)); + + s_globalRulesRegistry.Add("d", typeof(DatePatternConverter)); + s_globalRulesRegistry.Add("date", typeof(DatePatternConverter)); + + s_globalRulesRegistry.Add("exception", typeof(ExceptionPatternConverter)); + + s_globalRulesRegistry.Add("F", typeof(FileLocationPatternConverter)); + s_globalRulesRegistry.Add("file", typeof(FileLocationPatternConverter)); + + s_globalRulesRegistry.Add("l", typeof(FullLocationPatternConverter)); + s_globalRulesRegistry.Add("location", typeof(FullLocationPatternConverter)); + + s_globalRulesRegistry.Add("L", typeof(LineLocationPatternConverter)); + s_globalRulesRegistry.Add("line", typeof(LineLocationPatternConverter)); + + s_globalRulesRegistry.Add("m", typeof(MessagePatternConverter)); + s_globalRulesRegistry.Add("message", typeof(MessagePatternConverter)); + + s_globalRulesRegistry.Add("M", typeof(MethodLocationPatternConverter)); + s_globalRulesRegistry.Add("method", typeof(MethodLocationPatternConverter)); + + s_globalRulesRegistry.Add("p", typeof(LevelPatternConverter)); + s_globalRulesRegistry.Add("level", typeof(LevelPatternConverter)); + + s_globalRulesRegistry.Add("P", typeof(PropertyPatternConverter)); + s_globalRulesRegistry.Add("property", typeof(PropertyPatternConverter)); + s_globalRulesRegistry.Add("properties", typeof(PropertyPatternConverter)); + + s_globalRulesRegistry.Add("r", typeof(RelativeTimePatternConverter)); + s_globalRulesRegistry.Add("timestamp", typeof(RelativeTimePatternConverter)); + +#if !NETCF && !NETSTANDARD1_3 + s_globalRulesRegistry.Add("stacktrace", typeof(StackTracePatternConverter)); + s_globalRulesRegistry.Add("stacktracedetail", typeof(StackTraceDetailPatternConverter)); +#endif + + s_globalRulesRegistry.Add("t", typeof(ThreadPatternConverter)); + s_globalRulesRegistry.Add("thread", typeof(ThreadPatternConverter)); + + // For backwards compatibility the NDC patterns + s_globalRulesRegistry.Add("x", typeof(NdcPatternConverter)); + s_globalRulesRegistry.Add("ndc", typeof(NdcPatternConverter)); + + // For backwards compatibility the MDC patterns just do a property lookup + s_globalRulesRegistry.Add("X", typeof(PropertyPatternConverter)); + s_globalRulesRegistry.Add("mdc", typeof(PropertyPatternConverter)); + + s_globalRulesRegistry.Add("a", typeof(AppDomainPatternConverter)); + s_globalRulesRegistry.Add("appdomain", typeof(AppDomainPatternConverter)); + + s_globalRulesRegistry.Add("u", typeof(IdentityPatternConverter)); + s_globalRulesRegistry.Add("identity", typeof(IdentityPatternConverter)); + + s_globalRulesRegistry.Add("utcdate", typeof(UtcDatePatternConverter)); + s_globalRulesRegistry.Add("utcDate", typeof(UtcDatePatternConverter)); + s_globalRulesRegistry.Add("UtcDate", typeof(UtcDatePatternConverter)); + + s_globalRulesRegistry.Add("w", typeof(UserNamePatternConverter)); + s_globalRulesRegistry.Add("username", typeof(UserNamePatternConverter)); } /// - /// Initializes a new instance of the class. - /// Constructs a PatternLayout using the DefaultConversionPattern. - /// - /// - /// - /// The default pattern just produces the application supplied message. - /// - /// - /// Note to Inheritors: This constructor calls the virtual method - /// . If you override this method be - /// aware that it will be called before your is called constructor. - /// - /// - /// As per the contract the - /// method must be called after the properties on this object have been - /// configured. - /// - /// - public PatternLayout() - : this(DefaultConversionPattern) - { + /// Constructs a PatternLayout using the DefaultConversionPattern + /// + /// + /// + /// The default pattern just produces the application supplied message. + /// + /// + /// Note to Inheritors: This constructor calls the virtual method + /// . If you override this method be + /// aware that it will be called before your is called constructor. + /// + /// + /// As per the contract the + /// method must be called after the properties on this object have been + /// configured. + /// + /// + public PatternLayout() : this(DefaultConversionPattern) + { } /// - /// Initializes a new instance of the class. - /// Constructs a PatternLayout using the supplied conversion pattern. - /// - /// the pattern to use. - /// - /// - /// Note to Inheritors: This constructor calls the virtual method - /// . If you override this method be - /// aware that it will be called before your is called constructor. - /// - /// - /// When using this constructor the method - /// need not be called. This may not be the case when using a subclass. - /// - /// - public PatternLayout(string pattern) - { - // By default we do not process the exception - this.IgnoresException = true; - - this.m_pattern = pattern; - if (this.m_pattern == null) - { - this.m_pattern = DefaultConversionPattern; - } - - this.ActivateOptions(); + /// Constructs a PatternLayout using the supplied conversion pattern + /// + /// the pattern to use + /// + /// + /// Note to Inheritors: This constructor calls the virtual method + /// . If you override this method be + /// aware that it will be called before your is called constructor. + /// + /// + /// When using this constructor the method + /// need not be called. This may not be the case when using a subclass. + /// + /// + public PatternLayout(string pattern) + { + // By default we do not process the exception + this.IgnoresException = true; + + this.m_pattern = pattern; + if (this.m_pattern == null) + { + this.m_pattern = DefaultConversionPattern; + } + + this.ActivateOptions(); + } + + /// + /// The pattern formatting string + /// + /// + /// + /// The ConversionPattern option. This is the string which + /// controls formatting and consists of a mix of literal content and + /// conversion specifiers. + /// + /// + public string ConversionPattern + { + get { return this.m_pattern; } + set { this.m_pattern = value; } } - /// - /// Gets or sets the pattern formatting string. - /// - /// - /// - /// The ConversionPattern option. This is the string which - /// controls formatting and consists of a mix of literal content and - /// conversion specifiers. - /// - /// - public string ConversionPattern - { - get { return this.m_pattern; } - set { this.m_pattern = value; } - } - - /// - /// Create the pattern parser instance. - /// - /// the pattern to parse. - /// The that will format the event. - /// - /// - /// Creates the used to parse the conversion string. Sets the - /// global and instance rules on the . - /// - /// - protected virtual PatternParser CreatePatternParser(string pattern) - { - PatternParser patternParser = new PatternParser(pattern); - - // Add all the builtin patterns - foreach (DictionaryEntry entry in s_globalRulesRegistry) - { - ConverterInfo converterInfo = new ConverterInfo(); - converterInfo.Name = (string)entry.Key; - converterInfo.Type = (Type)entry.Value; - patternParser.PatternConverters[entry.Key] = converterInfo; - } + /// + /// Create the pattern parser instance + /// + /// the pattern to parse + /// The that will format the event + /// + /// + /// Creates the used to parse the conversion string. Sets the + /// global and instance rules on the . + /// + /// + protected virtual PatternParser CreatePatternParser(string pattern) + { + PatternParser patternParser = new PatternParser(pattern); - // Add the instance patterns - foreach (DictionaryEntry entry in this.m_instanceRulesRegistry) - { - patternParser.PatternConverters[entry.Key] = entry.Value; - } - - return patternParser; + // Add all the builtin patterns + foreach(DictionaryEntry entry in s_globalRulesRegistry) + { + ConverterInfo converterInfo = new ConverterInfo(); + converterInfo.Name = (string)entry.Key; + converterInfo.Type = (Type)entry.Value; + patternParser.PatternConverters[entry.Key] = converterInfo; + } + // Add the instance patterns + foreach(DictionaryEntry entry in this.m_instanceRulesRegistry) + { + patternParser.PatternConverters[entry.Key] = entry.Value; + } + + return patternParser; } - /// - /// Initialize layout options. - /// - /// - /// - /// This is part of the delayed object - /// activation scheme. The method must - /// be called on this object after the configuration properties have - /// been set. Until is called this - /// object is in an undefined state and must not be used. - /// - /// - /// If any of the configuration properties are modified then - /// must be called again. - /// - /// - public override void ActivateOptions() - { - this.m_head = this.CreatePatternParser(this.m_pattern).Parse(); - - PatternConverter curConverter = this.m_head; - while (curConverter != null) - { - PatternLayoutConverter layoutConverter = curConverter as PatternLayoutConverter; - if (layoutConverter != null) - { - if (!layoutConverter.IgnoresException) - { - // Found converter that handles the exception - this.IgnoresException = false; - - break; - } - } + /// + /// Initialize layout options + /// + /// + /// + /// This is part of the delayed object + /// activation scheme. The method must + /// be called on this object after the configuration properties have + /// been set. Until is called this + /// object is in an undefined state and must not be used. + /// + /// + /// If any of the configuration properties are modified then + /// must be called again. + /// + /// + public override void ActivateOptions() + { + this.m_head = this.CreatePatternParser(this.m_pattern).Parse(); - curConverter = curConverter.Next; - } + PatternConverter curConverter = this.m_head; + while(curConverter != null) + { + PatternLayoutConverter layoutConverter = curConverter as PatternLayoutConverter; + if (layoutConverter != null) + { + if (!layoutConverter.IgnoresException) + { + // Found converter that handles the exception + this.IgnoresException = false; + + break; + } + } + curConverter = curConverter.Next; + } } - /// - /// Produces a formatted string as specified by the conversion pattern. - /// - /// the event being logged. - /// The TextWriter to write the formatted event to. - /// - /// - /// Parse the using the patter format - /// specified in the property. - /// - /// - public override void Format(TextWriter writer, LoggingEvent loggingEvent) - { - if (writer == null) - { - throw new ArgumentNullException("writer"); - } + /// + /// Produces a formatted string as specified by the conversion pattern. + /// + /// the event being logged + /// The TextWriter to write the formatted event to + /// + /// + /// Parse the using the patter format + /// specified in the property. + /// + /// + public override void Format(TextWriter writer, LoggingEvent loggingEvent) + { + if (writer == null) + { + throw new ArgumentNullException("writer"); + } + if (loggingEvent == null) + { + throw new ArgumentNullException("loggingEvent"); + } + + PatternConverter c = this.m_head; - if (loggingEvent == null) - { - throw new ArgumentNullException("loggingEvent"); - } - - PatternConverter c = this.m_head; - - // loop through the chain of pattern converters - while (c != null) - { - c.Format(writer, loggingEvent); - c = c.Next; - } + // loop through the chain of pattern converters + while(c != null) + { + c.Format(writer, loggingEvent); + c = c.Next; + } } - /// - /// Add a converter to this PatternLayout. - /// - /// the converter info. - /// - /// - /// This version of the method is used by the configurator. - /// Programmatic users should use the alternative method. - /// - /// - public void AddConverter(ConverterInfo converterInfo) - { + /// + /// Add a converter to this PatternLayout + /// + /// the converter info + /// + /// + /// This version of the method is used by the configurator. + /// Programmatic users should use the alternative method. + /// + /// + public void AddConverter(ConverterInfo converterInfo) + { if (converterInfo == null) { throw new ArgumentNullException("converterInfo"); } - if (!typeof(PatternConverter).IsAssignableFrom(converterInfo.Type)) - { - throw new ArgumentException("The converter type specified [" + converterInfo.Type + "] must be a subclass of log4net.Util.PatternConverter", "converterInfo"); - } + if (!typeof(PatternConverter).IsAssignableFrom(converterInfo.Type)) + { + throw new ArgumentException("The converter type specified [" + converterInfo.Type + "] must be a subclass of log4net.Util.PatternConverter", "converterInfo"); + } + + this.m_instanceRulesRegistry[converterInfo.Name] = converterInfo; + } - this.m_instanceRulesRegistry[converterInfo.Name] = converterInfo; - } - - /// - /// Add a converter to this PatternLayout. - /// - /// the name of the conversion pattern for this converter. - /// the type of the converter. - /// - /// - /// Add a named pattern converter to this instance. This - /// converter will be used in the formatting of the event. - /// This method must be called before . - /// - /// - /// The specified must extend the - /// type. - /// - /// - public void AddConverter(string name, Type type) - { + /// + /// Add a converter to this PatternLayout + /// + /// the name of the conversion pattern for this converter + /// the type of the converter + /// + /// + /// Add a named pattern converter to this instance. This + /// converter will be used in the formatting of the event. + /// This method must be called before . + /// + /// + /// The specified must extend the + /// type. + /// + /// + public void AddConverter(string name, Type type) + { if (name == null) { throw new ArgumentNullException("name"); @@ -1156,11 +1144,11 @@ public void AddConverter(string name, Type type) throw new ArgumentNullException("type"); } - ConverterInfo converterInfo = new ConverterInfo(); - converterInfo.Name = name; - converterInfo.Type = type; - - this.AddConverter(converterInfo); - } - } -} + ConverterInfo converterInfo = new ConverterInfo(); + converterInfo.Name = name; + converterInfo.Type = type; + + this.AddConverter(converterInfo); + } + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/RawLayoutConverter.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/RawLayoutConverter.cs index afb348103e7..1e015a8e3b7 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/RawLayoutConverter.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/RawLayoutConverter.cs @@ -1,90 +1,83 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -#if NETSTANDARD1_3 -using System.Reflection; -#endif - -using log4net; -using log4net.Core; -using log4net.Util.TypeConverters; - -namespace log4net.Layout -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; +using System; - /// - /// Type converter for the interface. - /// - /// - /// - /// Used to convert objects to the interface. - /// Supports converting from the interface to - /// the interface using the . - /// - /// - /// Nicko Cadell. - /// Gert Driesen. - public class RawLayoutConverter : IConvertFrom +using log4net.Util.TypeConverters; + +namespace log4net.Layout +{ + /// + /// Type converter for the interface + /// + /// + /// + /// Used to convert objects to the interface. + /// Supports converting from the interface to + /// the interface using the . + /// + /// + /// Nicko Cadell + /// Gert Driesen + public class RawLayoutConverter : IConvertFrom { - /// - /// Can the sourceType be converted to an . - /// - /// the source to be to be converted. - /// true if the source type can be converted to . - /// - /// - /// Test if the can be converted to a - /// . Only is supported - /// as the . - /// - /// - public bool CanConvertFrom(Type sourceType) - { - // Accept an ILayout object - return typeof(ILayout).IsAssignableFrom(sourceType); - } - - /// - /// Convert the value to a object. - /// - /// the value to convert. - /// the object. - /// - /// - /// Convert the object to a - /// object. If the object - /// is a then the - /// is used to adapt between the two interfaces, otherwise an - /// exception is thrown. - /// - /// - public object ConvertFrom(object source) - { - ILayout layout = source as ILayout; - if (layout != null) - { - return new Layout2RawLayoutAdapter(layout); - } + /// + /// Can the sourceType be converted to an + /// + /// the source to be to be converted + /// true if the source type can be converted to + /// + /// + /// Test if the can be converted to a + /// . Only is supported + /// as the . + /// + /// + public bool CanConvertFrom(Type sourceType) + { + // Accept an ILayout object + return (typeof(ILayout).IsAssignableFrom(sourceType)); + } - throw ConversionNotSupportedException.Create(typeof(IRawLayout), source); + /// + /// Convert the value to a object + /// + /// the value to convert + /// the object + /// + /// + /// Convert the object to a + /// object. If the object + /// is a then the + /// is used to adapt between the two interfaces, otherwise an + /// exception is thrown. + /// + /// + public object ConvertFrom(object source) + { + ILayout layout = source as ILayout; + if (layout != null) + { + return new Layout2RawLayoutAdapter(layout); + } + throw ConversionNotSupportedException.Create(typeof(IRawLayout), source); } - } -} + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/RawPropertyLayout.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/RawPropertyLayout.cs index fef198bc147..136636dd959 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/RawPropertyLayout.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/RawPropertyLayout.cs @@ -1,84 +1,83 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.Layout -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; - using System.Text; +using System; +using System.Text; - using log4net.Core; - using log4net.Util; +using log4net.Core; +using log4net.Util; - /// - /// Extract the value of a property from the . - /// - /// - /// - /// Extract the value of a property from the . - /// - /// - /// Nicko Cadell. - public class RawPropertyLayout : IRawLayout +namespace log4net.Layout +{ + /// + /// Extract the value of a property from the + /// + /// + /// + /// Extract the value of a property from the + /// + /// + /// Nicko Cadell + public class RawPropertyLayout : IRawLayout { /// - /// Initializes a new instance of the class. - /// Constructs a RawPropertyLayout. - /// - public RawPropertyLayout() - { + /// Constructs a RawPropertyLayout + /// + public RawPropertyLayout() + { } - private string m_key; - - /// - /// Gets or sets the name of the value to lookup in the LoggingEvent Properties collection. - /// - /// - /// Value to lookup in the LoggingEvent Properties collection. - /// - /// - /// - /// String name of the property to lookup in the . - /// - /// - public string Key - { - get { return this.m_key; } - set { this.m_key = value; } + private string m_key; + + /// + /// The name of the value to lookup in the LoggingEvent Properties collection. + /// + /// + /// Value to lookup in the LoggingEvent Properties collection + /// + /// + /// + /// String name of the property to lookup in the . + /// + /// + public string Key + { + get { return this.m_key; } + set { this.m_key = value; } } - /// - /// Lookup the property for . - /// - /// The event to format. - /// returns property value. - /// - /// - /// Looks up and returns the object value of the property - /// named . If there is no property defined - /// with than name then null will be returned. - /// - /// - public virtual object Format(LoggingEvent loggingEvent) - { - return loggingEvent.LookupProperty(this.m_key); + /// + /// Lookup the property for + /// + /// The event to format + /// returns property value + /// + /// + /// Looks up and returns the object value of the property + /// named . If there is no property defined + /// with than name then null will be returned. + /// + /// + public virtual object Format(LoggingEvent loggingEvent) + { + return loggingEvent.LookupProperty(this.m_key); } - } -} + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/RawTimeStampLayout.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/RawTimeStampLayout.cs index d922cf357a7..2b27afc9b24 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/RawTimeStampLayout.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/RawTimeStampLayout.cs @@ -1,68 +1,67 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.Layout -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; - using System.Text; +using System; +using System.Text; - using log4net.Core; - using log4net.Util; +using log4net.Core; +using log4net.Util; - /// - /// Extract the date from the . - /// - /// - /// - /// Extract the date from the . - /// - /// - /// Nicko Cadell. - /// Gert Driesen. - public class RawTimeStampLayout : IRawLayout +namespace log4net.Layout +{ + /// + /// Extract the date from the + /// + /// + /// + /// Extract the date from the + /// + /// + /// Nicko Cadell + /// Gert Driesen + public class RawTimeStampLayout : IRawLayout { /// - /// Initializes a new instance of the class. - /// Constructs a RawTimeStampLayout. - /// - public RawTimeStampLayout() - { + /// Constructs a RawTimeStampLayout + /// + public RawTimeStampLayout() + { } - /// - /// Gets the as a . - /// - /// The event to format. - /// returns the time stamp. - /// - /// - /// Gets the as a . - /// - /// - /// The time stamp is in local time. To format the time stamp - /// in universal time use . - /// - /// - public virtual object Format(LoggingEvent loggingEvent) - { - return loggingEvent.TimeStamp; + /// + /// Gets the as a . + /// + /// The event to format + /// returns the time stamp + /// + /// + /// Gets the as a . + /// + /// + /// The time stamp is in local time. To format the time stamp + /// in universal time use . + /// + /// + public virtual object Format(LoggingEvent loggingEvent) + { + return loggingEvent.TimeStamp; } - } -} + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/RawUtcTimeStampLayout.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/RawUtcTimeStampLayout.cs index 3691a5a3259..c331beb5472 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/RawUtcTimeStampLayout.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/RawUtcTimeStampLayout.cs @@ -1,68 +1,67 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.Layout -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; - using System.Text; +using System; +using System.Text; - using log4net.Core; - using log4net.Util; +using log4net.Core; +using log4net.Util; - /// - /// Extract the date from the . - /// - /// - /// - /// Extract the date from the . - /// - /// - /// Nicko Cadell. - /// Gert Driesen. - public class RawUtcTimeStampLayout : IRawLayout +namespace log4net.Layout +{ + /// + /// Extract the date from the + /// + /// + /// + /// Extract the date from the + /// + /// + /// Nicko Cadell + /// Gert Driesen + public class RawUtcTimeStampLayout : IRawLayout { /// - /// Initializes a new instance of the class. - /// Constructs a RawUtcTimeStampLayout. - /// - public RawUtcTimeStampLayout() - { + /// Constructs a RawUtcTimeStampLayout + /// + public RawUtcTimeStampLayout() + { } - /// - /// Gets the as a . - /// - /// The event to format. - /// returns the time stamp. - /// - /// - /// Gets the as a . - /// - /// - /// The time stamp is in universal time. To format the time stamp - /// in local time use . - /// - /// - public virtual object Format(LoggingEvent loggingEvent) - { - return loggingEvent.TimeStampUtc; + /// + /// Gets the as a . + /// + /// The event to format + /// returns the time stamp + /// + /// + /// Gets the as a . + /// + /// + /// The time stamp is in universal time. To format the time stamp + /// in local time use . + /// + /// + public virtual object Format(LoggingEvent loggingEvent) + { + return loggingEvent.TimeStampUtc; } - } -} + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/SimpleLayout.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/SimpleLayout.cs index c877deac11e..6513b6d614d 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/SimpleLayout.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/SimpleLayout.cs @@ -1,101 +1,100 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.Layout -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; - using System.IO; - using System.Text; +using System; +using System.IO; +using System.Text; - using log4net.Core; - using log4net.Util; +using log4net.Util; +using log4net.Core; - /// - /// A very simple layout. - /// - /// - /// - /// SimpleLayout consists of the level of the log statement, - /// followed by " - " and then the log message itself. For example. - /// - /// DEBUG - Hello world - /// - /// - /// - /// Nicko Cadell. - /// Gert Driesen. - public class SimpleLayout : LayoutSkeleton +namespace log4net.Layout +{ + /// + /// A very simple layout + /// + /// + /// + /// SimpleLayout consists of the level of the log statement, + /// followed by " - " and then the log message itself. For example, + /// + /// DEBUG - Hello world + /// + /// + /// + /// Nicko Cadell + /// Gert Driesen + public class SimpleLayout : LayoutSkeleton { /// - /// Initializes a new instance of the class. - /// Constructs a SimpleLayout. - /// - public SimpleLayout() - { - this.IgnoresException = true; + /// Constructs a SimpleLayout + /// + public SimpleLayout() + { + this.IgnoresException = true; } - /// - /// Initialize layout options. - /// - /// - /// - /// This is part of the delayed object - /// activation scheme. The method must - /// be called on this object after the configuration properties have - /// been set. Until is called this - /// object is in an undefined state and must not be used. - /// - /// - /// If any of the configuration properties are modified then - /// must be called again. - /// - /// - public override void ActivateOptions() - { - // nothing to do. + /// + /// Initialize layout options + /// + /// + /// + /// This is part of the delayed object + /// activation scheme. The method must + /// be called on this object after the configuration properties have + /// been set. Until is called this + /// object is in an undefined state and must not be used. + /// + /// + /// If any of the configuration properties are modified then + /// must be called again. + /// + /// + public override void ActivateOptions() + { + // nothing to do. } - /// - /// Produces a simple formatted output. - /// - /// the event being logged. - /// The TextWriter to write the formatted event to. - /// - /// - /// Formats the event as the level of the even, - /// followed by " - " and then the log message itself. The - /// output is terminated by a newline. - /// - /// - public override void Format(TextWriter writer, LoggingEvent loggingEvent) - { - if (loggingEvent == null) - { - throw new ArgumentNullException("loggingEvent"); - } - - writer.Write(loggingEvent.Level.DisplayName); - writer.Write(" - "); - loggingEvent.WriteRenderedMessage(writer); - writer.WriteLine(); + /// + /// Produces a simple formatted output. + /// + /// the event being logged + /// The TextWriter to write the formatted event to + /// + /// + /// Formats the event as the level of the even, + /// followed by " - " and then the log message itself. The + /// output is terminated by a newline. + /// + /// + public override void Format(TextWriter writer, LoggingEvent loggingEvent) + { + if (loggingEvent == null) + { + throw new ArgumentNullException("loggingEvent"); + } + + writer.Write(loggingEvent.Level.DisplayName); + writer.Write(" - "); + loggingEvent.WriteRenderedMessage(writer); + writer.WriteLine(); } - } -} + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/XMLLayout.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/XMLLayout.cs index ea43f0c3ed9..30d4672645c 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/XMLLayout.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/XMLLayout.cs @@ -1,344 +1,339 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.Layout -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; - using System.Text; - using System.Xml; +using System; +using System.Text; +using System.Xml; - using log4net.Core; - using log4net.Util; +using log4net.Core; +using log4net.Util; - /// - /// Layout that formats the log events as XML elements. - /// - /// - /// - /// The output of the consists of a series of - /// log4net:event elements. It does not output a complete well-formed XML - /// file. The output is designed to be included as an external entity - /// in a separate file to form a correct XML file. - /// - /// - /// For example, if abc is the name of the file where - /// the output goes, then a well-formed XML file would - /// be: - /// - /// - /// <?xml version="1.0" ?> - /// - /// <!DOCTYPE log4net:events SYSTEM "log4net-events.dtd" [<!ENTITY data SYSTEM "abc">]> - /// - /// <log4net:events version="1.2" xmlns:log4net="http://logging.apache.org/log4net/schemas/log4net-events-1.2> - /// &data; - /// </log4net:events> - /// - /// - /// This approach enforces the independence of the - /// and the appender where it is embedded. - /// - /// - /// The version attribute helps components to correctly - /// interpret output generated by . The value of - /// this attribute should be "1.2" for release 1.2 and later. - /// - /// - /// Alternatively the Header and Footer properties can be - /// configured to output the correct XML header, open tag and close tag. - /// When setting the Header and Footer properties it is essential - /// that the underlying data store not be appendable otherwise the data - /// will become invalid XML. - /// - /// - /// Nicko Cadell. - /// Gert Driesen. - public class XmlLayout : XmlLayoutBase +namespace log4net.Layout +{ + /// + /// Layout that formats the log events as XML elements. + /// + /// + /// + /// The output of the consists of a series of + /// log4net:event elements. It does not output a complete well-formed XML + /// file. The output is designed to be included as an external entity + /// in a separate file to form a correct XML file. + /// + /// + /// For example, if abc is the name of the file where + /// the output goes, then a well-formed XML file would + /// be: + /// + /// + /// <?xml version="1.0" ?> + /// + /// <!DOCTYPE log4net:events SYSTEM "log4net-events.dtd" [<!ENTITY data SYSTEM "abc">]> + /// + /// <log4net:events version="1.2" xmlns:log4net="http://logging.apache.org/log4net/schemas/log4net-events-1.2> + /// &data; + /// </log4net:events> + /// + /// + /// This approach enforces the independence of the + /// and the appender where it is embedded. + /// + /// + /// The version attribute helps components to correctly + /// interpret output generated by . The value of + /// this attribute should be "1.2" for release 1.2 and later. + /// + /// + /// Alternatively the Header and Footer properties can be + /// configured to output the correct XML header, open tag and close tag. + /// When setting the Header and Footer properties it is essential + /// that the underlying data store not be appendable otherwise the data + /// will become invalid XML. + /// + /// + /// Nicko Cadell + /// Gert Driesen + public class XmlLayout : XmlLayoutBase { /// - /// Initializes a new instance of the class. - /// Constructs an XmlLayout. - /// - public XmlLayout() - : base() - { + /// Constructs an XmlLayout + /// + public XmlLayout() : base() + { } /// - /// Initializes a new instance of the class. - /// Constructs an XmlLayout. - /// - /// - /// - /// The LocationInfo option takes a boolean value. By - /// default, it is set to false which means there will be no location - /// information output by this layout. If the the option is set to - /// true, then the file name and line number of the statement - /// at the origin of the log statement will be output. - /// - /// - /// If you are embedding this layout within an SmtpAppender - /// then make sure to set the LocationInfo option of that - /// appender as well. - /// - /// - public XmlLayout(bool locationInfo) - : base(locationInfo) - { + /// Constructs an XmlLayout. + /// + /// + /// + /// The LocationInfo option takes a boolean value. By + /// default, it is set to false which means there will be no location + /// information output by this layout. If the the option is set to + /// true, then the file name and line number of the statement + /// at the origin of the log statement will be output. + /// + /// + /// If you are embedding this layout within an SmtpAppender + /// then make sure to set the LocationInfo option of that + /// appender as well. + /// + /// + public XmlLayout(bool locationInfo) : base(locationInfo) + { } - /// - /// Gets or sets the prefix to use for all element names. - /// - /// - /// - /// The default prefix is log4net. Set this property - /// to change the prefix. If the prefix is set to an empty string - /// then no prefix will be written. - /// - /// - public string Prefix - { - get { return this.m_prefix; } - set { this.m_prefix = value; } - } + /// + /// The prefix to use for all element names + /// + /// + /// + /// The default prefix is log4net. Set this property + /// to change the prefix. If the prefix is set to an empty string + /// then no prefix will be written. + /// + /// + public string Prefix + { + get { return this.m_prefix; } + set { this.m_prefix = value; } + } + + + /// + /// Set whether or not to base64 encode the message. + /// + /// + /// + /// By default the log message will be written as text to the xml + /// output. This can cause problems when the message contains binary + /// data. By setting this to true the contents of the message will be + /// base64 encoded. If this is set then invalid character replacement + /// (see ) will not be performed + /// on the log message. + /// + /// + public bool Base64EncodeMessage + { + get { return this.m_base64Message; } + set { this.m_base64Message = value; } + } - /// - /// Gets or sets a value indicating whether set whether or not to base64 encode the message. - /// - /// - /// - /// By default the log message will be written as text to the xml - /// output. This can cause problems when the message contains binary - /// data. By setting this to true the contents of the message will be - /// base64 encoded. If this is set then invalid character replacement - /// (see ) will not be performed - /// on the log message. - /// - /// - public bool Base64EncodeMessage - { - get { return this.m_base64Message; } - set { this.m_base64Message = value; } - } - - /// - /// Gets or sets a value indicating whether set whether or not to base64 encode the property values. - /// - /// - /// - /// By default the properties will be written as text to the xml - /// output. This can cause problems when one or more properties contain - /// binary data. By setting this to true the values of the properties - /// will be base64 encoded. If this is set then invalid character replacement - /// (see ) will not be performed - /// on the property values. - /// - /// - public bool Base64EncodeProperties - { - get { return this.m_base64Properties; } - set { this.m_base64Properties = value; } + /// + /// Set whether or not to base64 encode the property values. + /// + /// + /// + /// By default the properties will be written as text to the xml + /// output. This can cause problems when one or more properties contain + /// binary data. By setting this to true the values of the properties + /// will be base64 encoded. If this is set then invalid character replacement + /// (see ) will not be performed + /// on the property values. + /// + /// + public bool Base64EncodeProperties + { + get { return this.m_base64Properties; } + set { this.m_base64Properties = value; } } - /// - /// Initialize layout options. - /// - /// - /// - /// This is part of the delayed object - /// activation scheme. The method must - /// be called on this object after the configuration properties have - /// been set. Until is called this - /// object is in an undefined state and must not be used. - /// - /// - /// If any of the configuration properties are modified then - /// must be called again. - /// - /// - /// Builds a cache of the element names. - /// - /// - public override void ActivateOptions() - { - base.ActivateOptions(); - - // Cache the full element names including the prefix - if (this.m_prefix != null && this.m_prefix.Length > 0) - { - this.m_elmEvent = this.m_prefix + ":" + ELM_EVENT; - this.m_elmMessage = this.m_prefix + ":" + ELM_MESSAGE; - this.m_elmProperties = this.m_prefix + ":" + ELM_PROPERTIES; - this.m_elmData = this.m_prefix + ":" + ELM_DATA; - this.m_elmException = this.m_prefix + ":" + ELM_EXCEPTION; - this.m_elmLocation = this.m_prefix + ":" + ELM_LOCATION; - } + + /// + /// Initialize layout options + /// + /// + /// + /// This is part of the delayed object + /// activation scheme. The method must + /// be called on this object after the configuration properties have + /// been set. Until is called this + /// object is in an undefined state and must not be used. + /// + /// + /// If any of the configuration properties are modified then + /// must be called again. + /// + /// + /// Builds a cache of the element names + /// + /// + public override void ActivateOptions() + { + base.ActivateOptions(); + + // Cache the full element names including the prefix + if (this.m_prefix != null && this.m_prefix.Length > 0) + { + this.m_elmEvent = this.m_prefix + ":" + ELM_EVENT; + this.m_elmMessage = this.m_prefix + ":" + ELM_MESSAGE; + this.m_elmProperties = this.m_prefix + ":" + ELM_PROPERTIES; + this.m_elmData = this.m_prefix + ":" + ELM_DATA; + this.m_elmException = this.m_prefix + ":" + ELM_EXCEPTION; + this.m_elmLocation = this.m_prefix + ":" + ELM_LOCATION; + } } - /// - /// Does the actual writing of the XML. - /// - /// The writer to use to output the event to. - /// The event to write. - /// - /// - /// Override the base class method - /// to write the to the . - /// - /// - protected override void FormatXml(XmlWriter writer, LoggingEvent loggingEvent) - { - writer.WriteStartElement(this.m_elmEvent); - writer.WriteAttributeString(ATTR_LOGGER, loggingEvent.LoggerName); - -#if NET_2_0 || NETCF_2_0 || MONO_2_0 || NETSTANDARD1_3 - writer.WriteAttributeString(ATTR_TIMESTAMP, XmlConvert.ToString(loggingEvent.TimeStamp, XmlDateTimeSerializationMode.Local)); -#else - writer.WriteAttributeString(ATTR_TIMESTAMP, XmlConvert.ToString(loggingEvent.TimeStamp)); -#endif - - writer.WriteAttributeString(ATTR_LEVEL, loggingEvent.Level.DisplayName); - writer.WriteAttributeString(ATTR_THREAD, loggingEvent.ThreadName); - - if (loggingEvent.Domain != null && loggingEvent.Domain.Length > 0) - { - writer.WriteAttributeString(ATTR_DOMAIN, loggingEvent.Domain); - } + /// + /// Does the actual writing of the XML. + /// + /// The writer to use to output the event to. + /// The event to write. + /// + /// + /// Override the base class method + /// to write the to the . + /// + /// + protected override void FormatXml(XmlWriter writer, LoggingEvent loggingEvent) + { + writer.WriteStartElement(this.m_elmEvent); + writer.WriteAttributeString(ATTR_LOGGER, loggingEvent.LoggerName); + +#if NET_2_0 || NETCF_2_0 || MONO_2_0 || NETSTANDARD + writer.WriteAttributeString(ATTR_TIMESTAMP, XmlConvert.ToString(loggingEvent.TimeStamp, XmlDateTimeSerializationMode.Local)); +#else + writer.WriteAttributeString(ATTR_TIMESTAMP, XmlConvert.ToString(loggingEvent.TimeStamp)); +#endif + + writer.WriteAttributeString(ATTR_LEVEL, loggingEvent.Level.DisplayName); + writer.WriteAttributeString(ATTR_THREAD, loggingEvent.ThreadName); - if (loggingEvent.Identity != null && loggingEvent.Identity.Length > 0) - { - writer.WriteAttributeString(ATTR_IDENTITY, loggingEvent.Identity); - } + if (loggingEvent.Domain != null && loggingEvent.Domain.Length > 0) + { + writer.WriteAttributeString(ATTR_DOMAIN, loggingEvent.Domain); + } + if (loggingEvent.Identity != null && loggingEvent.Identity.Length > 0) + { + writer.WriteAttributeString(ATTR_IDENTITY, loggingEvent.Identity); + } + if (loggingEvent.UserName != null && loggingEvent.UserName.Length > 0) + { + writer.WriteAttributeString(ATTR_USERNAME, loggingEvent.UserName); + } + + // Append the message text + writer.WriteStartElement(this.m_elmMessage); + if (!this.Base64EncodeMessage) + { + Transform.WriteEscapedXmlString(writer, loggingEvent.RenderedMessage, this.InvalidCharReplacement); + } + else + { + byte[] messageBytes = Encoding.UTF8.GetBytes(loggingEvent.RenderedMessage); + string base64Message = Convert.ToBase64String(messageBytes, 0, messageBytes.Length); + Transform.WriteEscapedXmlString(writer, base64Message,this.InvalidCharReplacement); + } + writer.WriteEndElement(); - if (loggingEvent.UserName != null && loggingEvent.UserName.Length > 0) - { - writer.WriteAttributeString(ATTR_USERNAME, loggingEvent.UserName); - } - - // Append the message text - writer.WriteStartElement(this.m_elmMessage); - if (!this.Base64EncodeMessage) - { - Transform.WriteEscapedXmlString(writer, loggingEvent.RenderedMessage, this.InvalidCharReplacement); - } - else - { - byte[] messageBytes = Encoding.UTF8.GetBytes(loggingEvent.RenderedMessage); - string base64Message = Convert.ToBase64String(messageBytes, 0, messageBytes.Length); - Transform.WriteEscapedXmlString(writer, base64Message, this.InvalidCharReplacement); - } + PropertiesDictionary properties = loggingEvent.GetProperties(); - writer.WriteEndElement(); - - PropertiesDictionary properties = loggingEvent.GetProperties(); - - // Append the properties text - if (properties.Count > 0) - { - writer.WriteStartElement(this.m_elmProperties); - foreach (System.Collections.DictionaryEntry entry in properties) - { - writer.WriteStartElement(this.m_elmData); - writer.WriteAttributeString(ATTR_NAME, Transform.MaskXmlInvalidCharacters((string)entry.Key, this.InvalidCharReplacement)); - - // Use an ObjectRenderer to convert the object to a string - string valueStr = null; - if (!this.Base64EncodeProperties) - { - valueStr = Transform.MaskXmlInvalidCharacters(loggingEvent.Repository.RendererMap.FindAndRender(entry.Value), this.InvalidCharReplacement); - } - else - { - byte[] propertyValueBytes = Encoding.UTF8.GetBytes(loggingEvent.Repository.RendererMap.FindAndRender(entry.Value)); - valueStr = Convert.ToBase64String(propertyValueBytes, 0, propertyValueBytes.Length); - } + // Append the properties text + if (properties.Count > 0) + { + writer.WriteStartElement(this.m_elmProperties); + foreach(System.Collections.DictionaryEntry entry in properties) + { + writer.WriteStartElement(this.m_elmData); + writer.WriteAttributeString(ATTR_NAME, Transform.MaskXmlInvalidCharacters((string)entry.Key,this.InvalidCharReplacement)); - writer.WriteAttributeString(ATTR_VALUE, valueStr); - - writer.WriteEndElement(); - } + // Use an ObjectRenderer to convert the object to a string + string valueStr =null; + if (!this.Base64EncodeProperties) + { + valueStr = Transform.MaskXmlInvalidCharacters(loggingEvent.Repository.RendererMap.FindAndRender(entry.Value),this.InvalidCharReplacement); + } + else + { + byte[] propertyValueBytes = Encoding.UTF8.GetBytes(loggingEvent.Repository.RendererMap.FindAndRender(entry.Value)); + valueStr = Convert.ToBase64String(propertyValueBytes, 0, propertyValueBytes.Length); + } + writer.WriteAttributeString(ATTR_VALUE, valueStr); - writer.WriteEndElement(); - } - - string exceptionStr = loggingEvent.GetExceptionString(); - if (exceptionStr != null && exceptionStr.Length > 0) - { - // Append the stack trace line - writer.WriteStartElement(this.m_elmException); - Transform.WriteEscapedXmlString(writer, exceptionStr, this.InvalidCharReplacement); - writer.WriteEndElement(); - } - - if (this.LocationInfo) - { - LocationInfo locationInfo = loggingEvent.LocationInformation; - - writer.WriteStartElement(this.m_elmLocation); - writer.WriteAttributeString(ATTR_CLASS, locationInfo.ClassName); - writer.WriteAttributeString(ATTR_METHOD, locationInfo.MethodName); - writer.WriteAttributeString(ATTR_FILE, locationInfo.FileName); - writer.WriteAttributeString(ATTR_LINE, locationInfo.LineNumber); - writer.WriteEndElement(); - } - - writer.WriteEndElement(); + writer.WriteEndElement(); + } + writer.WriteEndElement(); + } + + string exceptionStr = loggingEvent.GetExceptionString(); + if (exceptionStr != null && exceptionStr.Length > 0) + { + // Append the stack trace line + writer.WriteStartElement(this.m_elmException); + Transform.WriteEscapedXmlString(writer, exceptionStr,this.InvalidCharReplacement); + writer.WriteEndElement(); + } + + if (this.LocationInfo) + { + LocationInfo locationInfo = loggingEvent.LocationInformation; + + writer.WriteStartElement(this.m_elmLocation); + writer.WriteAttributeString(ATTR_CLASS, locationInfo.ClassName); + writer.WriteAttributeString(ATTR_METHOD, locationInfo.MethodName); + writer.WriteAttributeString(ATTR_FILE, locationInfo.FileName); + writer.WriteAttributeString(ATTR_LINE, locationInfo.LineNumber); + writer.WriteEndElement(); + } + + writer.WriteEndElement(); } - /// - /// The prefix to use for all generated element names. - /// - private string m_prefix = PREFIX; - - private string m_elmEvent = ELM_EVENT; - private string m_elmMessage = ELM_MESSAGE; - private string m_elmData = ELM_DATA; - private string m_elmProperties = ELM_PROPERTIES; - private string m_elmException = ELM_EXCEPTION; - private string m_elmLocation = ELM_LOCATION; - - private bool m_base64Message = false; + /// + /// The prefix to use for all generated element names + /// + private string m_prefix = PREFIX; + + private string m_elmEvent = ELM_EVENT; + private string m_elmMessage = ELM_MESSAGE; + private string m_elmData = ELM_DATA; + private string m_elmProperties = ELM_PROPERTIES; + private string m_elmException = ELM_EXCEPTION; + private string m_elmLocation = ELM_LOCATION; + + private bool m_base64Message = false; private bool m_base64Properties = false; - private const string PREFIX = "log4net"; - - private const string ELM_EVENT = "event"; - private const string ELM_MESSAGE = "message"; - private const string ELM_PROPERTIES = "properties"; - private const string ELM_GLOBAL_PROPERTIES = "global-properties"; - private const string ELM_DATA = "data"; - private const string ELM_EXCEPTION = "exception"; - private const string ELM_LOCATION = "locationInfo"; - - private const string ATTR_LOGGER = "logger"; - private const string ATTR_TIMESTAMP = "timestamp"; - private const string ATTR_LEVEL = "level"; - private const string ATTR_THREAD = "thread"; - private const string ATTR_DOMAIN = "domain"; - private const string ATTR_IDENTITY = "identity"; - private const string ATTR_USERNAME = "username"; - private const string ATTR_CLASS = "class"; - private const string ATTR_METHOD = "method"; - private const string ATTR_FILE = "file"; - private const string ATTR_LINE = "line"; - private const string ATTR_NAME = "name"; + + private const string PREFIX = "log4net"; + + private const string ELM_EVENT = "event"; + private const string ELM_MESSAGE = "message"; + private const string ELM_PROPERTIES = "properties"; + private const string ELM_GLOBAL_PROPERTIES = "global-properties"; + private const string ELM_DATA = "data"; + private const string ELM_EXCEPTION = "exception"; + private const string ELM_LOCATION = "locationInfo"; + + private const string ATTR_LOGGER = "logger"; + private const string ATTR_TIMESTAMP = "timestamp"; + private const string ATTR_LEVEL = "level"; + private const string ATTR_THREAD = "thread"; + private const string ATTR_DOMAIN = "domain"; + private const string ATTR_IDENTITY = "identity"; + private const string ATTR_USERNAME = "username"; + private const string ATTR_CLASS = "class"; + private const string ATTR_METHOD = "method"; + private const string ATTR_FILE = "file"; + private const string ATTR_LINE = "line"; + private const string ATTR_NAME = "name"; private const string ATTR_VALUE = "value"; - } + } } + diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/XMLLayoutBase.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/XMLLayoutBase.cs index f6a750a263c..573b62fc962 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/XMLLayoutBase.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/XMLLayoutBase.cs @@ -1,238 +1,236 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.Layout -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; - using System.IO; - using System.Text; - using System.Xml; +using System; +using System.IO; +using System.Text; +using System.Xml; - using log4net.Core; - using log4net.Util; +using log4net.Util; +using log4net.Core; - /// - /// Layout that formats the log events as XML elements. - /// - /// - /// - /// This is an abstract class that must be subclassed by an implementation - /// to conform to a specific schema. - /// - /// - /// Deriving classes must implement the method. - /// - /// - /// Nicko Cadell. - /// Gert Driesen. - public abstract class XmlLayoutBase : LayoutSkeleton +namespace log4net.Layout +{ + /// + /// Layout that formats the log events as XML elements. + /// + /// + /// + /// This is an abstract class that must be subclassed by an implementation + /// to conform to a specific schema. + /// + /// + /// Deriving classes must implement the method. + /// + /// + /// Nicko Cadell + /// Gert Driesen + public abstract class XmlLayoutBase : LayoutSkeleton { /// - /// Initializes a new instance of the class. - /// Protected constructor to support subclasses. - /// - /// - /// - /// Initializes a new instance of the class - /// with no location info. - /// - /// - protected XmlLayoutBase() - : this(false) - { - this.IgnoresException = false; + /// Protected constructor to support subclasses + /// + /// + /// + /// Initializes a new instance of the class + /// with no location info. + /// + /// + protected XmlLayoutBase() : this(false) + { + this.IgnoresException = false; } /// - /// Initializes a new instance of the class. - /// Protected constructor to support subclasses. - /// - /// - /// - /// The parameter determines whether - /// location information will be output by the layout. If - /// is set to true, then the - /// file name and line number of the statement at the origin of the log - /// statement will be output. - /// - /// - /// If you are embedding this layout within an SMTPAppender - /// then make sure to set the LocationInfo option of that - /// appender as well. - /// - /// - protected XmlLayoutBase(bool locationInfo) - { - this.IgnoresException = false; - this.m_locationInfo = locationInfo; + /// Protected constructor to support subclasses + /// + /// + /// + /// The parameter determines whether + /// location information will be output by the layout. If + /// is set to true, then the + /// file name and line number of the statement at the origin of the log + /// statement will be output. + /// + /// + /// If you are embedding this layout within an SMTPAppender + /// then make sure to set the LocationInfo option of that + /// appender as well. + /// + /// + protected XmlLayoutBase(bool locationInfo) + { + this.IgnoresException = false; + this.m_locationInfo = locationInfo; } - /// - /// Gets or sets a value indicating whether to include location information in - /// the XML events. - /// - /// - /// true if location information should be included in the XML - /// events; otherwise, false. - /// - /// - /// - /// If is set to true, then the file - /// name and line number of the statement at the origin of the log - /// statement will be output. - /// - /// - /// If you are embedding this layout within an SMTPAppender - /// then make sure to set the LocationInfo option of that - /// appender as well. - /// - /// - public bool LocationInfo - { - get { return this.m_locationInfo; } - set { this.m_locationInfo = value; } - } + /// + /// Gets a value indicating whether to include location information in + /// the XML events. + /// + /// + /// true if location information should be included in the XML + /// events; otherwise, false. + /// + /// + /// + /// If is set to true, then the file + /// name and line number of the statement at the origin of the log + /// statement will be output. + /// + /// + /// If you are embedding this layout within an SMTPAppender + /// then make sure to set the LocationInfo option of that + /// appender as well. + /// + /// + public bool LocationInfo + { + get { return this.m_locationInfo; } + set { this.m_locationInfo = value; } + } + /// + /// The string to replace characters that can not be expressed in XML with. + /// + /// + /// Not all characters may be expressed in XML. This property contains the + /// string to replace those that can not with. This defaults to a ?. Set it + /// to the empty string to simply remove offending characters. For more + /// details on the allowed character ranges see http://www.w3.org/TR/REC-xml/#charsets + /// Character replacement will occur in the log message, the property names + /// and the property values. + /// + /// + /// + public string InvalidCharReplacement + { + get {return this.m_invalidCharReplacement;} + set { this.m_invalidCharReplacement = value;} + } - /// - /// Gets or sets the string to replace characters that can not be expressed in XML with. - /// - /// - /// Not all characters may be expressed in XML. This property contains the - /// string to replace those that can not with. This defaults to a ?. Set it - /// to the empty string to simply remove offending characters. For more - /// details on the allowed character ranges see http://www.w3.org/TR/REC-xml/#charsets - /// Character replacement will occur in the log message, the property names - /// and the property values. - /// - /// - /// - public string InvalidCharReplacement - { - get { return this.m_invalidCharReplacement; } - set { this.m_invalidCharReplacement = value; } + /// + /// Initialize layout options + /// + /// + /// + /// This is part of the delayed object + /// activation scheme. The method must + /// be called on this object after the configuration properties have + /// been set. Until is called this + /// object is in an undefined state and must not be used. + /// + /// + /// If any of the configuration properties are modified then + /// must be called again. + /// + /// + public override void ActivateOptions() + { + // nothing to do } - /// - /// Initialize layout options. - /// - /// - /// - /// This is part of the delayed object - /// activation scheme. The method must - /// be called on this object after the configuration properties have - /// been set. Until is called this - /// object is in an undefined state and must not be used. - /// - /// - /// If any of the configuration properties are modified then - /// must be called again. - /// - /// - public override void ActivateOptions() - { - // nothing to do + /// + /// Gets the content type output by this layout. + /// + /// + /// As this is the XML layout, the value is always "text/xml". + /// + /// + /// + /// As this is the XML layout, the value is always "text/xml". + /// + /// + public override string ContentType + { + get { return "text/xml"; } } - /// - /// Gets the content type output by this layout. - /// - /// - /// As this is the XML layout, the value is always "text/xml". - /// - /// - /// - /// As this is the XML layout, the value is always "text/xml". - /// - /// - public override string ContentType - { - get { return "text/xml"; } - } - - /// - /// Produces a formatted string. - /// - /// The event being logged. - /// The TextWriter to write the formatted event to. - /// - /// - /// Format the and write it to the . - /// - /// - /// This method creates an that writes to the - /// . The is passed - /// to the method. Subclasses should override the - /// method rather than this method. - /// - /// - public override void Format(TextWriter writer, LoggingEvent loggingEvent) - { - if (loggingEvent == null) - { - throw new ArgumentNullException("loggingEvent"); - } -#if NETSTANDARD1_3 - var settings = new XmlWriterSettings - { - Indent = false, - OmitXmlDeclaration = true - }; - var xmlWriter = XmlWriter.Create(new ProtectCloseTextWriter(writer), settings); -#else - XmlTextWriter xmlWriter = new XmlTextWriter(new ProtectCloseTextWriter(writer)); - xmlWriter.Formatting = Formatting.None; - xmlWriter.Namespaces = false; -#endif + /// + /// Produces a formatted string. + /// + /// The event being logged. + /// The TextWriter to write the formatted event to + /// + /// + /// Format the and write it to the . + /// + /// + /// This method creates an that writes to the + /// . The is passed + /// to the method. Subclasses should override the + /// method rather than this method. + /// + /// + public override void Format(TextWriter writer, LoggingEvent loggingEvent) + { + if (loggingEvent == null) + { + throw new ArgumentNullException("loggingEvent"); + } +#if NETSTANDARD + var settings = new XmlWriterSettings + { + Indent = false, + OmitXmlDeclaration = true + }; + using(var xmlWriter = XmlWriter.Create(new ProtectCloseTextWriter(writer), settings)) + { +#else + using (var xmlWriter = new XmlTextWriter(new ProtectCloseTextWriter(writer))) + { + xmlWriter.Formatting = Formatting.None; + xmlWriter.Namespaces = false; + +#endif + // Write the event to the writer + this.FormatXml(xmlWriter, loggingEvent); - // Write the event to the writer - this.FormatXml(xmlWriter, loggingEvent); - - xmlWriter.WriteWhitespace(SystemInfo.NewLine); - - // Close on xmlWriter will ensure xml is flushed - // the protected writer will ignore the actual close - xmlWriter.Close(); + xmlWriter.WriteWhitespace(SystemInfo.NewLine); + } + // Close on xmlWriter will ensure xml is flushed + // the protected writer will ignore the actual close + // -> Dispose from using var will close & flush } - /// - /// Does the actual writing of the XML. - /// - /// The writer to use to output the event to. - /// The event to write. - /// - /// - /// Subclasses should override this method to format - /// the as XML. - /// - /// + /// + /// Does the actual writing of the XML. + /// + /// The writer to use to output the event to. + /// The event to write. + /// + /// + /// Subclasses should override this method to format + /// the as XML. + /// + /// protected abstract void FormatXml(XmlWriter writer, LoggingEvent loggingEvent); - /// - /// Flag to indicate if location information should be included in - /// the XML events. - /// - private bool m_locationInfo = false; - - /// - /// The string to replace invalid chars with. - /// + /// + /// Flag to indicate if location information should be included in + /// the XML events. + /// + private bool m_locationInfo = false; + + /// + /// The string to replace invalid chars with + /// private string m_invalidCharReplacement = "?"; - } -} + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/XmlLayoutSchemaLog4j.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/XmlLayoutSchemaLog4j.cs index 0914d4a7fe4..72df825f0c9 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Layout/XmlLayoutSchemaLog4j.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Layout/XmlLayoutSchemaLog4j.cs @@ -1,246 +1,241 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.Layout -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; - using System.IO; - using System.Text; - using System.Xml; - - using log4net.Core; - using log4net.Util; - - /// - /// Layout that formats the log events as XML elements compatible with the log4j schema. - /// - /// - /// - /// Formats the log events according to the http://logging.apache.org/log4j schema. - /// - /// - /// Nicko Cadell. - public class XmlLayoutSchemaLog4j : XmlLayoutBase +using System; +using System.Text; +using System.Xml; +using System.IO; + +using log4net.Core; +using log4net.Util; + +namespace log4net.Layout +{ + /// + /// Layout that formats the log events as XML elements compatible with the log4j schema + /// + /// + /// + /// Formats the log events according to the http://logging.apache.org/log4j schema. + /// + /// + /// Nicko Cadell + public class XmlLayoutSchemaLog4j : XmlLayoutBase { - /// - /// The 1st of January 1970 in UTC. - /// + /// + /// The 1st of January 1970 in UTC + /// private static readonly DateTime s_date1970 = new DateTime(1970, 1, 1); /// - /// Initializes a new instance of the class. - /// Constructs an XMLLayoutSchemaLog4j. - /// - public XmlLayoutSchemaLog4j() - : base() - { + /// Constructs an XMLLayoutSchemaLog4j + /// + public XmlLayoutSchemaLog4j() : base() + { } /// - /// Initializes a new instance of the class. - /// Constructs an XMLLayoutSchemaLog4j. - /// - /// - /// - /// The LocationInfo option takes a boolean value. By - /// default, it is set to false which means there will be no location - /// information output by this layout. If the the option is set to - /// true, then the file name and line number of the statement - /// at the origin of the log statement will be output. - /// - /// - /// If you are embedding this layout within an SMTPAppender - /// then make sure to set the LocationInfo option of that - /// appender as well. - /// - /// - public XmlLayoutSchemaLog4j(bool locationInfo) - : base(locationInfo) - { + /// Constructs an XMLLayoutSchemaLog4j. + /// + /// + /// + /// The LocationInfo option takes a boolean value. By + /// default, it is set to false which means there will be no location + /// information output by this layout. If the the option is set to + /// true, then the file name and line number of the statement + /// at the origin of the log statement will be output. + /// + /// + /// If you are embedding this layout within an SMTPAppender + /// then make sure to set the LocationInfo option of that + /// appender as well. + /// + /// + public XmlLayoutSchemaLog4j(bool locationInfo) : base(locationInfo) + { } - /// - /// Gets or sets the version of the log4j schema to use. - /// - /// - /// - /// Only version 1.2 of the log4j schema is supported. - /// - /// - public string Version - { - get { return "1.2"; } - - set - { - if (value != "1.2") - { - throw new ArgumentException("Only version 1.2 of the log4j schema is currently supported"); - } - } + /// + /// The version of the log4j schema to use. + /// + /// + /// + /// Only version 1.2 of the log4j schema is supported. + /// + /// + public string Version + { + get { return "1.2"; } + set + { + if (value != "1.2") + { + throw new ArgumentException("Only version 1.2 of the log4j schema is currently supported"); + } + } } - /* Example log4j schema event - - - - - - - - - - - - - - - + /* Example log4j schema event + + + + + + + + + + + + + + + */ /* Since log4j 1.3 the log4j:MDC has been combined into the log4j:properties element */ - /// - /// Actually do the writing of the xml. - /// - /// the writer to use. - /// the event to write. - /// - /// - /// Generate XML that is compatible with the log4j schema. - /// - /// - protected override void FormatXml(XmlWriter writer, LoggingEvent loggingEvent) - { - // Translate logging events for log4j - - // Translate hostname property - if (loggingEvent.LookupProperty(LoggingEvent.HostNameProperty) != null && - loggingEvent.LookupProperty("log4jmachinename") == null) - { - loggingEvent.GetProperties()["log4jmachinename"] = loggingEvent.LookupProperty(LoggingEvent.HostNameProperty); - } - - // translate appdomain name - if (loggingEvent.LookupProperty("log4japp") == null && - loggingEvent.Domain != null && - loggingEvent.Domain.Length > 0) - { - loggingEvent.GetProperties()["log4japp"] = loggingEvent.Domain; - } - - // translate identity name - if (loggingEvent.Identity != null && - loggingEvent.Identity.Length > 0 && - loggingEvent.LookupProperty(LoggingEvent.IdentityProperty) == null) - { - loggingEvent.GetProperties()[LoggingEvent.IdentityProperty] = loggingEvent.Identity; - } - - // translate user name - if (loggingEvent.UserName != null && - loggingEvent.UserName.Length > 0 && - loggingEvent.LookupProperty(LoggingEvent.UserNameProperty) == null) - { - loggingEvent.GetProperties()[LoggingEvent.UserNameProperty] = loggingEvent.UserName; - } - - // Write the start element - writer.WriteStartElement("log4j:event"); - writer.WriteAttributeString("logger", loggingEvent.LoggerName); - - // Calculate the timestamp as the number of milliseconds since january 1970 - // - // We must convert the TimeStamp to UTC before performing any mathematical - // operations. This allows use to take into account discontinuities - // caused by daylight savings time transitions. - TimeSpan timeSince1970 = loggingEvent.TimeStampUtc - s_date1970; - - writer.WriteAttributeString("timestamp", XmlConvert.ToString((long)timeSince1970.TotalMilliseconds)); - writer.WriteAttributeString("level", loggingEvent.Level.DisplayName); - writer.WriteAttributeString("thread", loggingEvent.ThreadName); - - // Append the message text - writer.WriteStartElement("log4j:message"); - Transform.WriteEscapedXmlString(writer, loggingEvent.RenderedMessage, this.InvalidCharReplacement); - writer.WriteEndElement(); - - object ndcObj = loggingEvent.LookupProperty("NDC"); - if (ndcObj != null) - { - string valueStr = loggingEvent.Repository.RendererMap.FindAndRender(ndcObj); - - if (valueStr != null && valueStr.Length > 0) - { - // Append the NDC text - writer.WriteStartElement("log4j:NDC"); - Transform.WriteEscapedXmlString(writer, valueStr, this.InvalidCharReplacement); - writer.WriteEndElement(); - } - } - - // Append the properties text - PropertiesDictionary properties = loggingEvent.GetProperties(); - if (properties.Count > 0) - { - writer.WriteStartElement("log4j:properties"); - foreach (System.Collections.DictionaryEntry entry in properties) - { - writer.WriteStartElement("log4j:data"); - writer.WriteAttributeString("name", (string)entry.Key); - - // Use an ObjectRenderer to convert the object to a string - string valueStr = loggingEvent.Repository.RendererMap.FindAndRender(entry.Value); - writer.WriteAttributeString("value", valueStr); - - writer.WriteEndElement(); - } - - writer.WriteEndElement(); - } - - string exceptionStr = loggingEvent.GetExceptionString(); - if (exceptionStr != null && exceptionStr.Length > 0) - { - // Append the stack trace line - writer.WriteStartElement("log4j:throwable"); - Transform.WriteEscapedXmlString(writer, exceptionStr, this.InvalidCharReplacement); - writer.WriteEndElement(); - } - - if (this.LocationInfo) - { - LocationInfo locationInfo = loggingEvent.LocationInformation; - - writer.WriteStartElement("log4j:locationInfo"); - writer.WriteAttributeString("class", locationInfo.ClassName); - writer.WriteAttributeString("method", locationInfo.MethodName); - writer.WriteAttributeString("file", locationInfo.FileName); - writer.WriteAttributeString("line", locationInfo.LineNumber); - writer.WriteEndElement(); - } - - writer.WriteEndElement(); - } - } + /// + /// Actually do the writing of the xml + /// + /// the writer to use + /// the event to write + /// + /// + /// Generate XML that is compatible with the log4j schema. + /// + /// + protected override void FormatXml(XmlWriter writer, LoggingEvent loggingEvent) + { + // Translate logging events for log4j + + // Translate hostname property + if (loggingEvent.LookupProperty(LoggingEvent.HostNameProperty) != null && + loggingEvent.LookupProperty("log4jmachinename") == null) + { + loggingEvent.GetProperties()["log4jmachinename"] = loggingEvent.LookupProperty(LoggingEvent.HostNameProperty); + } + + // translate appdomain name + if (loggingEvent.LookupProperty("log4japp") == null && + loggingEvent.Domain != null && + loggingEvent.Domain.Length > 0) + { + loggingEvent.GetProperties()["log4japp"] = loggingEvent.Domain; + } + + // translate identity name + if (loggingEvent.Identity != null && + loggingEvent.Identity.Length > 0 && + loggingEvent.LookupProperty(LoggingEvent.IdentityProperty) == null) + { + loggingEvent.GetProperties()[LoggingEvent.IdentityProperty] = loggingEvent.Identity; + } + + // translate user name + if (loggingEvent.UserName != null && + loggingEvent.UserName.Length > 0 && + loggingEvent.LookupProperty(LoggingEvent.UserNameProperty) == null) + { + loggingEvent.GetProperties()[LoggingEvent.UserNameProperty] = loggingEvent.UserName; + } + + // Write the start element + writer.WriteStartElement("log4j", "event", "log4net"); + writer.WriteAttributeString("logger", loggingEvent.LoggerName); + + // Calculate the timestamp as the number of milliseconds since january 1970 + // + // We must convert the TimeStamp to UTC before performing any mathematical + // operations. This allows use to take into account discontinuities + // caused by daylight savings time transitions. + TimeSpan timeSince1970 = loggingEvent.TimeStampUtc - s_date1970; + + writer.WriteAttributeString("timestamp", XmlConvert.ToString((long)timeSince1970.TotalMilliseconds)); + writer.WriteAttributeString("level", loggingEvent.Level.DisplayName); + writer.WriteAttributeString("thread", loggingEvent.ThreadName); + + // Append the message text + writer.WriteStartElement("log4j", "message", "log4net"); + Transform.WriteEscapedXmlString(writer, loggingEvent.RenderedMessage,this.InvalidCharReplacement); + writer.WriteEndElement(); + + object ndcObj = loggingEvent.LookupProperty("NDC"); + if (ndcObj != null) + { + string valueStr = loggingEvent.Repository.RendererMap.FindAndRender(ndcObj); + + if (valueStr != null && valueStr.Length > 0) + { + // Append the NDC text + writer.WriteStartElement("log4j", "NDC", "log4net"); + Transform.WriteEscapedXmlString(writer, valueStr,this.InvalidCharReplacement); + writer.WriteEndElement(); + } + } + + // Append the properties text + PropertiesDictionary properties = loggingEvent.GetProperties(); + if (properties.Count > 0) + { + writer.WriteStartElement("log4j", "properties", "log4net"); + foreach(System.Collections.DictionaryEntry entry in properties) + { + writer.WriteStartElement("log4j", "data", "log4net"); + writer.WriteAttributeString("name", (string)entry.Key); + + // Use an ObjectRenderer to convert the object to a string + string valueStr = loggingEvent.Repository.RendererMap.FindAndRender(entry.Value); + writer.WriteAttributeString("value", valueStr); + + writer.WriteEndElement(); + } + writer.WriteEndElement(); + } + + string exceptionStr = loggingEvent.GetExceptionString(); + if (exceptionStr != null && exceptionStr.Length > 0) + { + // Append the stack trace line + writer.WriteStartElement("log4j", "throwable", "log4net"); + Transform.WriteEscapedXmlString(writer, exceptionStr,this.InvalidCharReplacement); + writer.WriteEndElement(); + } + + if (this.LocationInfo) + { + LocationInfo locationInfo = loggingEvent.LocationInformation; + + writer.WriteStartElement("log4j", "locationInfo", "log4net"); + writer.WriteAttributeString("class", locationInfo.ClassName); + writer.WriteAttributeString("method", locationInfo.MethodName); + writer.WriteAttributeString("file", locationInfo.FileName); + writer.WriteAttributeString("line", locationInfo.LineNumber); + writer.WriteEndElement(); + } + + writer.WriteEndElement(); + } + } } + diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Log4netAssemblyInfo.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Log4netAssemblyInfo.cs index 9dc18fb784b..78f1a0121d1 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Log4netAssemblyInfo.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Log4netAssemblyInfo.cs @@ -1,7 +1,3 @@ -// -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See LICENSE file in the project root for full license information. -// #region Apache License // // Licensed to the Apache Software Foundation (ASF) under one or more @@ -29,7 +25,7 @@ namespace log4net { /// public sealed class AssemblyInfo { /// Version of the assembly - public const string Version = "2.0.8"; + public const string Version = "2.0.9"; /// Version of the framework targeted #if NET_1_1 @@ -63,6 +59,8 @@ public sealed class AssemblyInfo { public const string TargetFramework = "Mono"; #elif SSCLI public const string TargetFramework = "Shared Source CLI"; +#elif NETSTANDARD1_3 + public const string TargetFramework = ".NET Core"; #else public const string TargetFramework = "Unknown"; #endif diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/LogManager.cs b/DNN Platform/DotNetNuke.Log4net/log4net/LogManager.cs index 24e04f7697f..f3f64f1f6a9 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/LogManager.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/LogManager.cs @@ -1,810 +1,808 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; - using System.Reflection; - - using log4net.Core; - using log4net.Repository; - - /// - /// This class is used by client applications to request logger instances. - /// - /// - /// - /// This class has static methods that are used by a client to request - /// a logger instance. The method is - /// used to retrieve a logger. - /// - /// - /// See the interface for more details. - /// - /// - /// Simple example of logging messages. - /// - /// ILog log = LogManager.GetLogger("application-log"); - /// - /// log.Info("Application Start"); - /// log.Debug("This is a debug message"); - /// - /// if (log.IsDebugEnabled) - /// { - /// log.Debug("This is another debug message"); - /// } - /// - /// - /// - /// - /// Nicko Cadell. - /// Gert Driesen. - public sealed class LogManager +using System; +using System.Reflection; + +using log4net.Core; +using log4net.Repository; + +namespace log4net +{ + /// + /// This class is used by client applications to request logger instances. + /// + /// + /// + /// This class has static methods that are used by a client to request + /// a logger instance. The method is + /// used to retrieve a logger. + /// + /// + /// See the interface for more details. + /// + /// + /// Simple example of logging messages + /// + /// ILog log = LogManager.GetLogger("application-log"); + /// + /// log.Info("Application Start"); + /// log.Debug("This is a debug message"); + /// + /// if (log.IsDebugEnabled) + /// { + /// log.Debug("This is another debug message"); + /// } + /// + /// + /// + /// + /// Nicko Cadell + /// Gert Driesen + public sealed class LogManager { - /// - /// Initializes a new instance of the class. - /// - /// - /// Uses a private access modifier to prevent instantiation of this class. - /// - private LogManager() - { - } - -#if !NETSTANDARD1_3 // Excluded because GetCallingAssembly() is not available in CoreFX (https://github.com/dotnet/corefx/issues/2221). - /// Returns the named logger if it exists. - /// - /// Returns the named logger if it exists. - /// - /// - /// - /// If the named logger exists (in the default repository) then it - /// returns a reference to the logger, otherwise it returns null. - /// - /// - /// The fully qualified logger name to look for. - /// The logger found, or null if no logger could be found. - public static ILog Exists(string name) - { - return Exists(Assembly.GetCallingAssembly(), name); - } - - /// Get the currently defined loggers. - /// - /// Returns all the currently defined loggers in the default repository. - /// - /// - /// The root logger is not included in the returned array. - /// - /// All the defined loggers. - public static ILog[] GetCurrentLoggers() - { - return GetCurrentLoggers(Assembly.GetCallingAssembly()); - } - - /// Get or create a logger. - /// - /// Retrieves or creates a named logger. - /// - /// - /// - /// Retrieves a logger named as the - /// parameter. If the named logger already exists, then the - /// existing instance will be returned. Otherwise, a new instance is - /// created. - /// - /// By default, loggers do not have a set level but inherit - /// it from the hierarchy. This is one of the central features of - /// log4net. - /// - /// - /// The name of the logger to retrieve. - /// The logger with the name specified. - public static ILog GetLogger(string name) - { - return GetLogger(Assembly.GetCallingAssembly(), name); - } -#endif // !NETSTANDARD1_3 - - /// - /// Returns the named logger if it exists. - /// - /// - /// - /// If the named logger exists (in the specified repository) then it - /// returns a reference to the logger, otherwise it returns - /// null. - /// - /// - /// The repository to lookup in. - /// The fully qualified logger name to look for. - /// - /// The logger found, or null if the logger doesn't exist in the specified - /// repository. - /// - public static ILog Exists(string repository, string name) - { - return WrapLogger(LoggerManager.Exists(repository, name)); - } - - /// - /// Returns the named logger if it exists. - /// - /// - /// - /// If the named logger exists (in the repository for the specified assembly) then it - /// returns a reference to the logger, otherwise it returns - /// null. - /// - /// - /// The assembly to use to lookup the repository. - /// The fully qualified logger name to look for. - /// - /// The logger, or null if the logger doesn't exist in the specified - /// assembly's repository. - /// - public static ILog Exists(Assembly repositoryAssembly, string name) - { - return WrapLogger(LoggerManager.Exists(repositoryAssembly, name)); - } - - /// - /// Returns all the currently defined loggers in the specified repository. - /// - /// The repository to lookup in. - /// - /// The root logger is not included in the returned array. - /// - /// All the defined loggers. - public static ILog[] GetCurrentLoggers(string repository) - { - return WrapLoggers(LoggerManager.GetCurrentLoggers(repository)); - } - - /// - /// Returns all the currently defined loggers in the specified assembly's repository. - /// - /// The assembly to use to lookup the repository. - /// - /// The root logger is not included in the returned array. - /// - /// All the defined loggers. - public static ILog[] GetCurrentLoggers(Assembly repositoryAssembly) - { - return WrapLoggers(LoggerManager.GetCurrentLoggers(repositoryAssembly)); - } - - /// - /// Retrieves or creates a named logger. - /// - /// - /// - /// Retrieve a logger named as the - /// parameter. If the named logger already exists, then the - /// existing instance will be returned. Otherwise, a new instance is - /// created. - /// - /// - /// By default, loggers do not have a set level but inherit - /// it from the hierarchy. This is one of the central features of - /// log4net. - /// - /// - /// The repository to lookup in. - /// The name of the logger to retrieve. - /// The logger with the name specified. - public static ILog GetLogger(string repository, string name) - { - return WrapLogger(LoggerManager.GetLogger(repository, name)); - } - - /// - /// Retrieves or creates a named logger. - /// - /// - /// - /// Retrieve a logger named as the - /// parameter. If the named logger already exists, then the - /// existing instance will be returned. Otherwise, a new instance is - /// created. - /// - /// - /// By default, loggers do not have a set level but inherit - /// it from the hierarchy. This is one of the central features of - /// log4net. - /// - /// - /// The assembly to use to lookup the repository. - /// The name of the logger to retrieve. - /// The logger with the name specified. - public static ILog GetLogger(Assembly repositoryAssembly, string name) - { - return WrapLogger(LoggerManager.GetLogger(repositoryAssembly, name)); - } - - /// - /// Shorthand for . - /// - /// - /// Get the logger for the fully qualified name of the type specified. - /// - /// The full name of will be used as the name of the logger to retrieve. - /// The logger with the name specified. - public static ILog GetLogger(Type type) - { -#if NETSTANDARD1_3 - return GetLogger(type.GetTypeInfo().Assembly, type.FullName); -#else - return GetLogger(Assembly.GetCallingAssembly(), type.FullName); -#endif - } - - /// - /// Shorthand for . - /// - /// - /// Gets the logger for the fully qualified name of the type specified. - /// - /// The repository to lookup in. - /// The full name of will be used as the name of the logger to retrieve. - /// The logger with the name specified. - public static ILog GetLogger(string repository, Type type) - { - return WrapLogger(LoggerManager.GetLogger(repository, type)); - } - - /// - /// Shorthand for . - /// - /// - /// Gets the logger for the fully qualified name of the type specified. - /// - /// The assembly to use to lookup the repository. - /// The full name of will be used as the name of the logger to retrieve. - /// The logger with the name specified. - public static ILog GetLogger(Assembly repositoryAssembly, Type type) - { - return WrapLogger(LoggerManager.GetLogger(repositoryAssembly, type)); - } - - /// - /// Shuts down the log4net system. - /// - /// - /// - /// Calling this method will safely close and remove all - /// appenders in all the loggers including root contained in all the - /// default repositories. - /// - /// - /// Some appenders need to be closed before the application exists. - /// Otherwise, pending logging events might be lost. - /// - /// The shutdown method is careful to close nested - /// appenders before closing regular appenders. This is allows - /// configurations where a regular appender is attached to a logger - /// and again to a nested appender. - /// - /// - public static void Shutdown() - { - LoggerManager.Shutdown(); - } - -#if !NETSTANDARD1_3 - /// Shutdown a logger repository. - /// - /// Shuts down the default repository. - /// - /// - /// - /// Calling this method will safely close and remove all - /// appenders in all the loggers including root contained in the - /// default repository. - /// - /// Some appenders need to be closed before the application exists. - /// Otherwise, pending logging events might be lost. - /// - /// The shutdown method is careful to close nested - /// appenders before closing regular appenders. This is allows - /// configurations where a regular appender is attached to a logger - /// and again to a nested appender. - /// - /// - public static void ShutdownRepository() - { - ShutdownRepository(Assembly.GetCallingAssembly()); - } - -#endif - - /// - /// Shuts down the repository for the repository specified. - /// - /// - /// - /// Calling this method will safely close and remove all - /// appenders in all the loggers including root contained in the - /// specified. - /// - /// - /// Some appenders need to be closed before the application exists. - /// Otherwise, pending logging events might be lost. - /// - /// The shutdown method is careful to close nested - /// appenders before closing regular appenders. This is allows - /// configurations where a regular appender is attached to a logger - /// and again to a nested appender. - /// - /// - /// The repository to shutdown. - public static void ShutdownRepository(string repository) - { - LoggerManager.ShutdownRepository(repository); - } - - /// - /// Shuts down the repository specified. - /// - /// - /// - /// Calling this method will safely close and remove all - /// appenders in all the loggers including root contained in the - /// repository. The repository is looked up using - /// the specified. - /// - /// - /// Some appenders need to be closed before the application exists. - /// Otherwise, pending logging events might be lost. - /// - /// - /// The shutdown method is careful to close nested - /// appenders before closing regular appenders. This is allows - /// configurations where a regular appender is attached to a logger - /// and again to a nested appender. - /// - /// - /// The assembly to use to lookup the repository. - public static void ShutdownRepository(Assembly repositoryAssembly) - { - LoggerManager.ShutdownRepository(repositoryAssembly); - } - -#if !NETSTANDARD1_3 - /// Reset the configuration of a repository. - /// - /// Resets all values contained in this repository instance to their defaults. - /// - /// - /// - /// Resets all values contained in the repository instance to their - /// defaults. This removes all appenders from all loggers, sets - /// the level of all non-root loggers to null, - /// sets their additivity flag to true and sets the level - /// of the root logger to . Moreover, - /// message disabling is set to its default "off" value. - /// - /// - public static void ResetConfiguration() - { - ResetConfiguration(Assembly.GetCallingAssembly()); - } -#endif - - /// - /// Resets all values contained in this repository instance to their defaults. - /// - /// - /// - /// Reset all values contained in the repository instance to their - /// defaults. This removes all appenders from all loggers, sets - /// the level of all non-root loggers to null, - /// sets their additivity flag to true and sets the level - /// of the root logger to . Moreover, - /// message disabling is set to its default "off" value. - /// - /// - /// The repository to reset. - public static void ResetConfiguration(string repository) - { - LoggerManager.ResetConfiguration(repository); - } - - /// - /// Resets all values contained in this repository instance to their defaults. - /// - /// - /// - /// Reset all values contained in the repository instance to their - /// defaults. This removes all appenders from all loggers, sets - /// the level of all non-root loggers to null, - /// sets their additivity flag to true and sets the level - /// of the root logger to . Moreover, - /// message disabling is set to its default "off" value. - /// - /// - /// The assembly to use to lookup the repository to reset. - public static void ResetConfiguration(Assembly repositoryAssembly) - { - LoggerManager.ResetConfiguration(repositoryAssembly); - } - -#if !NETSTANDARD1_3 - /// Get the logger repository. - /// - /// Returns the default instance. - /// - /// - /// - /// Gets the for the repository specified - /// by the callers assembly (). - /// - /// - /// The instance for the default repository. - [Obsolete("Use GetRepository instead of GetLoggerRepository. Scheduled removal in v10.0.0.")] - public static ILoggerRepository GetLoggerRepository() - { - return GetRepository(Assembly.GetCallingAssembly()); - } -#endif - - /// - /// Returns the default instance. - /// - /// The default instance. - /// - /// - /// Gets the for the repository specified - /// by the argument. - /// - /// - /// The repository to lookup in. - [Obsolete("Use GetRepository instead of GetLoggerRepository. Scheduled removal in v10.0.0.")] - public static ILoggerRepository GetLoggerRepository(string repository) - { - return GetRepository(repository); - } - - /// - /// Returns the default instance. - /// - /// The default instance. - /// - /// - /// Gets the for the repository specified - /// by the argument. - /// - /// - /// The assembly to use to lookup the repository. - [Obsolete("Use GetRepository instead of GetLoggerRepository. Scheduled removal in v10.0.0.")] - public static ILoggerRepository GetLoggerRepository(Assembly repositoryAssembly) - { - return GetRepository(repositoryAssembly); - } - -#if !NETSTANDARD1_3 - /// Get a logger repository. - /// - /// Returns the default instance. - /// - /// - /// - /// Gets the for the repository specified - /// by the callers assembly (). - /// - /// - /// The instance for the default repository. - public static ILoggerRepository GetRepository() - { - return GetRepository(Assembly.GetCallingAssembly()); - } -#endif - - /// - /// Returns the default instance. - /// - /// The default instance. - /// - /// - /// Gets the for the repository specified - /// by the argument. - /// - /// - /// The repository to lookup in. - public static ILoggerRepository GetRepository(string repository) - { - return LoggerManager.GetRepository(repository); - } - - /// - /// Returns the default instance. - /// - /// The default instance. - /// - /// - /// Gets the for the repository specified - /// by the argument. - /// - /// - /// The assembly to use to lookup the repository. - public static ILoggerRepository GetRepository(Assembly repositoryAssembly) - { - return LoggerManager.GetRepository(repositoryAssembly); - } - -#if !NETSTANDARD1_3 - /// Create a domain. - /// - /// Creates a repository with the specified repository type. - /// - /// - /// - /// CreateDomain is obsolete. Use CreateRepository instead of CreateDomain. - /// - /// - /// The created will be associated with the repository - /// specified such that a call to will return - /// the same repository instance. - /// - /// - /// A that implements - /// and has a no arg constructor. An instance of this type will be created to act - /// as the for the repository specified. - /// The created for the repository. - [Obsolete("Use CreateRepository instead of CreateDomain. Scheduled removal in v10.0.0.")] - public static ILoggerRepository CreateDomain(Type repositoryType) - { - return CreateRepository(Assembly.GetCallingAssembly(), repositoryType); - } - - /// Create a logger repository. - /// - /// Creates a repository with the specified repository type. - /// - /// A that implements - /// and has a no arg constructor. An instance of this type will be created to act - /// as the for the repository specified. - /// The created for the repository. - /// - /// - /// The created will be associated with the repository - /// specified such that a call to will return - /// the same repository instance. - /// - /// - public static ILoggerRepository CreateRepository(Type repositoryType) - { - return CreateRepository(Assembly.GetCallingAssembly(), repositoryType); - } -#endif - - /// - /// Creates a repository with the specified name. - /// - /// - /// - /// CreateDomain is obsolete. Use CreateRepository instead of CreateDomain. - /// - /// - /// Creates the default type of which is a - /// object. - /// - /// - /// The name must be unique. Repositories cannot be redefined. - /// An will be thrown if the repository already exists. - /// - /// - /// The name of the repository, this must be unique amongst repositories. - /// The created for the repository. - /// The specified repository already exists. - [Obsolete("Use CreateRepository instead of CreateDomain. Scheduled removal in v11.0.0.")] - public static ILoggerRepository CreateDomain(string repository) - { - return LoggerManager.CreateRepository(repository); - } - - /// - /// Creates a repository with the specified name. - /// - /// - /// - /// Creates the default type of which is a - /// object. - /// - /// - /// The name must be unique. Repositories cannot be redefined. - /// An will be thrown if the repository already exists. - /// - /// - /// The name of the repository, this must be unique amongst repositories. - /// The created for the repository. - /// The specified repository already exists. - public static ILoggerRepository CreateRepository(string repository) - { - return LoggerManager.CreateRepository(repository); - } - - /// - /// Creates a repository with the specified name and repository type. - /// - /// - /// - /// CreateDomain is obsolete. Use CreateRepository instead of CreateDomain. - /// - /// - /// The name must be unique. Repositories cannot be redefined. - /// An will be thrown if the repository already exists. - /// - /// - /// The name of the repository, this must be unique to the repository. - /// A that implements - /// and has a no arg constructor. An instance of this type will be created to act - /// as the for the repository specified. - /// The created for the repository. - /// The specified repository already exists. - [Obsolete("Use CreateRepository instead of CreateDomain. Scheduled removal in v10.0.0.")] - public static ILoggerRepository CreateDomain(string repository, Type repositoryType) - { - return LoggerManager.CreateRepository(repository, repositoryType); - } - - /// - /// Creates a repository with the specified name and repository type. - /// - /// - /// - /// The name must be unique. Repositories cannot be redefined. - /// An will be thrown if the repository already exists. - /// - /// - /// The name of the repository, this must be unique to the repository. - /// A that implements - /// and has a no arg constructor. An instance of this type will be created to act - /// as the for the repository specified. - /// The created for the repository. - /// The specified repository already exists. - public static ILoggerRepository CreateRepository(string repository, Type repositoryType) - { - return LoggerManager.CreateRepository(repository, repositoryType); - } - - /// - /// Creates a repository for the specified assembly and repository type. - /// - /// - /// - /// CreateDomain is obsolete. Use CreateRepository instead of CreateDomain. - /// - /// - /// The created will be associated with the repository - /// specified such that a call to with the - /// same assembly specified will return the same repository instance. - /// - /// - /// The assembly to use to get the name of the repository. - /// A that implements - /// and has a no arg constructor. An instance of this type will be created to act - /// as the for the repository specified. - /// The created for the repository. - [Obsolete("Use CreateRepository instead of CreateDomain. Scheduled removal in v10.0.0.")] - public static ILoggerRepository CreateDomain(Assembly repositoryAssembly, Type repositoryType) - { - return LoggerManager.CreateRepository(repositoryAssembly, repositoryType); - } - - /// - /// Creates a repository for the specified assembly and repository type. - /// - /// - /// - /// The created will be associated with the repository - /// specified such that a call to with the - /// same assembly specified will return the same repository instance. - /// - /// - /// The assembly to use to get the name of the repository. - /// A that implements - /// and has a no arg constructor. An instance of this type will be created to act - /// as the for the repository specified. - /// The created for the repository. - public static ILoggerRepository CreateRepository(Assembly repositoryAssembly, Type repositoryType) - { - return LoggerManager.CreateRepository(repositoryAssembly, repositoryType); - } - - /// - /// Gets the list of currently defined repositories. - /// - /// - /// - /// Get an array of all the objects that have been created. - /// - /// - /// An array of all the known objects. - public static ILoggerRepository[] GetAllRepositories() - { - return LoggerManager.GetAllRepositories(); - } - - /// - /// Flushes logging events buffered in all configured appenders in the default repository. - /// - /// The maximum time in milliseconds to wait for logging events from asycnhronous appenders to be flushed. - /// True if all logging events were flushed successfully, else false. - public static bool Flush(int millisecondsTimeout) - { -#if !NETSTANDARD1_3 // Excluded because GetCallingAssembly() is not available in CoreFX (https://github.com/dotnet/corefx/issues/2221). - Appender.IFlushable flushableRepository = LoggerManager.GetRepository(Assembly.GetCallingAssembly()) as Appender.IFlushable; - if (flushableRepository == null) + /// + /// Initializes a new instance of the class. + /// + /// + /// Uses a private access modifier to prevent instantiation of this class. + /// + private LogManager() + { + } + +#if !NETSTANDARD1_3 // Excluded because GetCallingAssembly() is not available in CoreFX (https://github.com/dotnet/corefx/issues/2221). + /// Returns the named logger if it exists. + /// + /// Returns the named logger if it exists. + /// + /// + /// + /// If the named logger exists (in the default repository) then it + /// returns a reference to the logger, otherwise it returns null. + /// + /// + /// The fully qualified logger name to look for. + /// The logger found, or null if no logger could be found. + public static ILog Exists(string name) + { + return Exists(Assembly.GetCallingAssembly(), name); + } + + /// Get the currently defined loggers. + /// + /// Returns all the currently defined loggers in the default repository. + /// + /// + /// The root logger is not included in the returned array. + /// + /// All the defined loggers. + public static ILog[] GetCurrentLoggers() + { + return GetCurrentLoggers(Assembly.GetCallingAssembly()); + } + + /// Get or create a logger. + /// + /// Retrieves or creates a named logger. + /// + /// + /// + /// Retrieves a logger named as the + /// parameter. If the named logger already exists, then the + /// existing instance will be returned. Otherwise, a new instance is + /// created. + /// + /// By default, loggers do not have a set level but inherit + /// it from the hierarchy. This is one of the central features of + /// log4net. + /// + /// + /// The name of the logger to retrieve. + /// The logger with the name specified. + public static ILog GetLogger(string name) + { + return GetLogger(Assembly.GetCallingAssembly(), name); + } +#endif // !NETSTANDARD1_3 + + /// + /// Returns the named logger if it exists. + /// + /// + /// + /// If the named logger exists (in the specified repository) then it + /// returns a reference to the logger, otherwise it returns + /// null. + /// + /// + /// The repository to lookup in. + /// The fully qualified logger name to look for. + /// + /// The logger found, or null if the logger doesn't exist in the specified + /// repository. + /// + public static ILog Exists(string repository, string name) + { + return WrapLogger(LoggerManager.Exists(repository, name)); + } + + /// + /// Returns the named logger if it exists. + /// + /// + /// + /// If the named logger exists (in the repository for the specified assembly) then it + /// returns a reference to the logger, otherwise it returns + /// null. + /// + /// + /// The assembly to use to lookup the repository. + /// The fully qualified logger name to look for. + /// + /// The logger, or null if the logger doesn't exist in the specified + /// assembly's repository. + /// + public static ILog Exists(Assembly repositoryAssembly, string name) + { + return WrapLogger(LoggerManager.Exists(repositoryAssembly, name)); + } + + /// + /// Returns all the currently defined loggers in the specified repository. + /// + /// The repository to lookup in. + /// + /// The root logger is not included in the returned array. + /// + /// All the defined loggers. + public static ILog[] GetCurrentLoggers(string repository) + { + return WrapLoggers(LoggerManager.GetCurrentLoggers(repository)); + } + + /// + /// Returns all the currently defined loggers in the specified assembly's repository. + /// + /// The assembly to use to lookup the repository. + /// + /// The root logger is not included in the returned array. + /// + /// All the defined loggers. + public static ILog[] GetCurrentLoggers(Assembly repositoryAssembly) + { + return WrapLoggers(LoggerManager.GetCurrentLoggers(repositoryAssembly)); + } + + /// + /// Retrieves or creates a named logger. + /// + /// + /// + /// Retrieve a logger named as the + /// parameter. If the named logger already exists, then the + /// existing instance will be returned. Otherwise, a new instance is + /// created. + /// + /// + /// By default, loggers do not have a set level but inherit + /// it from the hierarchy. This is one of the central features of + /// log4net. + /// + /// + /// The repository to lookup in. + /// The name of the logger to retrieve. + /// The logger with the name specified. + public static ILog GetLogger(string repository, string name) + { + return WrapLogger(LoggerManager.GetLogger(repository, name)); + } + + /// + /// Retrieves or creates a named logger. + /// + /// + /// + /// Retrieve a logger named as the + /// parameter. If the named logger already exists, then the + /// existing instance will be returned. Otherwise, a new instance is + /// created. + /// + /// + /// By default, loggers do not have a set level but inherit + /// it from the hierarchy. This is one of the central features of + /// log4net. + /// + /// + /// The assembly to use to lookup the repository. + /// The name of the logger to retrieve. + /// The logger with the name specified. + public static ILog GetLogger(Assembly repositoryAssembly, string name) + { + return WrapLogger(LoggerManager.GetLogger(repositoryAssembly, name)); + } + + /// + /// Shorthand for . + /// + /// + /// Get the logger for the fully qualified name of the type specified. + /// + /// The full name of will be used as the name of the logger to retrieve. + /// The logger with the name specified. + public static ILog GetLogger(Type type) + { +#if NETSTANDARD1_3 + return GetLogger(type.GetTypeInfo().Assembly, type.FullName); +#else + return GetLogger(Assembly.GetCallingAssembly(), type.FullName); +#endif + } + + /// + /// Shorthand for . + /// + /// + /// Gets the logger for the fully qualified name of the type specified. + /// + /// The repository to lookup in. + /// The full name of will be used as the name of the logger to retrieve. + /// The logger with the name specified. + public static ILog GetLogger(string repository, Type type) + { + return WrapLogger(LoggerManager.GetLogger(repository, type)); + } + + /// + /// Shorthand for . + /// + /// + /// Gets the logger for the fully qualified name of the type specified. + /// + /// The assembly to use to lookup the repository. + /// The full name of will be used as the name of the logger to retrieve. + /// The logger with the name specified. + public static ILog GetLogger(Assembly repositoryAssembly, Type type) + { + return WrapLogger(LoggerManager.GetLogger(repositoryAssembly, type)); + } + + /// + /// Shuts down the log4net system. + /// + /// + /// + /// Calling this method will safely close and remove all + /// appenders in all the loggers including root contained in all the + /// default repositories. + /// + /// + /// Some appenders need to be closed before the application exists. + /// Otherwise, pending logging events might be lost. + /// + /// The shutdown method is careful to close nested + /// appenders before closing regular appenders. This is allows + /// configurations where a regular appender is attached to a logger + /// and again to a nested appender. + /// + /// + public static void Shutdown() + { + LoggerManager.Shutdown(); + } + +#if !NETSTANDARD1_3 + /// Shutdown a logger repository. + /// + /// Shuts down the default repository. + /// + /// + /// + /// Calling this method will safely close and remove all + /// appenders in all the loggers including root contained in the + /// default repository. + /// + /// Some appenders need to be closed before the application exists. + /// Otherwise, pending logging events might be lost. + /// + /// The shutdown method is careful to close nested + /// appenders before closing regular appenders. This is allows + /// configurations where a regular appender is attached to a logger + /// and again to a nested appender. + /// + /// + public static void ShutdownRepository() + { + ShutdownRepository(Assembly.GetCallingAssembly()); + } +#endif + + /// + /// Shuts down the repository for the repository specified. + /// + /// + /// + /// Calling this method will safely close and remove all + /// appenders in all the loggers including root contained in the + /// specified. + /// + /// + /// Some appenders need to be closed before the application exists. + /// Otherwise, pending logging events might be lost. + /// + /// The shutdown method is careful to close nested + /// appenders before closing regular appenders. This is allows + /// configurations where a regular appender is attached to a logger + /// and again to a nested appender. + /// + /// + /// The repository to shutdown. + public static void ShutdownRepository(string repository) + { + LoggerManager.ShutdownRepository(repository); + } + + /// + /// Shuts down the repository specified. + /// + /// + /// + /// Calling this method will safely close and remove all + /// appenders in all the loggers including root contained in the + /// repository. The repository is looked up using + /// the specified. + /// + /// + /// Some appenders need to be closed before the application exists. + /// Otherwise, pending logging events might be lost. + /// + /// + /// The shutdown method is careful to close nested + /// appenders before closing regular appenders. This is allows + /// configurations where a regular appender is attached to a logger + /// and again to a nested appender. + /// + /// + /// The assembly to use to lookup the repository. + public static void ShutdownRepository(Assembly repositoryAssembly) + { + LoggerManager.ShutdownRepository(repositoryAssembly); + } + +#if !NETSTANDARD1_3 + /// Reset the configuration of a repository + /// + /// Resets all values contained in this repository instance to their defaults. + /// + /// + /// + /// Resets all values contained in the repository instance to their + /// defaults. This removes all appenders from all loggers, sets + /// the level of all non-root loggers to null, + /// sets their additivity flag to true and sets the level + /// of the root logger to . Moreover, + /// message disabling is set to its default "off" value. + /// + /// + public static void ResetConfiguration() + { + ResetConfiguration(Assembly.GetCallingAssembly()); + } +#endif + + /// + /// Resets all values contained in this repository instance to their defaults. + /// + /// + /// + /// Reset all values contained in the repository instance to their + /// defaults. This removes all appenders from all loggers, sets + /// the level of all non-root loggers to null, + /// sets their additivity flag to true and sets the level + /// of the root logger to . Moreover, + /// message disabling is set to its default "off" value. + /// + /// + /// The repository to reset. + public static void ResetConfiguration(string repository) + { + LoggerManager.ResetConfiguration(repository); + } + + /// + /// Resets all values contained in this repository instance to their defaults. + /// + /// + /// + /// Reset all values contained in the repository instance to their + /// defaults. This removes all appenders from all loggers, sets + /// the level of all non-root loggers to null, + /// sets their additivity flag to true and sets the level + /// of the root logger to . Moreover, + /// message disabling is set to its default "off" value. + /// + /// + /// The assembly to use to lookup the repository to reset. + public static void ResetConfiguration(Assembly repositoryAssembly) + { + LoggerManager.ResetConfiguration(repositoryAssembly); + } + +#if !NETSTANDARD1_3 + /// Get the logger repository. + /// + /// Returns the default instance. + /// + /// + /// + /// Gets the for the repository specified + /// by the callers assembly (). + /// + /// + /// The instance for the default repository. + [Obsolete("Use GetRepository instead of GetLoggerRepository")] + public static ILoggerRepository GetLoggerRepository() + { + return GetRepository(Assembly.GetCallingAssembly()); + } +#endif + + /// + /// Returns the default instance. + /// + /// The default instance. + /// + /// + /// Gets the for the repository specified + /// by the argument. + /// + /// + /// The repository to lookup in. + [Obsolete("Use GetRepository instead of GetLoggerRepository")] + public static ILoggerRepository GetLoggerRepository(string repository) + { + return GetRepository(repository); + } + + /// + /// Returns the default instance. + /// + /// The default instance. + /// + /// + /// Gets the for the repository specified + /// by the argument. + /// + /// + /// The assembly to use to lookup the repository. + [Obsolete("Use GetRepository instead of GetLoggerRepository")] + public static ILoggerRepository GetLoggerRepository(Assembly repositoryAssembly) + { + return GetRepository(repositoryAssembly); + } + +#if !NETSTANDARD1_3 + /// Get a logger repository. + /// + /// Returns the default instance. + /// + /// + /// + /// Gets the for the repository specified + /// by the callers assembly (). + /// + /// + /// The instance for the default repository. + public static ILoggerRepository GetRepository() + { + return GetRepository(Assembly.GetCallingAssembly()); + } +#endif + + /// + /// Returns the default instance. + /// + /// The default instance. + /// + /// + /// Gets the for the repository specified + /// by the argument. + /// + /// + /// The repository to lookup in. + public static ILoggerRepository GetRepository(string repository) + { + return LoggerManager.GetRepository(repository); + } + + /// + /// Returns the default instance. + /// + /// The default instance. + /// + /// + /// Gets the for the repository specified + /// by the argument. + /// + /// + /// The assembly to use to lookup the repository. + public static ILoggerRepository GetRepository(Assembly repositoryAssembly) + { + return LoggerManager.GetRepository(repositoryAssembly); + } + +#if !NETSTANDARD1_3 + /// Create a domain + /// + /// Creates a repository with the specified repository type. + /// + /// + /// + /// CreateDomain is obsolete. Use CreateRepository instead of CreateDomain. + /// + /// + /// The created will be associated with the repository + /// specified such that a call to will return + /// the same repository instance. + /// + /// + /// A that implements + /// and has a no arg constructor. An instance of this type will be created to act + /// as the for the repository specified. + /// The created for the repository. + [Obsolete("Use CreateRepository instead of CreateDomain")] + public static ILoggerRepository CreateDomain(Type repositoryType) + { + return CreateRepository(Assembly.GetCallingAssembly(), repositoryType); + } + + /// Create a logger repository. + /// + /// Creates a repository with the specified repository type. + /// + /// A that implements + /// and has a no arg constructor. An instance of this type will be created to act + /// as the for the repository specified. + /// The created for the repository. + /// + /// + /// The created will be associated with the repository + /// specified such that a call to will return + /// the same repository instance. + /// + /// + public static ILoggerRepository CreateRepository(Type repositoryType) + { + return CreateRepository(Assembly.GetCallingAssembly(), repositoryType); + } +#endif + + /// + /// Creates a repository with the specified name. + /// + /// + /// + /// CreateDomain is obsolete. Use CreateRepository instead of CreateDomain. + /// + /// + /// Creates the default type of which is a + /// object. + /// + /// + /// The name must be unique. Repositories cannot be redefined. + /// An will be thrown if the repository already exists. + /// + /// + /// The name of the repository, this must be unique amongst repositories. + /// The created for the repository. + /// The specified repository already exists. + [Obsolete("Use CreateRepository instead of CreateDomain")] + public static ILoggerRepository CreateDomain(string repository) + { + return LoggerManager.CreateRepository(repository); + } + + /// + /// Creates a repository with the specified name. + /// + /// + /// + /// Creates the default type of which is a + /// object. + /// + /// + /// The name must be unique. Repositories cannot be redefined. + /// An will be thrown if the repository already exists. + /// + /// + /// The name of the repository, this must be unique amongst repositories. + /// The created for the repository. + /// The specified repository already exists. + public static ILoggerRepository CreateRepository(string repository) + { + return LoggerManager.CreateRepository(repository); + } + + /// + /// Creates a repository with the specified name and repository type. + /// + /// + /// + /// CreateDomain is obsolete. Use CreateRepository instead of CreateDomain. + /// + /// + /// The name must be unique. Repositories cannot be redefined. + /// An will be thrown if the repository already exists. + /// + /// + /// The name of the repository, this must be unique to the repository. + /// A that implements + /// and has a no arg constructor. An instance of this type will be created to act + /// as the for the repository specified. + /// The created for the repository. + /// The specified repository already exists. + [Obsolete("Use CreateRepository instead of CreateDomain")] + public static ILoggerRepository CreateDomain(string repository, Type repositoryType) + { + return LoggerManager.CreateRepository(repository, repositoryType); + } + + /// + /// Creates a repository with the specified name and repository type. + /// + /// + /// + /// The name must be unique. Repositories cannot be redefined. + /// An will be thrown if the repository already exists. + /// + /// + /// The name of the repository, this must be unique to the repository. + /// A that implements + /// and has a no arg constructor. An instance of this type will be created to act + /// as the for the repository specified. + /// The created for the repository. + /// The specified repository already exists. + public static ILoggerRepository CreateRepository(string repository, Type repositoryType) + { + return LoggerManager.CreateRepository(repository, repositoryType); + } + + /// + /// Creates a repository for the specified assembly and repository type. + /// + /// + /// + /// CreateDomain is obsolete. Use CreateRepository instead of CreateDomain. + /// + /// + /// The created will be associated with the repository + /// specified such that a call to with the + /// same assembly specified will return the same repository instance. + /// + /// + /// The assembly to use to get the name of the repository. + /// A that implements + /// and has a no arg constructor. An instance of this type will be created to act + /// as the for the repository specified. + /// The created for the repository. + [Obsolete("Use CreateRepository instead of CreateDomain")] + public static ILoggerRepository CreateDomain(Assembly repositoryAssembly, Type repositoryType) + { + return LoggerManager.CreateRepository(repositoryAssembly, repositoryType); + } + + /// + /// Creates a repository for the specified assembly and repository type. + /// + /// + /// + /// The created will be associated with the repository + /// specified such that a call to with the + /// same assembly specified will return the same repository instance. + /// + /// + /// The assembly to use to get the name of the repository. + /// A that implements + /// and has a no arg constructor. An instance of this type will be created to act + /// as the for the repository specified. + /// The created for the repository. + public static ILoggerRepository CreateRepository(Assembly repositoryAssembly, Type repositoryType) + { + return LoggerManager.CreateRepository(repositoryAssembly, repositoryType); + } + + /// + /// Gets the list of currently defined repositories. + /// + /// + /// + /// Get an array of all the objects that have been created. + /// + /// + /// An array of all the known objects. + public static ILoggerRepository[] GetAllRepositories() + { + return LoggerManager.GetAllRepositories(); + } + + /// + /// Flushes logging events buffered in all configured appenders in the default repository. + /// + /// The maximum time in milliseconds to wait for logging events from asycnhronous appenders to be flushed. + /// True if all logging events were flushed successfully, else false. + public static bool Flush(int millisecondsTimeout) { +#if !NETSTANDARD1_3 // Excluded because GetCallingAssembly() is not available in CoreFX (https://github.com/dotnet/corefx/issues/2221). + Appender.IFlushable flushableRepository = LoggerManager.GetRepository(Assembly.GetCallingAssembly()) as Appender.IFlushable; + if (flushableRepository == null) + { + return false; + } + else + { + return flushableRepository.Flush(millisecondsTimeout); + } +#else return false; +#endif } - else + + /// + /// Looks up the wrapper object for the logger specified. + /// + /// The logger to get the wrapper for. + /// The wrapper for the logger specified. + private static ILog WrapLogger(ILogger logger) + { + return (ILog)s_wrapperMap.GetWrapper(logger); + } + + /// + /// Looks up the wrapper objects for the loggers specified. + /// + /// The loggers to get the wrappers for. + /// The wrapper objects for the loggers specified. + private static ILog[] WrapLoggers(ILogger[] loggers) + { + ILog[] results = new ILog[loggers.Length]; + for(int i = 0; i < loggers.Length; i++) { - return flushableRepository.Flush(millisecondsTimeout); + results[i] = WrapLogger(loggers[i]); } -#else - return false; -#endif - } - - /// - /// Looks up the wrapper object for the logger specified. - /// - /// The logger to get the wrapper for. - /// The wrapper for the logger specified. - private static ILog WrapLogger(ILogger logger) - { - return (ILog)s_wrapperMap.GetWrapper(logger); - } - - /// - /// Looks up the wrapper objects for the loggers specified. - /// - /// The loggers to get the wrappers for. - /// The wrapper objects for the loggers specified. - private static ILog[] WrapLoggers(ILogger[] loggers) - { - ILog[] results = new ILog[loggers.Length]; - for (int i = 0; i < loggers.Length; i++) - { - results[i] = WrapLogger(loggers[i]); - } - - return results; - } - - /// - /// Create the objects used by - /// this manager. - /// - /// The logger to wrap. - /// The wrapper for the logger specified. - private static ILoggerWrapper WrapperCreationHandler(ILogger logger) - { - return new LogImpl(logger); - } - - /// - /// The wrapper map to use to hold the objects. - /// + return results; + } + + /// + /// Create the objects used by + /// this manager. + /// + /// The logger to wrap. + /// The wrapper for the logger specified. + private static ILoggerWrapper WrapperCreationHandler(ILogger logger) + { + return new LogImpl(logger); + } + + /// + /// The wrapper map to use to hold the objects. + /// private static readonly WrapperMap s_wrapperMap = new WrapperMap(new WrapperCreationHandler(WrapperCreationHandler)); - } -} + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/LogicalThreadContext.cs b/DNN Platform/DotNetNuke.Log4net/log4net/LogicalThreadContext.cs index 8754e81bcde..72f2b4bef42 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/LogicalThreadContext.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/LogicalThreadContext.cs @@ -1,142 +1,142 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -// .NET Compact Framework 1.0 has no support for System.Runtime.Remoting.Messaging.CallContext -#if !NETCF - -using System; -using System.Collections; +// .NET Compact Framework 1.0 has no support for System.Runtime.Remoting.Messaging.CallContext +#if !NETCF -using log4net.Util; - -namespace log4net -{ - /// - /// The log4net Logical Thread Context. - /// - /// - /// - /// The LogicalThreadContext provides a location for specific debugging - /// information to be stored. - /// The LogicalThreadContext properties override any or - /// properties with the same name. - /// - /// - /// The Logical Thread Context has a properties map and a stack. - /// The properties and stack can - /// be included in the output of log messages. The - /// supports selecting and outputting these properties. - /// - /// - /// The Logical Thread Context provides a diagnostic context for the current call context. - /// This is an instrument for distinguishing interleaved log - /// output from different sources. Log output is typically interleaved - /// when a server handles multiple clients near-simultaneously. - /// - /// - /// The Logical Thread Context is managed on a per basis. - /// - /// - /// The requires a link time - /// for the - /// . - /// If the calling code does not have this permission then this context will be disabled. - /// It will not store any property values set on it. - /// - /// - /// Example of using the thread context properties to store a username. - /// - /// LogicalThreadContext.Properties["user"] = userName; - /// log.Info("This log message has a LogicalThreadContext Property called 'user'"); - /// - /// - /// Example of how to push a message into the context stack. - /// - /// using(LogicalThreadContext.Stacks["LDC"].Push("my context message")) - /// { - /// log.Info("This log message has a LogicalThreadContext Stack message that includes 'my context message'"); - /// - /// } // at the end of the using block the message is automatically popped - /// - /// - /// - /// Nicko Cadell. - public sealed class LogicalThreadContext +using log4net.Util; + +namespace log4net +{ + /// + /// The log4net Logical Thread Context. + /// + /// + /// + /// The LogicalThreadContext provides a location for specific debugging + /// information to be stored. + /// The LogicalThreadContext properties override any or + /// properties with the same name. + /// + /// + /// For .NET Standard 1.3 this class uses + /// System.Threading.AsyncLocal rather than . + /// + /// + /// The Logical Thread Context has a properties map and a stack. + /// The properties and stack can + /// be included in the output of log messages. The + /// supports selecting and outputting these properties. + /// + /// + /// The Logical Thread Context provides a diagnostic context for the current call context. + /// This is an instrument for distinguishing interleaved log + /// output from different sources. Log output is typically interleaved + /// when a server handles multiple clients near-simultaneously. + /// + /// + /// The Logical Thread Context is managed on a per basis. + /// + /// + /// The requires a link time + /// for the + /// . + /// If the calling code does not have this permission then this context will be disabled. + /// It will not store any property values set on it. + /// + /// + /// Example of using the thread context properties to store a username. + /// + /// LogicalThreadContext.Properties["user"] = userName; + /// log.Info("This log message has a LogicalThreadContext Property called 'user'"); + /// + /// + /// Example of how to push a message into the context stack + /// + /// using(LogicalThreadContext.Stacks["LDC"].Push("my context message")) + /// { + /// log.Info("This log message has a LogicalThreadContext Stack message that includes 'my context message'"); + /// + /// } // at the end of the using block the message is automatically popped + /// + /// + /// + /// Nicko Cadell + public sealed class LogicalThreadContext { /// - /// Initializes a new instance of the class. - /// Private Constructor. - /// - /// - /// - /// Uses a private access modifier to prevent instantiation of this class. - /// - /// - private LogicalThreadContext() - { + /// Private Constructor. + /// + /// + /// + /// Uses a private access modifier to prevent instantiation of this class. + /// + /// + private LogicalThreadContext() + { } - /// - /// Gets the thread properties map. - /// - /// - /// The thread properties map. - /// - /// - /// - /// The LogicalThreadContext properties override any - /// or properties with the same name. - /// - /// - public static LogicalThreadContextProperties Properties - { - get { return s_properties; } - } - - /// - /// Gets the thread stacks. - /// - /// - /// stack map. - /// - /// - /// - /// The logical thread stacks. - /// - /// - public static LogicalThreadContextStacks Stacks - { - get { return s_stacks; } + /// + /// The thread properties map + /// + /// + /// The thread properties map + /// + /// + /// + /// The LogicalThreadContext properties override any + /// or properties with the same name. + /// + /// + public static LogicalThreadContextProperties Properties + { + get { return s_properties; } + } + + /// + /// The thread stacks + /// + /// + /// stack map + /// + /// + /// + /// The logical thread stacks. + /// + /// + public static LogicalThreadContextStacks Stacks + { + get { return s_stacks; } } - /// - /// The thread context properties instance. - /// - private static readonly LogicalThreadContextProperties s_properties = new LogicalThreadContextProperties(); - - /// - /// The thread context stacks instance. - /// + /// + /// The thread context properties instance + /// + private static readonly LogicalThreadContextProperties s_properties = new LogicalThreadContextProperties(); + + /// + /// The thread context stacks instance + /// private static readonly LogicalThreadContextStacks s_stacks = new LogicalThreadContextStacks(s_properties); - } -} - -#endif + } +} + +#endif diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/MDC.cs b/DNN Platform/DotNetNuke.Log4net/log4net/MDC.cs index b3ba989e716..c6c9d3329f5 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/MDC.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/MDC.cs @@ -1,163 +1,162 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; - using System.Collections; +using System; +using System.Collections; - /// - /// Implementation of Mapped Diagnostic Contexts. - /// - /// - /// - /// - /// The MDC is deprecated and has been replaced by the . - /// The current MDC implementation forwards to the ThreadContext.Properties. - /// - /// - /// - /// The MDC class is similar to the class except that it is - /// based on a map instead of a stack. It provides mapped - /// diagnostic contexts. A Mapped Diagnostic Context, or - /// MDC in short, is an instrument for distinguishing interleaved log - /// output from different sources. Log output is typically interleaved - /// when a server handles multiple clients near-simultaneously. - /// - /// - /// The MDC is managed on a per thread basis. - /// - /// - /// - /// Nicko Cadell. - /// Gert Driesen. - [Obsolete("MDC has been replaced by ThreadContext.Properties. Scheduled removal in v10.0.0.")] - public sealed class MDC +namespace log4net +{ + /// + /// Implementation of Mapped Diagnostic Contexts. + /// + /// + /// + /// + /// The MDC is deprecated and has been replaced by the . + /// The current MDC implementation forwards to the ThreadContext.Properties. + /// + /// + /// + /// The MDC class is similar to the class except that it is + /// based on a map instead of a stack. It provides mapped + /// diagnostic contexts. A Mapped Diagnostic Context, or + /// MDC in short, is an instrument for distinguishing interleaved log + /// output from different sources. Log output is typically interleaved + /// when a server handles multiple clients near-simultaneously. + /// + /// + /// The MDC is managed on a per thread basis. + /// + /// + /// + /// Nicko Cadell + /// Gert Driesen + /*[Obsolete("MDC has been replaced by ThreadContext.Properties")]*/ + public sealed class MDC { - /// - /// Initializes a new instance of the class. - /// - /// - /// Uses a private access modifier to prevent instantiation of this class. - /// - private MDC() - { + /// + /// Initializes a new instance of the class. + /// + /// + /// Uses a private access modifier to prevent instantiation of this class. + /// + private MDC() + { } - /// - /// Gets the context value identified by the parameter. - /// - /// The key to lookup in the MDC. - /// The string value held for the key, or a null reference if no corresponding value is found. - /// - /// - /// - /// The MDC is deprecated and has been replaced by the . - /// The current MDC implementation forwards to the ThreadContext.Properties. - /// - /// - /// - /// If the parameter does not look up to a - /// previously defined context then null will be returned. - /// - /// - /*[Obsolete("MDC has been replaced by ThreadContext.Properties. Scheduled removal in v11.0.0.")]*/ - public static string Get(string key) - { - object obj = ThreadContext.Properties[key]; - if (obj == null) - { - return null; - } + /// + /// Gets the context value identified by the parameter. + /// + /// The key to lookup in the MDC. + /// The string value held for the key, or a null reference if no corresponding value is found. + /// + /// + /// + /// The MDC is deprecated and has been replaced by the . + /// The current MDC implementation forwards to the ThreadContext.Properties. + /// + /// + /// + /// If the parameter does not look up to a + /// previously defined context then null will be returned. + /// + /// + /*[Obsolete("MDC has been replaced by ThreadContext.Properties")]*/ + public static string Get(string key) + { + object obj = ThreadContext.Properties[key]; + if (obj == null) + { + return null; + } + return obj.ToString(); + } + + /// + /// Add an entry to the MDC + /// + /// The key to store the value under. + /// The value to store. + /// + /// + /// + /// The MDC is deprecated and has been replaced by the . + /// The current MDC implementation forwards to the ThreadContext.Properties. + /// + /// + /// + /// Puts a context value (the parameter) as identified + /// with the parameter into the current thread's + /// context map. + /// + /// + /// If a value is already defined for the + /// specified then the value will be replaced. If the + /// is specified as null then the key value mapping will be removed. + /// + /// + /*[Obsolete("MDC has been replaced by ThreadContext.Properties")]*/ + public static void Set(string key, string value) + { + ThreadContext.Properties[key] = value; + } + + /// + /// Removes the key value mapping for the key specified. + /// + /// The key to remove. + /// + /// + /// + /// The MDC is deprecated and has been replaced by the . + /// The current MDC implementation forwards to the ThreadContext.Properties. + /// + /// + /// + /// Remove the specified entry from this thread's MDC + /// + /// + /*[Obsolete("MDC has been replaced by ThreadContext.Properties")]*/ + public static void Remove(string key) + { + ThreadContext.Properties.Remove(key); + } - return obj.ToString(); - } - - /// - /// Add an entry to the MDC. - /// - /// The key to store the value under. - /// The value to store. - /// - /// - /// - /// The MDC is deprecated and has been replaced by the . - /// The current MDC implementation forwards to the ThreadContext.Properties. - /// - /// - /// - /// Puts a context value (the parameter) as identified - /// with the parameter into the current thread's - /// context map. - /// - /// - /// If a value is already defined for the - /// specified then the value will be replaced. If the - /// is specified as null then the key value mapping will be removed. - /// - /// - [Obsolete("MDC has been replaced by ThreadContext.Properties. Scheduled removal in v10.0.0.")] - public static void Set(string key, string value) - { - ThreadContext.Properties[key] = value; - } - - /// - /// Removes the key value mapping for the key specified. - /// - /// The key to remove. - /// - /// - /// - /// The MDC is deprecated and has been replaced by the . - /// The current MDC implementation forwards to the ThreadContext.Properties. - /// - /// - /// - /// Remove the specified entry from this thread's MDC. - /// - /// - [Obsolete("MDC has been replaced by ThreadContext.Properties. Scheduled removal in v10.0.0.")] - public static void Remove(string key) - { - ThreadContext.Properties.Remove(key); - } - - /// - /// Clear all entries in the MDC. - /// - /// - /// - /// - /// The MDC is deprecated and has been replaced by the . - /// The current MDC implementation forwards to the ThreadContext.Properties. - /// - /// - /// - /// Remove all the entries from this thread's MDC. - /// - /// - [Obsolete("MDC has been replaced by ThreadContext.Properties. Scheduled removal in v10.0.0.")] - public static void Clear() - { - ThreadContext.Properties.Clear(); + /// + /// Clear all entries in the MDC + /// + /// + /// + /// + /// The MDC is deprecated and has been replaced by the . + /// The current MDC implementation forwards to the ThreadContext.Properties. + /// + /// + /// + /// Remove all the entries from this thread's MDC + /// + /// + /*[Obsolete("MDC has been replaced by ThreadContext.Properties")]*/ + public static void Clear() + { + ThreadContext.Properties.Clear(); } - } -} + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/NDC.cs b/DNN Platform/DotNetNuke.Log4net/log4net/NDC.cs index 5165d70013e..f559fc25e8c 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/NDC.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/NDC.cs @@ -1,338 +1,338 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -#if NETCF_1_0 -using Stack = log4net.Util.ThreadContextStack.Stack; -#endif - -namespace log4net -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; - using System.Collections; +using System; +using System.Collections; - /// - /// Implementation of Nested Diagnostic Contexts. - /// - /// - /// - /// - /// The NDC is deprecated and has been replaced by the . - /// The current NDC implementation forwards to the ThreadContext.Stacks["NDC"]. - /// - /// - /// - /// A Nested Diagnostic Context, or NDC in short, is an instrument - /// to distinguish interleaved log output from different sources. Log - /// output is typically interleaved when a server handles multiple - /// clients near-simultaneously. - /// - /// - /// Interleaved log output can still be meaningful if each log entry - /// from different contexts had a distinctive stamp. This is where NDCs - /// come into play. - /// - /// - /// Note that NDCs are managed on a per thread basis. The NDC class - /// is made up of static methods that operate on the context of the - /// calling thread. - /// - /// - /// How to push a message into the context. - /// - /// using(NDC.Push("my context message")) - /// { - /// ... all log calls will have 'my context message' included ... - /// - /// } // at the end of the using block the message is automatically removed - /// - /// - /// - /// Nicko Cadell. - /// Gert Driesen. - [Obsolete("NDC has been replaced by ThreadContext.Stacks. Scheduled removal in v10.0.0.")] - public sealed class NDC +#if NETCF_1_0 +using Stack = log4net.Util.ThreadContextStack.Stack; +#endif + +namespace log4net +{ + /// + /// Implementation of Nested Diagnostic Contexts. + /// + /// + /// + /// + /// The NDC is deprecated and has been replaced by the . + /// The current NDC implementation forwards to the ThreadContext.Stacks["NDC"]. + /// + /// + /// + /// A Nested Diagnostic Context, or NDC in short, is an instrument + /// to distinguish interleaved log output from different sources. Log + /// output is typically interleaved when a server handles multiple + /// clients near-simultaneously. + /// + /// + /// Interleaved log output can still be meaningful if each log entry + /// from different contexts had a distinctive stamp. This is where NDCs + /// come into play. + /// + /// + /// Note that NDCs are managed on a per thread basis. The NDC class + /// is made up of static methods that operate on the context of the + /// calling thread. + /// + /// + /// How to push a message into the context + /// + /// using(NDC.Push("my context message")) + /// { + /// ... all log calls will have 'my context message' included ... + /// + /// } // at the end of the using block the message is automatically removed + /// + /// + /// + /// Nicko Cadell + /// Gert Driesen + /*[Obsolete("NDC has been replaced by ThreadContext.Stacks")]*/ + public sealed class NDC { - /// - /// Initializes a new instance of the class. - /// - /// - /// Uses a private access modifier to prevent instantiation of this class. - /// - private NDC() - { + /// + /// Initializes a new instance of the class. + /// + /// + /// Uses a private access modifier to prevent instantiation of this class. + /// + private NDC() + { + } + + /// + /// Gets the current context depth. + /// + /// The current context depth. + /// + /// + /// + /// The NDC is deprecated and has been replaced by the . + /// The current NDC implementation forwards to the ThreadContext.Stacks["NDC"]. + /// + /// + /// + /// The number of context values pushed onto the context stack. + /// + /// + /// Used to record the current depth of the context. This can then + /// be restored using the method. + /// + /// + /// + /*[Obsolete("NDC has been replaced by ThreadContext.Stacks")]*/ + public static int Depth + { + get { return ThreadContext.Stacks["NDC"].Count; } + } + + /// + /// Clears all the contextual information held on the current thread. + /// + /// + /// + /// + /// The NDC is deprecated and has been replaced by the . + /// The current NDC implementation forwards to the ThreadContext.Stacks["NDC"]. + /// + /// + /// + /// Clears the stack of NDC data held on the current thread. + /// + /// + /*[Obsolete("NDC has been replaced by ThreadContext.Stacks")]*/ + public static void Clear() + { + ThreadContext.Stacks["NDC"].Clear(); + } + + /// + /// Creates a clone of the stack of context information. + /// + /// A clone of the context info for this thread. + /// + /// + /// + /// The NDC is deprecated and has been replaced by the . + /// The current NDC implementation forwards to the ThreadContext.Stacks["NDC"]. + /// + /// + /// + /// The results of this method can be passed to the + /// method to allow child threads to inherit the context of their + /// parent thread. + /// + /// + /*[Obsolete("NDC has been replaced by ThreadContext.Stacks")]*/ + public static Stack CloneStack() + { + return ThreadContext.Stacks["NDC"].InternalStack; + } + + /// + /// Inherits the contextual information from another thread. + /// + /// The context stack to inherit. + /// + /// + /// + /// The NDC is deprecated and has been replaced by the . + /// The current NDC implementation forwards to the ThreadContext.Stacks["NDC"]. + /// + /// + /// + /// This thread will use the context information from the stack + /// supplied. This can be used to initialize child threads with + /// the same contextual information as their parent threads. These + /// contexts will NOT be shared. Any further contexts that + /// are pushed onto the stack will not be visible to the other. + /// Call to obtain a stack to pass to + /// this method. + /// + /// + /*[Obsolete("NDC has been replaced by ThreadContext.Stacks", true)]*/ + public static void Inherit(Stack stack) + { + ThreadContext.Stacks["NDC"].InternalStack = stack; + } + + /// + /// Removes the top context from the stack. + /// + /// + /// The message in the context that was removed from the top + /// of the stack. + /// + /// + /// + /// + /// The NDC is deprecated and has been replaced by the . + /// The current NDC implementation forwards to the ThreadContext.Stacks["NDC"]. + /// + /// + /// + /// Remove the top context from the stack, and return + /// it to the caller. If the stack is empty then an + /// empty string (not null) is returned. + /// + /// + /*[Obsolete("NDC has been replaced by ThreadContext.Stacks")]*/ + public static string Pop() + { + return ThreadContext.Stacks["NDC"].Pop(); + } + + /// + /// Pushes a new context message. + /// + /// The new context message. + /// + /// An that can be used to clean up + /// the context stack. + /// + /// + /// + /// + /// The NDC is deprecated and has been replaced by the . + /// The current NDC implementation forwards to the ThreadContext.Stacks["NDC"]. + /// + /// + /// + /// Pushes a new context onto the context stack. An + /// is returned that can be used to clean up the context stack. This + /// can be easily combined with the using keyword to scope the + /// context. + /// + /// + /// Simple example of using the Push method with the using keyword. + /// + /// using(log4net.NDC.Push("NDC_Message")) + /// { + /// log.Warn("This should have an NDC message"); + /// } + /// + /// + /*[Obsolete("NDC has been replaced by ThreadContext.Stacks")]*/ + public static IDisposable Push(string message) + { + return ThreadContext.Stacks["NDC"].Push(message); + } + + /// + /// Pushes a new context message. + /// + /// The new context message string format. + /// Arguments to be passed into messageFormat. + /// + /// An that can be used to clean up + /// the context stack. + /// + /// + /// + /// + /// The NDC is deprecated and has been replaced by the . + /// The current NDC implementation forwards to the ThreadContext.Stacks["NDC"]. + /// + /// + /// + /// Pushes a new context onto the context stack. An + /// is returned that can be used to clean up the context stack. This + /// can be easily combined with the using keyword to scope the + /// context. + /// + /// + /// Simple example of using the Push method with the using keyword. + /// + /// var someValue = "ExampleContext" + /// using(log4net.NDC.PushFormat("NDC_Message {0}", someValue)) + /// { + /// log.Warn("This should have an NDC message"); + /// } + /// + /// + /*[Obsolete("NDC has been replaced by ThreadContext.Stacks")]*/ + public static IDisposable PushFormat(string messageFormat, params object[] args) + { + return Push(string.Format(messageFormat, args)); } - /// - /// Gets the current context depth. - /// - /// The current context depth. - /// - /// - /// - /// The NDC is deprecated and has been replaced by the . - /// The current NDC implementation forwards to the ThreadContext.Stacks["NDC"]. - /// - /// - /// - /// The number of context values pushed onto the context stack. - /// - /// - /// Used to record the current depth of the context. This can then - /// be restored using the method. - /// - /// - /// - /*[Obsolete("NDC has been replaced by ThreadContext.Stacks. Scheduled removal in v11.0.0.")]*/ - public static int Depth - { - get { return ThreadContext.Stacks["NDC"].Count; } + /// + /// Removes the context information for this thread. It is + /// not required to call this method. + /// + /// + /// + /// + /// The NDC is deprecated and has been replaced by the . + /// The current NDC implementation forwards to the ThreadContext.Stacks["NDC"]. + /// + /// + /// + /// This method is not implemented. + /// + /// + /*[Obsolete("NDC has been replaced by ThreadContext.Stacks")]*/ + public static void Remove() + { } - /// - /// Clears all the contextual information held on the current thread. - /// - /// - /// - /// - /// The NDC is deprecated and has been replaced by the . - /// The current NDC implementation forwards to the ThreadContext.Stacks["NDC"]. - /// - /// - /// - /// Clears the stack of NDC data held on the current thread. - /// - /// - [Obsolete("NDC has been replaced by ThreadContext.Stacks. Scheduled removal in v10.0.0.")] - public static void Clear() - { - ThreadContext.Stacks["NDC"].Clear(); - } - - /// - /// Creates a clone of the stack of context information. - /// - /// A clone of the context info for this thread. - /// - /// - /// - /// The NDC is deprecated and has been replaced by the . - /// The current NDC implementation forwards to the ThreadContext.Stacks["NDC"]. - /// - /// - /// - /// The results of this method can be passed to the - /// method to allow child threads to inherit the context of their - /// parent thread. - /// - /// - [Obsolete("NDC has been replaced by ThreadContext.Stacks. Scheduled removal in v10.0.0.")] - public static Stack CloneStack() - { - return ThreadContext.Stacks["NDC"].InternalStack; - } - - /// - /// Inherits the contextual information from another thread. - /// - /// The context stack to inherit. - /// - /// - /// - /// The NDC is deprecated and has been replaced by the . - /// The current NDC implementation forwards to the ThreadContext.Stacks["NDC"]. - /// - /// - /// - /// This thread will use the context information from the stack - /// supplied. This can be used to initialize child threads with - /// the same contextual information as their parent threads. These - /// contexts will NOT be shared. Any further contexts that - /// are pushed onto the stack will not be visible to the other. - /// Call to obtain a stack to pass to - /// this method. - /// - /// - [Obsolete("NDC has been replaced by ThreadContext.Stacks. Scheduled removal in v10.0.0.", true)] - public static void Inherit(Stack stack) - { - ThreadContext.Stacks["NDC"].InternalStack = stack; - } - - /// - /// Removes the top context from the stack. - /// - /// - /// The message in the context that was removed from the top - /// of the stack. - /// - /// - /// - /// - /// The NDC is deprecated and has been replaced by the . - /// The current NDC implementation forwards to the ThreadContext.Stacks["NDC"]. - /// - /// - /// - /// Remove the top context from the stack, and return - /// it to the caller. If the stack is empty then an - /// empty string (not null) is returned. - /// - /// - /*[Obsolete("NDC has been replaced by ThreadContext.Stacks. Scheduled removal in v11.0.0.")]*/ - public static string Pop() - { - return ThreadContext.Stacks["NDC"].Pop(); - } - - /// - /// Pushes a new context message. - /// - /// The new context message. - /// - /// An that can be used to clean up - /// the context stack. - /// - /// - /// - /// - /// The NDC is deprecated and has been replaced by the . - /// The current NDC implementation forwards to the ThreadContext.Stacks["NDC"]. - /// - /// - /// - /// Pushes a new context onto the context stack. An - /// is returned that can be used to clean up the context stack. This - /// can be easily combined with the using keyword to scope the - /// context. - /// - /// - /// Simple example of using the Push method with the using keyword. - /// - /// using(log4net.NDC.Push("NDC_Message")) - /// { - /// log.Warn("This should have an NDC message"); - /// } - /// - /// - [Obsolete("NDC has been replaced by ThreadContext.Stacks. Scheduled removal in v10.0.0.")] - public static IDisposable Push(string message) - { - return ThreadContext.Stacks["NDC"].Push(message); - } - - /// - /// Pushes a new context message. - /// - /// The new context message string format. - /// Arguments to be passed into messageFormat. - /// - /// An that can be used to clean up - /// the context stack. - /// - /// - /// - /// - /// The NDC is deprecated and has been replaced by the . - /// The current NDC implementation forwards to the ThreadContext.Stacks["NDC"]. - /// - /// - /// - /// Pushes a new context onto the context stack. An - /// is returned that can be used to clean up the context stack. This - /// can be easily combined with the using keyword to scope the - /// context. - /// - /// - /// Simple example of using the Push method with the using keyword. - /// - /// var someValue = "ExampleContext" - /// using(log4net.NDC.PushFormat("NDC_Message {0}", someValue)) - /// { - /// log.Warn("This should have an NDC message"); - /// } - /// - /// - [Obsolete("NDC has been replaced by ThreadContext.Stacks. Scheduled removal in v10.0.0.")] - public static IDisposable PushFormat(string messageFormat, params object[] args) - { - return Push(string.Format(messageFormat, args)); - } - - /// - /// Removes the context information for this thread. It is - /// not required to call this method. - /// - /// - /// - /// - /// The NDC is deprecated and has been replaced by the . - /// The current NDC implementation forwards to the ThreadContext.Stacks["NDC"]. - /// - /// - /// - /// This method is not implemented. - /// - /// - [Obsolete("NDC has been replaced by ThreadContext.Stacks. Scheduled removal in v10.0.0.")] - public static void Remove() - { - } - - /// - /// Forces the stack depth to be at most . - /// - /// The maximum depth of the stack. - /// - /// - /// - /// The NDC is deprecated and has been replaced by the . - /// The current NDC implementation forwards to the ThreadContext.Stacks["NDC"]. - /// - /// - /// - /// Forces the stack depth to be at most . - /// This may truncate the head of the stack. This only affects the - /// stack in the current thread. Also it does not prevent it from - /// growing, it only sets the maximum depth at the time of the - /// call. This can be used to return to a known context depth. - /// - /// - [Obsolete("NDC has been replaced by ThreadContext.Stacks. Scheduled removal in v10.0.0.")] - public static void SetMaxDepth(int maxDepth) - { - if (maxDepth >= 0) - { - log4net.Util.ThreadContextStack stack = ThreadContext.Stacks["NDC"]; - - if (maxDepth == 0) - { - stack.Clear(); - } - else - { - while (stack.Count > maxDepth) - { - stack.Pop(); - } - } - } + /// + /// Forces the stack depth to be at most . + /// + /// The maximum depth of the stack + /// + /// + /// + /// The NDC is deprecated and has been replaced by the . + /// The current NDC implementation forwards to the ThreadContext.Stacks["NDC"]. + /// + /// + /// + /// Forces the stack depth to be at most . + /// This may truncate the head of the stack. This only affects the + /// stack in the current thread. Also it does not prevent it from + /// growing, it only sets the maximum depth at the time of the + /// call. This can be used to return to a known context depth. + /// + /// + /*[Obsolete("NDC has been replaced by ThreadContext.Stacks")]*/ + public static void SetMaxDepth(int maxDepth) + { + if (maxDepth >= 0) + { + Util.ThreadContextStack stack = ThreadContext.Stacks["NDC"]; + + if (maxDepth == 0) + { + stack.Clear(); + } + else + { + while(stack.Count > maxDepth) + { + stack.Pop(); + } + } + } } - } -} + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/ObjectRenderer/DefaultRenderer.cs b/DNN Platform/DotNetNuke.Log4net/log4net/ObjectRenderer/DefaultRenderer.cs index 300f4ede916..a787960509b 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/ObjectRenderer/DefaultRenderer.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/ObjectRenderer/DefaultRenderer.cs @@ -1,305 +1,303 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.ObjectRenderer -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; - using System.Collections; - using System.IO; - using System.Text; +using System; +using System.Text; +using System.IO; +using System.Collections; - using log4net.Util; +using log4net.Util; - /// - /// The default object Renderer. - /// - /// - /// - /// The default renderer supports rendering objects and collections to strings. - /// - /// - /// See the method for details of the output. - /// - /// - /// Nicko Cadell. - /// Gert Driesen. - public sealed class DefaultRenderer : IObjectRenderer +namespace log4net.ObjectRenderer +{ + /// + /// The default object Renderer. + /// + /// + /// + /// The default renderer supports rendering objects and collections to strings. + /// + /// + /// See the method for details of the output. + /// + /// + /// Nicko Cadell + /// Gert Driesen + public sealed class DefaultRenderer : IObjectRenderer { /// - /// Initializes a new instance of the class. - /// Default constructor. - /// - /// - /// - /// Default constructor. - /// - /// - public DefaultRenderer() - { + /// Default constructor + /// + /// + /// + /// Default constructor + /// + /// + public DefaultRenderer() + { } - /// - /// Render the object to a string. - /// - /// The map used to lookup renderers. - /// The object to render. - /// The writer to render to. - /// - /// - /// Render the object to a string. - /// - /// - /// The parameter is - /// provided to lookup and render other objects. This is - /// very useful where contains - /// nested objects of unknown type. The - /// method can be used to render these objects. - /// - /// - /// The default renderer supports rendering objects to strings as follows: - /// - /// - /// - /// Value - /// Rendered String - /// - /// - /// null - /// - /// "(null)" - /// - /// - /// - /// - /// - /// - /// For a one dimensional array this is the - /// array type name, an open brace, followed by a comma - /// separated list of the elements (using the appropriate - /// renderer), followed by a close brace. - /// - /// - /// For example: int[] {1, 2, 3}. - /// - /// - /// If the array is not one dimensional the - /// Array.ToString() is returned. - /// - /// - /// - /// - /// , & - /// - /// - /// Rendered as an open brace, followed by a comma - /// separated list of the elements (using the appropriate - /// renderer), followed by a close brace. - /// - /// - /// For example: {a, b, c}. - /// - /// - /// All collection classes that implement its subclasses, - /// or generic equivalents all implement the interface. - /// - /// - /// - /// - /// - /// - /// - /// Rendered as the key, an equals sign ('='), and the value (using the appropriate - /// renderer). - /// - /// - /// For example: key=value. - /// - /// - /// - /// - /// other - /// - /// Object.ToString() - /// - /// - /// - /// - public void RenderObject(RendererMap rendererMap, object obj, TextWriter writer) - { - if (rendererMap == null) - { - throw new ArgumentNullException("rendererMap"); - } - - if (obj == null) - { - writer.Write(SystemInfo.NullText); - return; - } - - Array objArray = obj as Array; - if (objArray != null) - { - this.RenderArray(rendererMap, objArray, writer); - return; - } - - // Test if we are dealing with some form of collection object - IEnumerable objEnumerable = obj as IEnumerable; - if (objEnumerable != null) - { - // Get a collection interface if we can as its .Count property may be more - // performant than getting the IEnumerator object and trying to advance it. - ICollection objCollection = obj as ICollection; - if (objCollection != null && objCollection.Count == 0) - { - writer.Write("{}"); - return; - } - - // This is a special check to allow us to get the enumerator from the IDictionary - // interface as this guarantees us DictionaryEntry objects. Note that in .NET 2.0 - // the generic IDictionary<> interface enumerates KeyValuePair objects rather than - // DictionaryEntry ones. However the implementation of the plain IDictionary - // interface on the generic Dictionary<> still returns DictionaryEntry objects. - IDictionary objDictionary = obj as IDictionary; - if (objDictionary != null) - { - this.RenderEnumerator(rendererMap, objDictionary.GetEnumerator(), writer); - return; - } - - this.RenderEnumerator(rendererMap, objEnumerable.GetEnumerator(), writer); - return; - } - - IEnumerator objEnumerator = obj as IEnumerator; - if (objEnumerator != null) - { - this.RenderEnumerator(rendererMap, objEnumerator, writer); - return; - } - - if (obj is DictionaryEntry) - { - this.RenderDictionaryEntry(rendererMap, (DictionaryEntry)obj, writer); - return; - } - - string str = obj.ToString(); - writer.Write((str == null) ? SystemInfo.NullText : str); + /// + /// Render the object to a string + /// + /// The map used to lookup renderers + /// The object to render + /// The writer to render to + /// + /// + /// Render the object to a string. + /// + /// + /// The parameter is + /// provided to lookup and render other objects. This is + /// very useful where contains + /// nested objects of unknown type. The + /// method can be used to render these objects. + /// + /// + /// The default renderer supports rendering objects to strings as follows: + /// + /// + /// + /// Value + /// Rendered String + /// + /// + /// null + /// + /// "(null)" + /// + /// + /// + /// + /// + /// + /// For a one dimensional array this is the + /// array type name, an open brace, followed by a comma + /// separated list of the elements (using the appropriate + /// renderer), followed by a close brace. + /// + /// + /// For example: int[] {1, 2, 3}. + /// + /// + /// If the array is not one dimensional the + /// Array.ToString() is returned. + /// + /// + /// + /// + /// , & + /// + /// + /// Rendered as an open brace, followed by a comma + /// separated list of the elements (using the appropriate + /// renderer), followed by a close brace. + /// + /// + /// For example: {a, b, c}. + /// + /// + /// All collection classes that implement its subclasses, + /// or generic equivalents all implement the interface. + /// + /// + /// + /// + /// + /// + /// + /// Rendered as the key, an equals sign ('='), and the value (using the appropriate + /// renderer). + /// + /// + /// For example: key=value. + /// + /// + /// + /// + /// other + /// + /// Object.ToString() + /// + /// + /// + /// + public void RenderObject(RendererMap rendererMap, object obj, TextWriter writer) + { + if (rendererMap == null) + { + throw new ArgumentNullException("rendererMap"); + } + + if (obj == null) + { + writer.Write(SystemInfo.NullText); + return; + } + + Array objArray = obj as Array; + if (objArray != null) + { + this.RenderArray(rendererMap, objArray, writer); + return; + } + + // Test if we are dealing with some form of collection object + IEnumerable objEnumerable = obj as IEnumerable; + if (objEnumerable != null) + { + // Get a collection interface if we can as its .Count property may be more + // performant than getting the IEnumerator object and trying to advance it. + ICollection objCollection = obj as ICollection; + if (objCollection != null && objCollection.Count == 0) + { + writer.Write("{}"); + return; + } + + // This is a special check to allow us to get the enumerator from the IDictionary + // interface as this guarantees us DictionaryEntry objects. Note that in .NET 2.0 + // the generic IDictionary<> interface enumerates KeyValuePair objects rather than + // DictionaryEntry ones. However the implementation of the plain IDictionary + // interface on the generic Dictionary<> still returns DictionaryEntry objects. + IDictionary objDictionary = obj as IDictionary; + if (objDictionary != null) + { + this.RenderEnumerator(rendererMap, objDictionary.GetEnumerator(), writer); + return; + } + + this.RenderEnumerator(rendererMap, objEnumerable.GetEnumerator(), writer); + return; + } + + IEnumerator objEnumerator = obj as IEnumerator; + if (objEnumerator != null) + { + this.RenderEnumerator(rendererMap, objEnumerator, writer); + return; + } + + if (obj is DictionaryEntry) + { + this.RenderDictionaryEntry(rendererMap, (DictionaryEntry)obj, writer); + return; + } + + string str = obj.ToString(); + writer.Write( (str == null) ? SystemInfo.NullText : str ); + } + + /// + /// Render the array argument into a string + /// + /// The map used to lookup renderers + /// the array to render + /// The writer to render to + /// + /// + /// For a one dimensional array this is the + /// array type name, an open brace, followed by a comma + /// separated list of the elements (using the appropriate + /// renderer), followed by a close brace. For example: + /// int[] {1, 2, 3}. + /// + /// + /// If the array is not one dimensional the + /// Array.ToString() is returned. + /// + /// + private void RenderArray(RendererMap rendererMap, Array array, TextWriter writer) + { + if (array.Rank != 1) + { + writer.Write(array.ToString()); + } + else + { + writer.Write(array.GetType().Name + " {"); + int len = array.Length; + + if (len > 0) + { + rendererMap.FindAndRender(array.GetValue(0), writer); + for(int i = 1; i < len; i++) + { + writer.Write(", "); + rendererMap.FindAndRender(array.GetValue(i), writer); + } + } + writer.Write("}"); + } } - /// - /// Render the array argument into a string. - /// - /// The map used to lookup renderers. - /// the array to render. - /// The writer to render to. - /// - /// - /// For a one dimensional array this is the - /// array type name, an open brace, followed by a comma - /// separated list of the elements (using the appropriate - /// renderer), followed by a close brace. For example: - /// int[] {1, 2, 3}. - /// - /// - /// If the array is not one dimensional the - /// Array.ToString() is returned. - /// - /// - private void RenderArray(RendererMap rendererMap, Array array, TextWriter writer) - { - if (array.Rank != 1) - { - writer.Write(array.ToString()); - } - else - { - writer.Write(array.GetType().Name + " {"); - int len = array.Length; - - if (len > 0) - { - rendererMap.FindAndRender(array.GetValue(0), writer); - for (int i = 1; i < len; i++) - { - writer.Write(", "); - rendererMap.FindAndRender(array.GetValue(i), writer); - } - } + /// + /// Render the enumerator argument into a string + /// + /// The map used to lookup renderers + /// the enumerator to render + /// The writer to render to + /// + /// + /// Rendered as an open brace, followed by a comma + /// separated list of the elements (using the appropriate + /// renderer), followed by a close brace. For example: + /// {a, b, c}. + /// + /// + private void RenderEnumerator(RendererMap rendererMap, IEnumerator enumerator, TextWriter writer) + { + writer.Write("{"); + + if (enumerator != null && enumerator.MoveNext()) + { + rendererMap.FindAndRender(enumerator.Current, writer); - writer.Write("}"); - } - } - - /// - /// Render the enumerator argument into a string. - /// - /// The map used to lookup renderers. - /// the enumerator to render. - /// The writer to render to. - /// - /// - /// Rendered as an open brace, followed by a comma - /// separated list of the elements (using the appropriate - /// renderer), followed by a close brace. For example: - /// {a, b, c}. - /// - /// - private void RenderEnumerator(RendererMap rendererMap, IEnumerator enumerator, TextWriter writer) - { - writer.Write("{"); - - if (enumerator != null && enumerator.MoveNext()) - { - rendererMap.FindAndRender(enumerator.Current, writer); - - while (enumerator.MoveNext()) - { - writer.Write(", "); - rendererMap.FindAndRender(enumerator.Current, writer); - } - } - - writer.Write("}"); - } - - /// - /// Render the DictionaryEntry argument into a string. - /// - /// The map used to lookup renderers. - /// the DictionaryEntry to render. - /// The writer to render to. - /// - /// - /// Render the key, an equals sign ('='), and the value (using the appropriate - /// renderer). For example: key=value. - /// - /// - private void RenderDictionaryEntry(RendererMap rendererMap, DictionaryEntry entry, TextWriter writer) - { - rendererMap.FindAndRender(entry.Key, writer); - writer.Write("="); - rendererMap.FindAndRender(entry.Value, writer); - } - } -} + while (enumerator.MoveNext()) + { + writer.Write(", "); + rendererMap.FindAndRender(enumerator.Current, writer); + } + } + + writer.Write("}"); + } + + /// + /// Render the DictionaryEntry argument into a string + /// + /// The map used to lookup renderers + /// the DictionaryEntry to render + /// The writer to render to + /// + /// + /// Render the key, an equals sign ('='), and the value (using the appropriate + /// renderer). For example: key=value. + /// + /// + private void RenderDictionaryEntry(RendererMap rendererMap, DictionaryEntry entry, TextWriter writer) + { + rendererMap.FindAndRender(entry.Key, writer); + writer.Write("="); + rendererMap.FindAndRender(entry.Value, writer); + } + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/ObjectRenderer/IObjectRenderer.cs b/DNN Platform/DotNetNuke.Log4net/log4net/ObjectRenderer/IObjectRenderer.cs index 9efb078790b..a4fc4f83ae1 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/ObjectRenderer/IObjectRenderer.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/ObjectRenderer/IObjectRenderer.cs @@ -1,62 +1,62 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.ObjectRenderer -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; - using System.IO; +using System; +using System.IO; - /// - /// Implement this interface in order to render objects as strings. - /// - /// - /// - /// Certain types require special case conversion to - /// string form. This conversion is done by an object renderer. - /// Object renderers implement the - /// interface. - /// - /// - /// Nicko Cadell. - /// Gert Driesen. - public interface IObjectRenderer - { - /// - /// Render the object to a string. - /// - /// The map used to lookup renderers. - /// The object to render. - /// The writer to render to. - /// - /// - /// Render the object to a - /// string. - /// - /// - /// The parameter is - /// provided to lookup and render other objects. This is - /// very useful where contains - /// nested objects of unknown type. The - /// method can be used to render these objects. - /// - /// - void RenderObject(RendererMap rendererMap, object obj, TextWriter writer); - } -} +namespace log4net.ObjectRenderer +{ + /// + /// Implement this interface in order to render objects as strings + /// + /// + /// + /// Certain types require special case conversion to + /// string form. This conversion is done by an object renderer. + /// Object renderers implement the + /// interface. + /// + /// + /// Nicko Cadell + /// Gert Driesen + public interface IObjectRenderer + { + /// + /// Render the object to a string + /// + /// The map used to lookup renderers + /// The object to render + /// The writer to render to + /// + /// + /// Render the object to a + /// string. + /// + /// + /// The parameter is + /// provided to lookup and render other objects. This is + /// very useful where contains + /// nested objects of unknown type. The + /// method can be used to render these objects. + /// + /// + void RenderObject(RendererMap rendererMap, object obj, TextWriter writer); + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/ObjectRenderer/RendererMap.cs b/DNN Platform/DotNetNuke.Log4net/log4net/ObjectRenderer/RendererMap.cs index a7c8f95dcc9..5ccd162f36a 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/ObjectRenderer/RendererMap.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/ObjectRenderer/RendererMap.cs @@ -1,331 +1,330 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -#if NETSTANDARD1_3 -using System.Reflection; -#endif - -using log4net.Util; - -namespace log4net.ObjectRenderer -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; - using System.IO; +using System; +using System.IO; +#if NETSTANDARD1_3 +using System.Reflection; +#endif - /// - /// Map class objects to an . - /// - /// - /// - /// Maintains a mapping between types that require special - /// rendering and the that - /// is used to render them. - /// - /// - /// The method is used to render an - /// object using the appropriate renderers defined in this map. - /// - /// - /// Nicko Cadell. - /// Gert Driesen. - public class RendererMap - { +using log4net.Util; + +namespace log4net.ObjectRenderer +{ + /// + /// Map class objects to an . + /// + /// + /// + /// Maintains a mapping between types that require special + /// rendering and the that + /// is used to render them. + /// + /// + /// The method is used to render an + /// object using the appropriate renderers defined in this map. + /// + /// + /// Nicko Cadell + /// Gert Driesen + public class RendererMap + { private static readonly Type declaringType = typeof(RendererMap); - private System.Collections.Hashtable m_map; - private System.Collections.Hashtable m_cache = new System.Collections.Hashtable(); - + + private System.Collections.Hashtable m_map; + private System.Collections.Hashtable m_cache = new System.Collections.Hashtable(); + private static IObjectRenderer s_defaultRenderer = new DefaultRenderer(); /// - /// Initializes a new instance of the class. - /// Default Constructor. - /// - /// - /// - /// Default constructor. - /// - /// - public RendererMap() - { - this.m_map = System.Collections.Hashtable.Synchronized(new System.Collections.Hashtable()); + /// Default Constructor + /// + /// + /// + /// Default constructor. + /// + /// + public RendererMap() + { + this.m_map = System.Collections.Hashtable.Synchronized(new System.Collections.Hashtable()); } - /// - /// Render using the appropriate renderer. - /// - /// the object to render to a string. - /// the object rendered as a string. - /// - /// - /// This is a convenience method used to render an object to a string. - /// The alternative method - /// should be used when streaming output to a . - /// - /// - public string FindAndRender(object obj) - { - // Optimisation for strings - string strData = obj as string; - if (strData != null) - { - return strData; - } - - StringWriter stringWriter = new StringWriter(System.Globalization.CultureInfo.InvariantCulture); - this.FindAndRender(obj, stringWriter); - return stringWriter.ToString(); - } - - /// - /// Render using the appropriate renderer. - /// - /// the object to render to a string. - /// The writer to render to. - /// - /// - /// Find the appropriate renderer for the type of the - /// parameter. This is accomplished by calling the - /// method. Once a renderer is found, it is - /// applied on the object and the result is returned - /// as a . - /// - /// - public void FindAndRender(object obj, TextWriter writer) - { - if (obj == null) - { - writer.Write(SystemInfo.NullText); - } - else - { - // Optimisation for strings - string str = obj as string; - if (str != null) - { - writer.Write(str); - } - else - { - // Lookup the renderer for the specific type - try - { - this.Get(obj.GetType()).RenderObject(this, obj, writer); - } - catch (Exception ex) - { - // Exception rendering the object - log4net.Util.LogLog.Error(declaringType, "Exception while rendering object of type [" + obj.GetType().FullName + "]", ex); - - // return default message - string objectTypeName = string.Empty; - if (obj != null && obj.GetType() != null) - { - objectTypeName = obj.GetType().FullName; - } - - writer.Write("Exception rendering object type [" + objectTypeName + "]"); - if (ex != null) - { - string exceptionText = null; - - try - { - exceptionText = ex.ToString(); - } - catch - { - // Ignore exception - } - - writer.Write("" + exceptionText + ""); - } + /// + /// Render using the appropriate renderer. + /// + /// the object to render to a string + /// the object rendered as a string + /// + /// + /// This is a convenience method used to render an object to a string. + /// The alternative method + /// should be used when streaming output to a . + /// + /// + public string FindAndRender(object obj) + { + // Optimisation for strings + string strData = obj as String; + if (strData != null) + { + return strData; + } + + using (var stringWriter = new StringWriter(System.Globalization.CultureInfo.InvariantCulture)) + { + this.FindAndRender(obj, stringWriter); + return stringWriter.ToString(); + } + + } + + /// + /// Render using the appropriate renderer. + /// + /// the object to render to a string + /// The writer to render to + /// + /// + /// Find the appropriate renderer for the type of the + /// parameter. This is accomplished by calling the + /// method. Once a renderer is found, it is + /// applied on the object and the result is returned + /// as a . + /// + /// + public void FindAndRender(object obj, TextWriter writer) + { + if (obj == null) + { + writer.Write(SystemInfo.NullText); + } + else + { + // Optimisation for strings + string str = obj as string; + if (str != null) + { + writer.Write(str); + } + else + { + // Lookup the renderer for the specific type + try + { + this.Get(obj.GetType()).RenderObject(this, obj, writer); + } + catch(Exception ex) + { + // Exception rendering the object + LogLog.Error(declaringType, "Exception while rendering object of type ["+obj.GetType().FullName+"]", ex); + + // return default message + string objectTypeName = string.Empty; + if (obj != null && obj.GetType() != null) + { + objectTypeName = obj.GetType().FullName; + } + + writer.Write("Exception rendering object type ["+objectTypeName+"]"); + if (ex != null) + { + string exceptionText = null; + + try + { + exceptionText = ex.ToString(); + } + catch + { + // Ignore exception + } + + writer.Write("" + exceptionText + ""); + } + writer.Write(""); + } + } + } + } + + /// + /// Gets the renderer for the specified object type + /// + /// the object to lookup the renderer for + /// the renderer for + /// + /// + /// Gets the renderer for the specified object type. + /// + /// + /// Syntactic sugar method that calls + /// with the type of the object parameter. + /// + /// + public IObjectRenderer Get(Object obj) + { + if (obj == null) + { + return null; + } + else + { + return this.Get(obj.GetType()); + } + } + + /// + /// Gets the renderer for the specified type + /// + /// the type to lookup the renderer for + /// the renderer for the specified type + /// + /// + /// Returns the renderer for the specified type. + /// If no specific renderer has been defined the + /// will be returned. + /// + /// + public IObjectRenderer Get(Type type) + { + if (type == null) + { + throw new ArgumentNullException("type"); + } - writer.Write(""); - } - } - } - } - - /// - /// Gets the renderer for the specified object type. - /// - /// the object to lookup the renderer for. - /// the renderer for . - /// - /// - /// Gets the renderer for the specified object type. - /// - /// - /// Syntactic sugar method that calls - /// with the type of the object parameter. - /// - /// - public IObjectRenderer Get(object obj) - { - if (obj == null) - { - return null; - } - else - { - return this.Get(obj.GetType()); - } - } - - /// - /// Gets the renderer for the specified type. - /// - /// the type to lookup the renderer for. - /// the renderer for the specified type. - /// - /// - /// Returns the renderer for the specified type. - /// If no specific renderer has been defined the - /// will be returned. - /// - /// - public IObjectRenderer Get(Type type) - { - if (type == null) - { - throw new ArgumentNullException("type"); - } - - IObjectRenderer result = null; - - // Check cache - result = (IObjectRenderer)this.m_cache[type]; - - if (result == null) - { -#if NETSTANDARD1_3 - for (Type cur = type; cur != null; cur = cur.GetTypeInfo().BaseType) -#else - for (Type cur = type; cur != null; cur = cur.BaseType) -#endif - { - // Search the type's interfaces - result = this.SearchTypeAndInterfaces(cur); - if (result != null) - { - break; - } - } - - // if not set then use the default renderer - if (result == null) - { - result = s_defaultRenderer; - } - - // Add to cache - this.m_cache[type] = result; - } - - return result; - } - - /// - /// Internal function to recursively search interfaces. - /// - /// the type to lookup the renderer for. - /// the renderer for the specified type. - private IObjectRenderer SearchTypeAndInterfaces(Type type) - { - IObjectRenderer r = (IObjectRenderer)this.m_map[type]; - if (r != null) - { - return r; - } - else - { - foreach (Type t in type.GetInterfaces()) - { - r = this.SearchTypeAndInterfaces(t); - if (r != null) - { - return r; - } - } - } + IObjectRenderer result = null; + + // Check cache + result = (IObjectRenderer)this.m_cache[type]; + + if (result == null) + { +#if NETSTANDARD1_3 + for (Type cur = type; cur != null; cur = cur.GetTypeInfo().BaseType) +#else + for(Type cur = type; cur != null; cur = cur.BaseType) +#endif + { + // Search the type's interfaces + result = this.SearchTypeAndInterfaces(cur); + if (result != null) + { + break; + } + } + + // if not set then use the default renderer + if (result == null) + { + result = s_defaultRenderer; + } + + // Add to cache + this.m_cache[type] = result; + } + + return result; + } + + /// + /// Internal function to recursively search interfaces + /// + /// the type to lookup the renderer for + /// the renderer for the specified type + private IObjectRenderer SearchTypeAndInterfaces(Type type) + { + IObjectRenderer r = (IObjectRenderer)this.m_map[type]; + if (r != null) + { + return r; + } + else + { + foreach(Type t in type.GetInterfaces()) + { + r = this.SearchTypeAndInterfaces(t); + if (r != null) + { + return r; + } + } + } + return null; + } + + /// + /// Get the default renderer instance + /// + /// the default renderer + /// + /// + /// Get the default renderer + /// + /// + public IObjectRenderer DefaultRenderer + { + get { return s_defaultRenderer; } + } + + /// + /// Clear the map of renderers + /// + /// + /// + /// Clear the custom renderers defined by using + /// . The + /// cannot be removed. + /// + /// + public void Clear() + { + this.m_map.Clear(); + this.m_cache.Clear(); + } + + /// + /// Register an for . + /// + /// the type that will be rendered by + /// the renderer for + /// + /// + /// Register an object renderer for a specific source type. + /// This renderer will be returned from a call to + /// specifying the same as an argument. + /// + /// + public void Put(Type typeToRender, IObjectRenderer renderer) + { + this.m_cache.Clear(); - return null; - } - - /// - /// Gets get the default renderer instance. - /// - /// the default renderer. - /// - /// - /// Get the default renderer. - /// - /// - public IObjectRenderer DefaultRenderer - { - get { return s_defaultRenderer; } - } - - /// - /// Clear the map of renderers. - /// - /// - /// - /// Clear the custom renderers defined by using - /// . The - /// cannot be removed. - /// - /// - public void Clear() - { - this.m_map.Clear(); - this.m_cache.Clear(); - } - - /// - /// Register an for . - /// - /// the type that will be rendered by . - /// the renderer for . - /// - /// - /// Register an object renderer for a specific source type. - /// This renderer will be returned from a call to - /// specifying the same as an argument. - /// - /// - public void Put(Type typeToRender, IObjectRenderer renderer) - { - this.m_cache.Clear(); - - if (typeToRender == null) - { - throw new ArgumentNullException("typeToRender"); - } + if (typeToRender == null) + { + throw new ArgumentNullException("typeToRender"); + } + if (renderer == null) + { + throw new ArgumentNullException("renderer"); + } - if (renderer == null) - { - throw new ArgumentNullException("renderer"); - } - - this.m_map[typeToRender] = renderer; - } - } -} + this.m_map[typeToRender] = renderer; + } + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Plugin/IPlugin.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Plugin/IPlugin.cs index 7e96570b39a..3f8a915db1e 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Plugin/IPlugin.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Plugin/IPlugin.cs @@ -1,86 +1,86 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.Plugin -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using log4net.Repository; +using log4net.Repository; - /// - /// Interface implemented by logger repository plugins. - /// - /// - /// - /// Plugins define additional behavior that can be associated - /// with a . - /// The held by the - /// property is used to store the plugins for a repository. - /// - /// - /// The log4net.Config.PluginAttribute can be used to - /// attach plugins to repositories created using configuration - /// attributes. - /// - /// - /// Nicko Cadell. - /// Gert Driesen. - public interface IPlugin - { - /// - /// Gets the name of the plugin. - /// - /// - /// The name of the plugin. - /// - /// - /// - /// Plugins are stored in the - /// keyed by name. Each plugin instance attached to a - /// repository must be a unique name. - /// - /// - string Name { get; } - - /// - /// Attaches the plugin to the specified . - /// - /// The that this plugin should be attached to. - /// - /// - /// A plugin may only be attached to a single repository. - /// - /// - /// This method is called when the plugin is attached to the repository. - /// - /// - void Attach(ILoggerRepository repository); - - /// - /// Is called when the plugin is to shutdown. - /// - /// - /// - /// This method is called to notify the plugin that - /// it should stop operating and should detach from - /// the repository. - /// - /// - void Shutdown(); - } -} +namespace log4net.Plugin +{ + /// + /// Interface implemented by logger repository plugins. + /// + /// + /// + /// Plugins define additional behavior that can be associated + /// with a . + /// The held by the + /// property is used to store the plugins for a repository. + /// + /// + /// The log4net.Config.PluginAttribute can be used to + /// attach plugins to repositories created using configuration + /// attributes. + /// + /// + /// Nicko Cadell + /// Gert Driesen + public interface IPlugin + { + /// + /// Gets the name of the plugin. + /// + /// + /// The name of the plugin. + /// + /// + /// + /// Plugins are stored in the + /// keyed by name. Each plugin instance attached to a + /// repository must be a unique name. + /// + /// + string Name { get; } + + /// + /// Attaches the plugin to the specified . + /// + /// The that this plugin should be attached to. + /// + /// + /// A plugin may only be attached to a single repository. + /// + /// + /// This method is called when the plugin is attached to the repository. + /// + /// + void Attach(ILoggerRepository repository); + + /// + /// Is called when the plugin is to shutdown. + /// + /// + /// + /// This method is called to notify the plugin that + /// it should stop operating and should detach from + /// the repository. + /// + /// + void Shutdown(); + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Plugin/IPluginFactory.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Plugin/IPluginFactory.cs index 153a60523bb..2d701af406d 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Plugin/IPluginFactory.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Plugin/IPluginFactory.cs @@ -1,46 +1,46 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information - -// +// // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at -// +// // http://www.apache.org/licenses/LICENSE-2.0 -// +// // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. -// -namespace log4net.Plugin -{ - /// - /// Interface used to create plugins. - /// - /// - /// - /// Interface used to create a plugin. - /// - /// - /// Nicko Cadell. - /// Gert Driesen. - public interface IPluginFactory - { - /// - /// Creates the plugin object. - /// - /// the new plugin instance. - /// - /// - /// Create and return a new plugin instance. - /// - /// - IPlugin CreatePlugin(); - } -} +// + +namespace log4net.Plugin +{ + /// + /// Interface used to create plugins. + /// + /// + /// + /// Interface used to create a plugin. + /// + /// + /// Nicko Cadell + /// Gert Driesen + public interface IPluginFactory + { + /// + /// Creates the plugin object. + /// + /// the new plugin instance + /// + /// + /// Create and return a new plugin instance. + /// + /// + IPlugin CreatePlugin(); + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Plugin/PluginCollection.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Plugin/PluginCollection.cs index 2b55fd75742..e3132b4ad16 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Plugin/PluginCollection.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Plugin/PluginCollection.cs @@ -1,797 +1,784 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information - -namespace log4net.Plugin -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; - using System.Collections; - - /// - /// A strongly-typed collection of objects. - /// - /// Nicko Cadell. - public class PluginCollection : ICollection, IList, IEnumerable -#if !NETSTANDARD1_3 - , ICloneable -#endif +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +using System; +using System.Collections; + +namespace log4net.Plugin +{ + /// + /// A strongly-typed collection of objects. + /// + /// Nicko Cadell + public class PluginCollection : ICollection, IList, IEnumerable +#if !NETSTANDARD1_3 + , ICloneable +#endif { - /// - /// Supports type-safe iteration over a . - /// - /// - public interface IPluginCollectionEnumerator - { - /// - /// Gets the current element in the collection. - /// - IPlugin Current { get; } - - /// - /// Advances the enumerator to the next element in the collection. - /// - /// - /// true if the enumerator was successfully advanced to the next element; - /// false if the enumerator has passed the end of the collection. - /// - /// - /// The collection was modified after the enumerator was created. - /// - bool MoveNext(); - - /// - /// Sets the enumerator to its initial position, before the first element in the collection. - /// - void Reset(); + /// + /// Supports type-safe iteration over a . + /// + /// + public interface IPluginCollectionEnumerator + { + /// + /// Gets the current element in the collection. + /// + IPlugin Current { get; } + + /// + /// Advances the enumerator to the next element in the collection. + /// + /// + /// true if the enumerator was successfully advanced to the next element; + /// false if the enumerator has passed the end of the collection. + /// + /// + /// The collection was modified after the enumerator was created. + /// + bool MoveNext(); + + /// + /// Sets the enumerator to its initial position, before the first element in the collection. + /// + void Reset(); } private const int DEFAULT_CAPACITY = 16; - private IPlugin[] m_array; - private int m_count = 0; + + private IPlugin[] m_array; + private int m_count = 0; private int m_version = 0; - /// - /// Creates a read-only wrapper for a PluginCollection instance. - /// - /// list to create a readonly wrapper arround. - /// - /// A PluginCollection wrapper that is read-only. - /// - public static PluginCollection ReadOnly(PluginCollection list) - { - if (list == null) + /// + /// Creates a read-only wrapper for a PluginCollection instance. + /// + /// list to create a readonly wrapper arround + /// + /// A PluginCollection wrapper that is read-only. + /// + public static PluginCollection ReadOnly(PluginCollection list) + { + if(list == null) { throw new ArgumentNullException("list"); } - return new ReadOnlyPluginCollection(list); - } - - /// - /// Initializes a new instance of the class. - /// Initializes a new instance of the PluginCollection class - /// that is empty and has the default initial capacity. - /// - public PluginCollection() - { - this.m_array = new IPlugin[DEFAULT_CAPACITY]; - } - - /// - /// Initializes a new instance of the class. - /// Initializes a new instance of the PluginCollection class - /// that has the specified initial capacity. - /// - /// - /// The number of elements that the new PluginCollection is initially capable of storing. - /// - public PluginCollection(int capacity) - { - this.m_array = new IPlugin[capacity]; - } - - /// - /// Initializes a new instance of the class. - /// Initializes a new instance of the PluginCollection class - /// that contains elements copied from the specified PluginCollection. - /// - /// The PluginCollection whose elements are copied to the new collection. - public PluginCollection(PluginCollection c) - { - this.m_array = new IPlugin[c.Count]; - this.AddRange(c); - } - - /// - /// Initializes a new instance of the class. - /// Initializes a new instance of the PluginCollection class - /// that contains elements copied from the specified array. - /// - /// The array whose elements are copied to the new list. - public PluginCollection(IPlugin[] a) - { - this.m_array = new IPlugin[a.Length]; - this.AddRange(a); - } - - /// - /// Initializes a new instance of the class. - /// Initializes a new instance of the PluginCollection class - /// that contains elements copied from the specified collection. - /// - /// The collection whose elements are copied to the new list. - public PluginCollection(ICollection col) - { - this.m_array = new IPlugin[col.Count]; - this.AddRange(col); - } - - /// - /// Type visible only to our subclasses - /// Used to access protected constructor. - /// - /// - protected internal enum Tag - { - /// - /// A value - /// - Default, - } - - /// - /// Initializes a new instance of the class. - /// Allow subclasses to avoid our default constructors. - /// - /// - /// - protected internal PluginCollection(Tag tag) - { - this.m_array = null; - } - - /// - /// Gets the number of elements actually contained in the PluginCollection. - /// - public virtual int Count - { - get { return this.m_count; } - } - - /// - /// Copies the entire PluginCollection to a one-dimensional - /// array. - /// - /// The one-dimensional array to copy to. - public virtual void CopyTo(IPlugin[] array) - { - this.CopyTo(array, 0); - } - - /// - /// Copies the entire PluginCollection to a one-dimensional - /// array, starting at the specified index of the target array. - /// - /// The one-dimensional array to copy to. - /// The zero-based index in at which copying begins. - public virtual void CopyTo(IPlugin[] array, int start) - { - if (this.m_count > array.GetUpperBound(0) + 1 - start) - { - throw new System.ArgumentException("Destination array was not long enough."); - } - - Array.Copy(this.m_array, 0, array, start, this.m_count); - } - - /// - /// Gets a value indicating whether access to the collection is synchronized (thread-safe). - /// - /// false, because the backing type is an array, which is never thread-safe. - public virtual bool IsSynchronized - { - get { return false; } - } - - /// - /// Gets an object that can be used to synchronize access to the collection. - /// - /// - /// An object that can be used to synchronize access to the collection. - /// - public virtual object SyncRoot - { - get { return this.m_array; } - } - - /// - /// Gets or sets the at the specified index. - /// - /// - /// The at the specified index. - /// - /// The zero-based index of the element to get or set. - /// - /// is less than zero. - /// -or- - /// is equal to or greater than . - /// - public virtual IPlugin this[int index] - { - get - { - this.ValidateIndex(index); // throws - return this.m_array[index]; - } - - set - { - this.ValidateIndex(index); // throws - ++this.m_version; - this.m_array[index] = value; - } - } - - /// - /// Adds a to the end of the PluginCollection. - /// - /// The to be added to the end of the PluginCollection. - /// The index at which the value has been added. - public virtual int Add(IPlugin item) - { - if (this.m_count == this.m_array.Length) - { - this.EnsureCapacity(this.m_count + 1); - } - - this.m_array[this.m_count] = item; - this.m_version++; - - return this.m_count++; - } - - /// - /// Removes all elements from the PluginCollection. - /// - public virtual void Clear() - { - ++this.m_version; - this.m_array = new IPlugin[DEFAULT_CAPACITY]; - this.m_count = 0; - } - - /// - /// Creates a shallow copy of the . - /// - /// A new with a shallow copy of the collection data. - public virtual object Clone() - { - PluginCollection newCol = new PluginCollection(this.m_count); - Array.Copy(this.m_array, 0, newCol.m_array, 0, this.m_count); - newCol.m_count = this.m_count; - newCol.m_version = this.m_version; - - return newCol; - } - - /// - /// Determines whether a given is in the PluginCollection. - /// - /// The to check for. - /// true if is found in the PluginCollection; otherwise, false. - public virtual bool Contains(IPlugin item) - { - for (int i = 0; i != this.m_count; ++i) - { - if (this.m_array[i].Equals(item)) - { - return true; - } - } - - return false; - } - - /// - /// Returns the zero-based index of the first occurrence of a - /// in the PluginCollection. - /// - /// The to locate in the PluginCollection. - /// - /// The zero-based index of the first occurrence of - /// in the entire PluginCollection, if found; otherwise, -1. - /// - public virtual int IndexOf(IPlugin item) - { - for (int i = 0; i != this.m_count; ++i) - { - if (this.m_array[i].Equals(item)) - { - return i; - } - } - - return -1; - } - - /// - /// Inserts an element into the PluginCollection at the specified index. - /// - /// The zero-based index at which should be inserted. - /// The to insert. - /// - /// is less than zero. - /// -or- - /// is equal to or greater than . - /// - public virtual void Insert(int index, IPlugin item) - { - this.ValidateIndex(index, true); // throws - - if (this.m_count == this.m_array.Length) - { - this.EnsureCapacity(this.m_count + 1); - } - - if (index < this.m_count) - { - Array.Copy(this.m_array, index, this.m_array, index + 1, this.m_count - index); - } - - this.m_array[index] = item; - this.m_count++; - this.m_version++; - } - - /// - /// Removes the first occurrence of a specific from the PluginCollection. - /// - /// The to remove from the PluginCollection. - /// - /// The specified was not found in the PluginCollection. - /// - public virtual void Remove(IPlugin item) - { - int i = this.IndexOf(item); - if (i < 0) - { - throw new System.ArgumentException("Cannot remove the specified item because it was not found in the specified Collection."); - } - - ++this.m_version; - this.RemoveAt(i); - } - - /// - /// Removes the element at the specified index of the PluginCollection. - /// - /// The zero-based index of the element to remove. - /// - /// is less than zero. - /// -or- - /// is equal to or greater than . - /// - public virtual void RemoveAt(int index) - { - this.ValidateIndex(index); // throws - - this.m_count--; - - if (index < this.m_count) - { - Array.Copy(this.m_array, index + 1, this.m_array, index, this.m_count - index); - } - - // We can't set the deleted entry equal to null, because it might be a value type. - // Instead, we'll create an empty single-element array of the right type and copy it - // over the entry we want to erase. - IPlugin[] temp = new IPlugin[1]; - Array.Copy(temp, 0, this.m_array, this.m_count, 1); - this.m_version++; - } - - /// - /// Gets a value indicating whether the collection has a fixed size. - /// - /// true if the collection has a fixed size; otherwise, false. The default is false. - public virtual bool IsFixedSize - { - get { return false; } - } - - /// - /// Gets a value indicating whether the IList is read-only. - /// - /// true if the collection is read-only; otherwise, false. The default is false. - public virtual bool IsReadOnly - { - get { return false; } - } - - /// - /// Returns an enumerator that can iterate through the PluginCollection. - /// - /// An for the entire PluginCollection. - public virtual IPluginCollectionEnumerator GetEnumerator() - { - return new Enumerator(this); - } - - /// - /// Gets or sets the number of elements the PluginCollection can contain. - /// - /// - /// The number of elements the PluginCollection can contain. - /// - public virtual int Capacity - { - get - { - return this.m_array.Length; - } - - set - { - if (value < this.m_count) - { - value = this.m_count; - } - - if (value != this.m_array.Length) - { - if (value > 0) - { - IPlugin[] temp = new IPlugin[value]; - Array.Copy(this.m_array, 0, temp, 0, this.m_count); - this.m_array = temp; - } - else - { - this.m_array = new IPlugin[DEFAULT_CAPACITY]; - } - } - } - } - - /// - /// Adds the elements of another PluginCollection to the current PluginCollection. - /// - /// The PluginCollection whose elements should be added to the end of the current PluginCollection. - /// The new of the PluginCollection. - public virtual int AddRange(PluginCollection x) - { - if (this.m_count + x.Count >= this.m_array.Length) - { - this.EnsureCapacity(this.m_count + x.Count); - } - - Array.Copy(x.m_array, 0, this.m_array, this.m_count, x.Count); - this.m_count += x.Count; - this.m_version++; - - return this.m_count; - } - - /// - /// Adds the elements of a array to the current PluginCollection. - /// - /// The array whose elements should be added to the end of the PluginCollection. - /// The new of the PluginCollection. - public virtual int AddRange(IPlugin[] x) - { - if (this.m_count + x.Length >= this.m_array.Length) - { - this.EnsureCapacity(this.m_count + x.Length); - } - - Array.Copy(x, 0, this.m_array, this.m_count, x.Length); - this.m_count += x.Length; - this.m_version++; - - return this.m_count; - } - - /// - /// Adds the elements of a collection to the current PluginCollection. - /// - /// The collection whose elements should be added to the end of the PluginCollection. - /// The new of the PluginCollection. - public virtual int AddRange(ICollection col) - { - if (this.m_count + col.Count >= this.m_array.Length) - { - this.EnsureCapacity(this.m_count + col.Count); - } - - foreach (object item in col) - { - this.Add((IPlugin)item); - } - - return this.m_count; - } - - /// - /// Sets the capacity to the actual number of elements. - /// - public virtual void TrimToSize() - { - this.Capacity = this.m_count; - } - - /// - /// is less than zero. - /// -or- - /// is equal to or greater than . - /// - private void ValidateIndex(int i) - { - this.ValidateIndex(i, false); - } - - /// - /// is less than zero. - /// -or- - /// is equal to or greater than . - /// - private void ValidateIndex(int i, bool allowEqualEnd) - { - int max = allowEqualEnd ? this.m_count : (this.m_count - 1); - if (i < 0 || i > max) - { - throw log4net.Util.SystemInfo.CreateArgumentOutOfRangeException("i", (object)i, "Index was out of range. Must be non-negative and less than the size of the collection. [" + (object)i + "] Specified argument was out of the range of valid values."); - } - } - - private void EnsureCapacity(int min) - { - int newCapacity = (this.m_array.Length == 0) ? DEFAULT_CAPACITY : this.m_array.Length * 2; - if (newCapacity < min) - { - newCapacity = min; - } - - this.Capacity = newCapacity; - } - - void ICollection.CopyTo(Array array, int start) - { - Array.Copy(this.m_array, 0, array, start, this.m_count); - } - - object IList.this[int i] - { - get { return (object)this[i]; } - set { this[i] = (IPlugin)value; } - } - - int IList.Add(object x) - { - return this.Add((IPlugin)x); - } - - bool IList.Contains(object x) - { - return this.Contains((IPlugin)x); - } - - int IList.IndexOf(object x) - { - return this.IndexOf((IPlugin)x); - } - - void IList.Insert(int pos, object x) - { - this.Insert(pos, (IPlugin)x); - } - - void IList.Remove(object x) - { - this.Remove((IPlugin)x); - } - - void IList.RemoveAt(int pos) - { - this.RemoveAt(pos); - } - - IEnumerator IEnumerable.GetEnumerator() - { - return (IEnumerator)this.GetEnumerator(); - } - - /// - /// Supports simple iteration over a . - /// - /// - private sealed class Enumerator : IEnumerator, IPluginCollectionEnumerator - { - private readonly PluginCollection m_collection; - private int m_index; + return new ReadOnlyPluginCollection(list); + } + + /// + /// Initializes a new instance of the PluginCollection class + /// that is empty and has the default initial capacity. + /// + public PluginCollection() + { + this.m_array = new IPlugin[DEFAULT_CAPACITY]; + } + + /// + /// Initializes a new instance of the PluginCollection class + /// that has the specified initial capacity. + /// + /// + /// The number of elements that the new PluginCollection is initially capable of storing. + /// + public PluginCollection(int capacity) + { + this.m_array = new IPlugin[capacity]; + } + + /// + /// Initializes a new instance of the PluginCollection class + /// that contains elements copied from the specified PluginCollection. + /// + /// The PluginCollection whose elements are copied to the new collection. + public PluginCollection(PluginCollection c) + { + this.m_array = new IPlugin[c.Count]; + this.AddRange(c); + } + + /// + /// Initializes a new instance of the PluginCollection class + /// that contains elements copied from the specified array. + /// + /// The array whose elements are copied to the new list. + public PluginCollection(IPlugin[] a) + { + this.m_array = new IPlugin[a.Length]; + this.AddRange(a); + } + + /// + /// Initializes a new instance of the PluginCollection class + /// that contains elements copied from the specified collection. + /// + /// The collection whose elements are copied to the new list. + public PluginCollection(ICollection col) + { + this.m_array = new IPlugin[col.Count]; + this.AddRange(col); + } + + /// + /// Type visible only to our subclasses + /// Used to access protected constructor + /// + /// + protected internal enum Tag + { + /// + /// A value + /// + Default + } + + /// + /// Allow subclasses to avoid our default constructors + /// + /// + /// + protected internal PluginCollection(Tag tag) + { + this.m_array = null; + } + + /// + /// Gets the number of elements actually contained in the PluginCollection. + /// + public virtual int Count + { + get { return this.m_count; } + } + + /// + /// Copies the entire PluginCollection to a one-dimensional + /// array. + /// + /// The one-dimensional array to copy to. + public virtual void CopyTo(IPlugin[] array) + { + this.CopyTo(array, 0); + } + + /// + /// Copies the entire PluginCollection to a one-dimensional + /// array, starting at the specified index of the target array. + /// + /// The one-dimensional array to copy to. + /// The zero-based index in at which copying begins. + public virtual void CopyTo(IPlugin[] array, int start) + { + if (this.m_count > array.GetUpperBound(0) + 1 - start) + { + throw new ArgumentException("Destination array was not long enough."); + } + + Array.Copy(this.m_array, 0, array, start, this.m_count); + } + + /// + /// Gets a value indicating whether access to the collection is synchronized (thread-safe). + /// + /// false, because the backing type is an array, which is never thread-safe. + public virtual bool IsSynchronized + { + get { return false; } + } + + /// + /// Gets an object that can be used to synchronize access to the collection. + /// + /// + /// An object that can be used to synchronize access to the collection. + /// + public virtual object SyncRoot + { + get { return this.m_array; } + } + + /// + /// Gets or sets the at the specified index. + /// + /// + /// The at the specified index. + /// + /// The zero-based index of the element to get or set. + /// + /// is less than zero. + /// -or- + /// is equal to or greater than . + /// + public virtual IPlugin this[int index] + { + get + { + this.ValidateIndex(index); // throws + return this.m_array[index]; + } + set + { + this.ValidateIndex(index); // throws + ++this.m_version; + this.m_array[index] = value; + } + } + + /// + /// Adds a to the end of the PluginCollection. + /// + /// The to be added to the end of the PluginCollection. + /// The index at which the value has been added. + public virtual int Add(IPlugin item) + { + if (this.m_count == this.m_array.Length) + { + this.EnsureCapacity(this.m_count + 1); + } + + this.m_array[this.m_count] = item; + this.m_version++; + + return this.m_count++; + } + + /// + /// Removes all elements from the PluginCollection. + /// + public virtual void Clear() + { + ++this.m_version; + this.m_array = new IPlugin[DEFAULT_CAPACITY]; + this.m_count = 0; + } + + /// + /// Creates a shallow copy of the . + /// + /// A new with a shallow copy of the collection data. + public virtual object Clone() + { + PluginCollection newCol = new PluginCollection(this.m_count); + Array.Copy(this.m_array, 0, newCol.m_array, 0, this.m_count); + newCol.m_count = this.m_count; + newCol.m_version = this.m_version; + + return newCol; + } + + /// + /// Determines whether a given is in the PluginCollection. + /// + /// The to check for. + /// true if is found in the PluginCollection; otherwise, false. + public virtual bool Contains(IPlugin item) + { + for (int i = 0; i != this.m_count; ++i) + { + if (this.m_array[i].Equals(item)) + { + return true; + } + } + return false; + } + + /// + /// Returns the zero-based index of the first occurrence of a + /// in the PluginCollection. + /// + /// The to locate in the PluginCollection. + /// + /// The zero-based index of the first occurrence of + /// in the entire PluginCollection, if found; otherwise, -1. + /// + public virtual int IndexOf(IPlugin item) + { + for (int i = 0; i != this.m_count; ++i) + { + if (this.m_array[i].Equals(item)) + { + return i; + } + } + return -1; + } + + /// + /// Inserts an element into the PluginCollection at the specified index. + /// + /// The zero-based index at which should be inserted. + /// The to insert. + /// + /// is less than zero + /// -or- + /// is equal to or greater than . + /// + public virtual void Insert(int index, IPlugin item) + { + this.ValidateIndex(index, true); // throws + + if (this.m_count == this.m_array.Length) + { + this.EnsureCapacity(this.m_count + 1); + } + + if (index < this.m_count) + { + Array.Copy(this.m_array, index, this.m_array, index + 1, this.m_count - index); + } + + this.m_array[index] = item; + this.m_count++; + this.m_version++; + } + + /// + /// Removes the first occurrence of a specific from the PluginCollection. + /// + /// The to remove from the PluginCollection. + /// + /// The specified was not found in the PluginCollection. + /// + public virtual void Remove(IPlugin item) + { + int i = this.IndexOf(item); + if (i < 0) + { + throw new ArgumentException("Cannot remove the specified item because it was not found in the specified Collection."); + } + ++this.m_version; + this.RemoveAt(i); + } + + /// + /// Removes the element at the specified index of the PluginCollection. + /// + /// The zero-based index of the element to remove. + /// + /// is less than zero. + /// -or- + /// is equal to or greater than . + /// + public virtual void RemoveAt(int index) + { + this.ValidateIndex(index); // throws + + this.m_count--; + + if (index < this.m_count) + { + Array.Copy(this.m_array, index + 1, this.m_array, index, this.m_count - index); + } + + // We can't set the deleted entry equal to null, because it might be a value type. + // Instead, we'll create an empty single-element array of the right type and copy it + // over the entry we want to erase. + IPlugin[] temp = new IPlugin[1]; + Array.Copy(temp, 0, this.m_array, this.m_count, 1); + this.m_version++; + } + + /// + /// Gets a value indicating whether the collection has a fixed size. + /// + /// true if the collection has a fixed size; otherwise, false. The default is false. + public virtual bool IsFixedSize + { + get { return false; } + } + + /// + /// Gets a value indicating whether the IList is read-only. + /// + /// true if the collection is read-only; otherwise, false. The default is false. + public virtual bool IsReadOnly + { + get { return false; } + } + + /// + /// Returns an enumerator that can iterate through the PluginCollection. + /// + /// An for the entire PluginCollection. + public virtual IPluginCollectionEnumerator GetEnumerator() + { + return new Enumerator(this); + } + + /// + /// Gets or sets the number of elements the PluginCollection can contain. + /// + /// + /// The number of elements the PluginCollection can contain. + /// + public virtual int Capacity + { + get + { + return this.m_array.Length; + } + set + { + if (value < this.m_count) + { + value = this.m_count; + } + + if (value != this.m_array.Length) + { + if (value > 0) + { + IPlugin[] temp = new IPlugin[value]; + Array.Copy(this.m_array, 0, temp, 0, this.m_count); + this.m_array = temp; + } + else + { + this.m_array = new IPlugin[DEFAULT_CAPACITY]; + } + } + } + } + + /// + /// Adds the elements of another PluginCollection to the current PluginCollection. + /// + /// The PluginCollection whose elements should be added to the end of the current PluginCollection. + /// The new of the PluginCollection. + public virtual int AddRange(PluginCollection x) + { + if (this.m_count + x.Count >= this.m_array.Length) + { + this.EnsureCapacity(this.m_count + x.Count); + } + + Array.Copy(x.m_array, 0, this.m_array, this.m_count, x.Count); + this.m_count += x.Count; + this.m_version++; + + return this.m_count; + } + + /// + /// Adds the elements of a array to the current PluginCollection. + /// + /// The array whose elements should be added to the end of the PluginCollection. + /// The new of the PluginCollection. + public virtual int AddRange(IPlugin[] x) + { + if (this.m_count + x.Length >= this.m_array.Length) + { + this.EnsureCapacity(this.m_count + x.Length); + } + + Array.Copy(x, 0, this.m_array, this.m_count, x.Length); + this.m_count += x.Length; + this.m_version++; + + return this.m_count; + } + + /// + /// Adds the elements of a collection to the current PluginCollection. + /// + /// The collection whose elements should be added to the end of the PluginCollection. + /// The new of the PluginCollection. + public virtual int AddRange(ICollection col) + { + if (this.m_count + col.Count >= this.m_array.Length) + { + this.EnsureCapacity(this.m_count + col.Count); + } + + foreach(object item in col) + { + this.Add((IPlugin)item); + } + + return this.m_count; + } + + /// + /// Sets the capacity to the actual number of elements. + /// + public virtual void TrimToSize() + { + this.Capacity = this.m_count; + } + + /// + /// is less than zero. + /// -or- + /// is equal to or greater than . + /// + private void ValidateIndex(int i) + { + this.ValidateIndex(i, false); + } + + /// + /// is less than zero. + /// -or- + /// is equal to or greater than . + /// + private void ValidateIndex(int i, bool allowEqualEnd) + { + int max = (allowEqualEnd) ? (this.m_count) : (this.m_count-1); + if (i < 0 || i > max) + { + throw Util.SystemInfo.CreateArgumentOutOfRangeException("i", (object)i, "Index was out of range. Must be non-negative and less than the size of the collection. [" + (object)i + "] Specified argument was out of the range of valid values."); + } + } + + private void EnsureCapacity(int min) + { + int newCapacity = ((this.m_array.Length == 0) ? DEFAULT_CAPACITY : this.m_array.Length * 2); + if (newCapacity < min) + { + newCapacity = min; + } + + this.Capacity = newCapacity; + } + + void ICollection.CopyTo(Array array, int start) + { + Array.Copy(this.m_array, 0, array, start, this.m_count); + } + + object IList.this[int i] + { + get { return (object)this[i]; } + set { this[i] = (IPlugin)value; } + } + + int IList.Add(object x) + { + return this.Add((IPlugin)x); + } + + bool IList.Contains(object x) + { + return this.Contains((IPlugin)x); + } + + int IList.IndexOf(object x) + { + return this.IndexOf((IPlugin)x); + } + + void IList.Insert(int pos, object x) + { + this.Insert(pos, (IPlugin)x); + } + + void IList.Remove(object x) + { + this.Remove((IPlugin)x); + } + + void IList.RemoveAt(int pos) + { + this.RemoveAt(pos); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return (IEnumerator)(this.GetEnumerator()); + } + + /// + /// Supports simple iteration over a . + /// + /// + private sealed class Enumerator : IEnumerator, IPluginCollectionEnumerator + { + private readonly PluginCollection m_collection; + private int m_index; private int m_version; /// - /// Initializes a new instance of the class. - /// Initializes a new instance of the Enumerator class. - /// - /// - internal Enumerator(PluginCollection tc) - { - this.m_collection = tc; - this.m_index = -1; - this.m_version = tc.m_version; - } - - /// - /// Gets the current element in the collection. - /// - /// - /// The current element in the collection. - /// - public IPlugin Current - { - get { return this.m_collection[this.m_index]; } - } - - /// - /// Advances the enumerator to the next element in the collection. - /// - /// - /// true if the enumerator was successfully advanced to the next element; - /// false if the enumerator has passed the end of the collection. - /// - /// - /// The collection was modified after the enumerator was created. - /// - public bool MoveNext() - { - if (this.m_version != this.m_collection.m_version) - { - throw new System.InvalidOperationException("Collection was modified; enumeration operation may not execute."); - } - - ++this.m_index; - return this.m_index < this.m_collection.Count; - } - - /// - /// Sets the enumerator to its initial position, before the first element in the collection. - /// - public void Reset() - { - this.m_index = -1; - } - - object IEnumerator.Current - { - get { return this.Current; } - } - } - - /// - private sealed class ReadOnlyPluginCollection : PluginCollection + /// Initializes a new instance of the Enumerator class. + /// + /// + internal Enumerator(PluginCollection tc) + { + this.m_collection = tc; + this.m_index = -1; + this.m_version = tc.m_version; + } + + /// + /// Gets the current element in the collection. + /// + /// + /// The current element in the collection. + /// + public IPlugin Current + { + get { return this.m_collection[this.m_index]; } + } + + /// + /// Advances the enumerator to the next element in the collection. + /// + /// + /// true if the enumerator was successfully advanced to the next element; + /// false if the enumerator has passed the end of the collection. + /// + /// + /// The collection was modified after the enumerator was created. + /// + public bool MoveNext() + { + if (this.m_version != this.m_collection.m_version) + { + throw new InvalidOperationException("Collection was modified; enumeration operation may not execute."); + } + + ++this.m_index; + return (this.m_index < this.m_collection.Count); + } + + /// + /// Sets the enumerator to its initial position, before the first element in the collection. + /// + public void Reset() + { + this.m_index = -1; + } + + object IEnumerator.Current + { + get { return this.Current; } + } + } + + /// + private sealed class ReadOnlyPluginCollection : PluginCollection { private readonly PluginCollection m_collection; - internal ReadOnlyPluginCollection(PluginCollection list) - : base(Tag.Default) - { - this.m_collection = list; - } - - public override void CopyTo(IPlugin[] array) - { - this.m_collection.CopyTo(array); - } - - public override void CopyTo(IPlugin[] array, int start) - { - this.m_collection.CopyTo(array, start); - } - - public override int Count - { - get { return this.m_collection.Count; } - } - - public override bool IsSynchronized - { - get { return this.m_collection.IsSynchronized; } - } - - public override object SyncRoot - { - get { return this.m_collection.SyncRoot; } - } - - public override IPlugin this[int i] - { - get { return this.m_collection[i]; } - set { throw new NotSupportedException("This is a Read Only Collection and can not be modified"); } - } - - public override int Add(IPlugin x) - { - throw new NotSupportedException("This is a Read Only Collection and can not be modified"); - } - - public override void Clear() - { - throw new NotSupportedException("This is a Read Only Collection and can not be modified"); - } - - public override bool Contains(IPlugin x) - { - return this.m_collection.Contains(x); - } - - public override int IndexOf(IPlugin x) - { - return this.m_collection.IndexOf(x); - } - - public override void Insert(int pos, IPlugin x) - { - throw new NotSupportedException("This is a Read Only Collection and can not be modified"); - } - - public override void Remove(IPlugin x) - { - throw new NotSupportedException("This is a Read Only Collection and can not be modified"); - } - - public override void RemoveAt(int pos) - { - throw new NotSupportedException("This is a Read Only Collection and can not be modified"); - } - - public override bool IsFixedSize - { - get { return true; } - } - - public override bool IsReadOnly - { - get { return true; } - } - - public override IPluginCollectionEnumerator GetEnumerator() - { - return this.m_collection.GetEnumerator(); + internal ReadOnlyPluginCollection(PluginCollection list) : base(Tag.Default) + { + this.m_collection = list; + } + + public override void CopyTo(IPlugin[] array) + { + this.m_collection.CopyTo(array); + } + + public override void CopyTo(IPlugin[] array, int start) + { + this.m_collection.CopyTo(array,start); + } + public override int Count + { + get { return this.m_collection.Count; } + } + + public override bool IsSynchronized + { + get { return this.m_collection.IsSynchronized; } + } + + public override object SyncRoot + { + get { return this.m_collection.SyncRoot; } + } + + public override IPlugin this[int i] + { + get { return this.m_collection[i]; } + set { throw new NotSupportedException("This is a Read Only Collection and can not be modified"); } + } + + public override int Add(IPlugin x) + { + throw new NotSupportedException("This is a Read Only Collection and can not be modified"); + } + + public override void Clear() + { + throw new NotSupportedException("This is a Read Only Collection and can not be modified"); + } + + public override bool Contains(IPlugin x) + { + return this.m_collection.Contains(x); + } + + public override int IndexOf(IPlugin x) + { + return this.m_collection.IndexOf(x); + } + + public override void Insert(int pos, IPlugin x) + { + throw new NotSupportedException("This is a Read Only Collection and can not be modified"); + } + + public override void Remove(IPlugin x) + { + throw new NotSupportedException("This is a Read Only Collection and can not be modified"); + } + + public override void RemoveAt(int pos) + { + throw new NotSupportedException("This is a Read Only Collection and can not be modified"); + } + + public override bool IsFixedSize + { + get { return true; } + } + + public override bool IsReadOnly + { + get { return true; } + } + + public override IPluginCollectionEnumerator GetEnumerator() + { + return this.m_collection.GetEnumerator(); } // (just to mimic some nice features of ArrayList) - public override int Capacity - { - get { return this.m_collection.Capacity; } - set { throw new NotSupportedException("This is a Read Only Collection and can not be modified"); } - } - - public override int AddRange(PluginCollection x) - { - throw new NotSupportedException("This is a Read Only Collection and can not be modified"); - } - - public override int AddRange(IPlugin[] x) - { - throw new NotSupportedException("This is a Read Only Collection and can not be modified"); - } - } - } -} + public override int Capacity + { + get { return this.m_collection.Capacity; } + set { throw new NotSupportedException("This is a Read Only Collection and can not be modified"); } + } + + public override int AddRange(PluginCollection x) + { + throw new NotSupportedException("This is a Read Only Collection and can not be modified"); + } + + public override int AddRange(IPlugin[] x) + { + throw new NotSupportedException("This is a Read Only Collection and can not be modified"); + } + } + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Plugin/PluginMap.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Plugin/PluginMap.cs index 888ad8b1916..aaac7e964b6 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Plugin/PluginMap.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Plugin/PluginMap.cs @@ -1,176 +1,174 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.Plugin -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; - using System.Collections; +using System; +using System.Collections; - using log4net.Repository; - using log4net.Util; +using log4net.Util; +using log4net.Repository; - /// - /// Map of repository plugins. - /// - /// - /// - /// This class is a name keyed map of the plugins that are - /// attached to a repository. - /// - /// - /// Nicko Cadell. - /// Gert Driesen. - public sealed class PluginMap +namespace log4net.Plugin +{ + /// + /// Map of repository plugins. + /// + /// + /// + /// This class is a name keyed map of the plugins that are + /// attached to a repository. + /// + /// + /// Nicko Cadell + /// Gert Driesen + public sealed class PluginMap { /// - /// Initializes a new instance of the class. - /// Constructor. - /// - /// The repository that the plugins should be attached to. - /// - /// - /// Initialize a new instance of the class with a - /// repository that the plugins should be attached to. - /// - /// - public PluginMap(ILoggerRepository repository) - { - this.m_repository = repository; + /// Constructor + /// + /// The repository that the plugins should be attached to. + /// + /// + /// Initialize a new instance of the class with a + /// repository that the plugins should be attached to. + /// + /// + public PluginMap(ILoggerRepository repository) + { + this.m_repository = repository; } - /// - /// Gets a by name. - /// - /// The name of the to lookup. - /// - /// The from the map with the name specified, or - /// null if no plugin is found. - /// - /// - /// - /// Lookup a plugin by name. If the plugin is not found null - /// will be returned. - /// - /// - public IPlugin this[string name] - { - get - { - if (name == null) - { - throw new ArgumentNullException("name"); - } - - lock (this) - { - return (IPlugin)this.m_mapName2Plugin[name]; - } - } - } - - /// - /// Gets all possible plugins as a list of objects. - /// - /// All possible plugins as a list of objects. - /// - /// - /// Get a collection of all the plugins defined in this map. - /// - /// - public PluginCollection AllPlugins - { - get - { - lock (this) - { - return new PluginCollection(this.m_mapName2Plugin.Values); - } - } + /// + /// Gets a by name. + /// + /// The name of the to lookup. + /// + /// The from the map with the name specified, or + /// null if no plugin is found. + /// + /// + /// + /// Lookup a plugin by name. If the plugin is not found null + /// will be returned. + /// + /// + public IPlugin this[string name] + { + get + { + if (name == null) + { + throw new ArgumentNullException("name"); + } + + lock(this) + { + return (IPlugin)this.m_mapName2Plugin[name]; + } + } } - /// - /// Adds a to the map. - /// - /// The to add to the map. - /// - /// - /// The will be attached to the repository when added. - /// - /// - /// If there already exists a plugin with the same name - /// attached to the repository then the old plugin will - /// be and replaced with - /// the new plugin. - /// - /// - public void Add(IPlugin plugin) - { - if (plugin == null) - { - throw new ArgumentNullException("plugin"); - } - - IPlugin curPlugin = null; - - lock (this) - { - // Get the current plugin if it exists - curPlugin = this.m_mapName2Plugin[plugin.Name] as IPlugin; - - // Store new plugin - this.m_mapName2Plugin[plugin.Name] = plugin; - } - - // Shutdown existing plugin with same name - if (curPlugin != null) - { - curPlugin.Shutdown(); - } - - // Attach new plugin to repository - plugin.Attach(this.m_repository); - } - - /// - /// Removes a from the map. - /// - /// The to remove from the map. - /// - /// - /// Remove a specific plugin from this map. - /// - /// - public void Remove(IPlugin plugin) - { - if (plugin == null) - { - throw new ArgumentNullException("plugin"); - } + /// + /// Gets all possible plugins as a list of objects. + /// + /// All possible plugins as a list of objects. + /// + /// + /// Get a collection of all the plugins defined in this map. + /// + /// + public PluginCollection AllPlugins + { + get + { + lock(this) + { + return new PluginCollection(this.m_mapName2Plugin.Values); + } + } + } + + /// + /// Adds a to the map. + /// + /// The to add to the map. + /// + /// + /// The will be attached to the repository when added. + /// + /// + /// If there already exists a plugin with the same name + /// attached to the repository then the old plugin will + /// be and replaced with + /// the new plugin. + /// + /// + public void Add(IPlugin plugin) + { + if (plugin == null) + { + throw new ArgumentNullException("plugin"); + } + + IPlugin curPlugin = null; - lock (this) - { - this.m_mapName2Plugin.Remove(plugin.Name); - } + lock(this) + { + // Get the current plugin if it exists + curPlugin = this.m_mapName2Plugin[plugin.Name] as IPlugin; + + // Store new plugin + this.m_mapName2Plugin[plugin.Name] = plugin; + } + + // Shutdown existing plugin with same name + if (curPlugin != null) + { + curPlugin.Shutdown(); + } + + // Attach new plugin to repository + plugin.Attach(this.m_repository); + } + + /// + /// Removes a from the map. + /// + /// The to remove from the map. + /// + /// + /// Remove a specific plugin from this map. + /// + /// + public void Remove(IPlugin plugin) + { + if (plugin == null) + { + throw new ArgumentNullException("plugin"); + } + lock(this) + { + this.m_mapName2Plugin.Remove(plugin.Name); + } } - private readonly Hashtable m_mapName2Plugin = new Hashtable(); + private readonly Hashtable m_mapName2Plugin = new Hashtable(); private readonly ILoggerRepository m_repository; - } -} + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Plugin/PluginSkeleton.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Plugin/PluginSkeleton.cs index 3496caa4211..a32a5b3956a 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Plugin/PluginSkeleton.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Plugin/PluginSkeleton.cs @@ -1,134 +1,133 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.Plugin -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using log4net.Repository; +using log4net.Repository; - /// - /// Base implementation of . - /// - /// - /// - /// Default abstract implementation of the - /// interface. This base class can be used by implementors - /// of the interface. - /// - /// - /// Nicko Cadell. - /// Gert Driesen. - public abstract class PluginSkeleton : IPlugin +namespace log4net.Plugin +{ + /// + /// Base implementation of + /// + /// + /// + /// Default abstract implementation of the + /// interface. This base class can be used by implementors + /// of the interface. + /// + /// + /// Nicko Cadell + /// Gert Driesen + public abstract class PluginSkeleton : IPlugin { /// - /// Initializes a new instance of the class. - /// Constructor. - /// - /// the name of the plugin. - /// - /// Initializes a new Plugin with the specified name. - /// - protected PluginSkeleton(string name) - { - this.m_name = name; + /// Constructor + /// + /// the name of the plugin + /// + /// Initializes a new Plugin with the specified name. + /// + protected PluginSkeleton(string name) + { + this.m_name = name; } - /// - /// Gets or sets the name of the plugin. - /// - /// - /// The name of the plugin. - /// - /// - /// - /// Plugins are stored in the - /// keyed by name. Each plugin instance attached to a - /// repository must be a unique name. - /// - /// - /// The name of the plugin must not change one the - /// plugin has been attached to a repository. - /// - /// - public virtual string Name - { - get { return this.m_name; } - set { this.m_name = value; } - } - - /// - /// Attaches this plugin to a . - /// - /// The that this plugin should be attached to. - /// - /// - /// A plugin may only be attached to a single repository. - /// - /// - /// This method is called when the plugin is attached to the repository. - /// - /// - public virtual void Attach(ILoggerRepository repository) - { - this.m_repository = repository; - } - - /// - /// Is called when the plugin is to shutdown. - /// - /// - /// - /// This method is called to notify the plugin that - /// it should stop operating and should detach from - /// the repository. - /// - /// - public virtual void Shutdown() - { + /// + /// Gets or sets the name of the plugin. + /// + /// + /// The name of the plugin. + /// + /// + /// + /// Plugins are stored in the + /// keyed by name. Each plugin instance attached to a + /// repository must be a unique name. + /// + /// + /// The name of the plugin must not change one the + /// plugin has been attached to a repository. + /// + /// + public virtual string Name + { + get { return this.m_name; } + set { this.m_name = value; } + } + + /// + /// Attaches this plugin to a . + /// + /// The that this plugin should be attached to. + /// + /// + /// A plugin may only be attached to a single repository. + /// + /// + /// This method is called when the plugin is attached to the repository. + /// + /// + public virtual void Attach(ILoggerRepository repository) + { + this.m_repository = repository; } - /// - /// Gets or sets the repository for this plugin. - /// - /// - /// The that this plugin is attached to. - /// - /// - /// - /// Gets or sets the that this plugin is - /// attached to. - /// - /// - protected virtual ILoggerRepository LoggerRepository - { - get { return this.m_repository; } - set { this.m_repository = value; } + /// + /// Is called when the plugin is to shutdown. + /// + /// + /// + /// This method is called to notify the plugin that + /// it should stop operating and should detach from + /// the repository. + /// + /// + public virtual void Shutdown() + { } - /// - /// The name of this plugin. - /// - private string m_name; - - /// - /// The repository this plugin is attached to. - /// + /// + /// The repository for this plugin + /// + /// + /// The that this plugin is attached to. + /// + /// + /// + /// Gets or sets the that this plugin is + /// attached to. + /// + /// + protected virtual ILoggerRepository LoggerRepository + { + get { return this.m_repository; } + set { this.m_repository = value; } + } + + /// + /// The name of this plugin. + /// + private string m_name; + + /// + /// The repository this plugin is attached to. + /// private ILoggerRepository m_repository; - } -} + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Plugin/RemoteLoggingServerPlugin.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Plugin/RemoteLoggingServerPlugin.cs index ce75e250439..6734e2314b8 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Plugin/RemoteLoggingServerPlugin.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Plugin/RemoteLoggingServerPlugin.cs @@ -1,251 +1,244 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -// .NET Compact Framework 1.0 has no support for System.Runtime.Remoting -#if !NETCF - -using System; -using System.Runtime.Remoting; - -using log4net.Core; -using log4net.Repository; -using log4net.Util; - -using IRemoteLoggingSink = log4net.Appender.RemotingAppender.IRemoteLoggingSink; - -namespace log4net.Plugin -{ - /// - /// Plugin that listens for events from the . - /// - /// - /// - /// This plugin publishes an instance of - /// on a specified . This listens for logging events delivered from - /// a remote . - /// - /// - /// When an event is received it is relogged within the attached repository - /// as if it had been raised locally. - /// - /// - /// Nicko Cadell. - /// Gert Driesen. - public class RemoteLoggingServerPlugin : PluginSkeleton +// .NET Compact Framework 1.0 && netstandard has no support for System.Runtime.Remoting +#if NET_2_0 + +using System; +using System.Runtime.Remoting; + +using log4net.Util; +using log4net.Repository; +using log4net.Core; +using IRemoteLoggingSink = log4net.Appender.RemotingAppender.IRemoteLoggingSink; + +namespace log4net.Plugin +{ + /// + /// Plugin that listens for events from the + /// + /// + /// + /// This plugin publishes an instance of + /// on a specified . This listens for logging events delivered from + /// a remote . + /// + /// + /// When an event is received it is relogged within the attached repository + /// as if it had been raised locally. + /// + /// + /// Nicko Cadell + /// Gert Driesen + public class RemoteLoggingServerPlugin : PluginSkeleton { /// - /// Initializes a new instance of the class. - /// Default constructor. - /// - /// - /// - /// Initializes a new instance of the class. - /// - /// - /// The property must be set. - /// - /// - public RemoteLoggingServerPlugin() - : base("RemoteLoggingServerPlugin:Unset URI") - { + /// Default constructor + /// + /// + /// + /// Initializes a new instance of the class. + /// + /// + /// The property must be set. + /// + /// + public RemoteLoggingServerPlugin() : base("RemoteLoggingServerPlugin:Unset URI") + { } /// - /// Initializes a new instance of the class. - /// Construct with sink Uri. - /// - /// The name to publish the sink under in the remoting infrastructure. - /// See for more details. - /// - /// - /// Initializes a new instance of the class - /// with specified name. - /// - /// - public RemoteLoggingServerPlugin(string sinkUri) - : base("RemoteLoggingServerPlugin:" + sinkUri) - { - this.m_sinkUri = sinkUri; + /// Construct with sink Uri. + /// + /// The name to publish the sink under in the remoting infrastructure. + /// See for more details. + /// + /// + /// Initializes a new instance of the class + /// with specified name. + /// + /// + public RemoteLoggingServerPlugin(string sinkUri) : base("RemoteLoggingServerPlugin:"+sinkUri) + { + this.m_sinkUri = sinkUri; } - /// - /// Gets or sets the URI of this sink. - /// - /// - /// The URI of this sink. - /// - /// - /// - /// This is the name under which the object is marshaled. - /// . - /// - /// - public virtual string SinkUri - { - get { return this.m_sinkUri; } - set { this.m_sinkUri = value; } + /// + /// Gets or sets the URI of this sink. + /// + /// + /// The URI of this sink. + /// + /// + /// + /// This is the name under which the object is marshaled. + /// + /// + /// + public virtual string SinkUri + { + get { return this.m_sinkUri; } + set { this.m_sinkUri = value; } } - /// - /// Attaches this plugin to a . - /// - /// The that this plugin should be attached to. - /// - /// - /// A plugin may only be attached to a single repository. - /// - /// - /// This method is called when the plugin is attached to the repository. - /// - /// -#if NET_4_0 || MONO_4_0 - [System.Security.SecuritySafeCritical] -#endif - public override void Attach(ILoggerRepository repository) - { - base.Attach(repository); - - // Create the sink and marshal it - this.m_sink = new RemoteLoggingSinkImpl(repository); - - try - { - RemotingServices.Marshal(this.m_sink, this.m_sinkUri, typeof(IRemoteLoggingSink)); - } - catch (Exception ex) - { - LogLog.Error(declaringType, "Failed to Marshal remoting sink", ex); - } + /// + /// Attaches this plugin to a . + /// + /// The that this plugin should be attached to. + /// + /// + /// A plugin may only be attached to a single repository. + /// + /// + /// This method is called when the plugin is attached to the repository. + /// + /// +#if NET_4_0 || MONO_4_0 + [System.Security.SecuritySafeCritical] +#endif + public override void Attach(ILoggerRepository repository) + { + base.Attach(repository); + + // Create the sink and marshal it + this.m_sink = new RemoteLoggingSinkImpl(repository); + + try + { + RemotingServices.Marshal(this.m_sink, this.m_sinkUri, typeof(IRemoteLoggingSink)); + } + catch(Exception ex) + { + LogLog.Error(declaringType, "Failed to Marshal remoting sink", ex); + } } - /// - /// Is called when the plugin is to shutdown. - /// - /// - /// - /// When the plugin is shutdown the remote logging - /// sink is disconnected. - /// - /// -#if NET_4_0 || MONO_4_0 - [System.Security.SecuritySafeCritical] -#endif - public override void Shutdown() - { - // Stops the sink from receiving messages - RemotingServices.Disconnect(this.m_sink); - this.m_sink = null; - - base.Shutdown(); + /// + /// Is called when the plugin is to shutdown. + /// + /// + /// + /// When the plugin is shutdown the remote logging + /// sink is disconnected. + /// + /// +#if NET_4_0 || MONO_4_0 + [System.Security.SecuritySafeCritical] +#endif + public override void Shutdown() + { + // Stops the sink from receiving messages + RemotingServices.Disconnect(this.m_sink); + this.m_sink = null; + + base.Shutdown(); } - private RemoteLoggingSinkImpl m_sink; + private RemoteLoggingSinkImpl m_sink; private string m_sinkUri; - /// - /// The fully qualified type of the RemoteLoggingServerPlugin class. - /// - /// - /// Used by the internal logger to record the Type of the - /// log message. - /// + /// + /// The fully qualified type of the RemoteLoggingServerPlugin class. + /// + /// + /// Used by the internal logger to record the Type of the + /// log message. + /// private static readonly Type declaringType = typeof(RemoteLoggingServerPlugin); - /// - /// Delivers objects to a remote sink. - /// - /// - /// - /// Internal class used to listen for logging events - /// and deliver them to the local repository. - /// - /// - private class RemoteLoggingSinkImpl : MarshalByRefObject, IRemoteLoggingSink + /// + /// Delivers objects to a remote sink. + /// + /// + /// + /// Internal class used to listen for logging events + /// and deliver them to the local repository. + /// + /// + private class RemoteLoggingSinkImpl : MarshalByRefObject, IRemoteLoggingSink { /// - /// Initializes a new instance of the class. - /// Constructor. - /// - /// The repository to log to. - /// - /// - /// Initializes a new instance of the for the - /// specified . - /// - /// - public RemoteLoggingSinkImpl(ILoggerRepository repository) - { - this.m_repository = repository; + /// Constructor + /// + /// The repository to log to. + /// + /// + /// Initializes a new instance of the for the + /// specified . + /// + /// + public RemoteLoggingSinkImpl(ILoggerRepository repository) + { + this.m_repository = repository; } - /// - /// Logs the events to the repository. - /// - /// The events to log. - /// - /// - /// The events passed are logged to the . - /// - /// - public void LogEvents(LoggingEvent[] events) - { - if (events != null) - { - foreach (LoggingEvent logEvent in events) - { - if (logEvent != null) - { - this.m_repository.Log(logEvent); - } - } - } + /// + /// Logs the events to the repository. + /// + /// The events to log. + /// + /// + /// The events passed are logged to the + /// + /// + public void LogEvents(LoggingEvent[] events) + { + if (events != null) + { + foreach(LoggingEvent logEvent in events) + { + if (logEvent != null) + { + this.m_repository.Log(logEvent); + } + } + } } - /// - /// Obtains a lifetime service object to control the lifetime - /// policy for this instance. - /// - /// null to indicate that this instance should live forever. - /// - /// - /// Obtains a lifetime service object to control the lifetime - /// policy for this instance. This object should live forever - /// therefore this implementation returns null. - /// - /// -#if NET_4_0 || MONO_4_0 - [System.Security.SecurityCritical] -#endif - public override object InitializeLifetimeService() - { - return null; + /// + /// Obtains a lifetime service object to control the lifetime + /// policy for this instance. + /// + /// null to indicate that this instance should live forever. + /// + /// + /// Obtains a lifetime service object to control the lifetime + /// policy for this instance. This object should live forever + /// therefore this implementation returns null. + /// + /// +#if NET_4_0 || MONO_4_0 + [System.Security.SecurityCritical] +#endif + public override object InitializeLifetimeService() + { + return null; } - /// - /// The underlying that events should - /// be logged to. - /// + /// + /// The underlying that events should + /// be logged to. + /// private readonly ILoggerRepository m_repository; - } - } -} - -#endif // !NETCF + } + } +} + +#endif // NET_2_0 diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Repository/ConfigurationChangedEventArgs.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Repository/ConfigurationChangedEventArgs.cs index 06874302c6d..7be02765d5c 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Repository/ConfigurationChangedEventArgs.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Repository/ConfigurationChangedEventArgs.cs @@ -1,55 +1,50 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.Repository -{ - /* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * -*/ - - using System; - using System.Collections; +using System; +using System.Collections; - /// - /// - /// - public class ConfigurationChangedEventArgs : EventArgs - { +namespace log4net.Repository +{ + /// + /// + /// + public class ConfigurationChangedEventArgs : EventArgs + { private readonly ICollection configurationMessages; /// - /// Initializes a new instance of the class. - /// - /// - public ConfigurationChangedEventArgs(ICollection configurationMessages) - { - this.configurationMessages = configurationMessages; - } - - /// - /// - /// - public ICollection ConfigurationMessages - { - get { return this.configurationMessages; } - } - } -} + /// + /// + /// + public ConfigurationChangedEventArgs(ICollection configurationMessages) + { + this.configurationMessages = configurationMessages; + } + + /// + /// + /// + public ICollection ConfigurationMessages + { + get { return this.configurationMessages; } + } + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Repository/Hierarchy/DefaultLoggerFactory.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Repository/Hierarchy/DefaultLoggerFactory.cs index 6ad84edb010..8700ae8bf0e 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Repository/Hierarchy/DefaultLoggerFactory.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Repository/Hierarchy/DefaultLoggerFactory.cs @@ -1,111 +1,107 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.Repository.Hierarchy -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using log4net.Core; +using log4net.Core; - /// - /// Default implementation of . - /// - /// - /// - /// This default implementation of the - /// interface is used to create the default subclass - /// of the object. - /// - /// - /// Nicko Cadell. - /// Gert Driesen. - internal class DefaultLoggerFactory : ILoggerFactory +namespace log4net.Repository.Hierarchy +{ + /// + /// Default implementation of + /// + /// + /// + /// This default implementation of the + /// interface is used to create the default subclass + /// of the object. + /// + /// + /// Nicko Cadell + /// Gert Driesen + internal class DefaultLoggerFactory : ILoggerFactory { /// - /// Initializes a new instance of the class. - /// Default constructor. - /// - /// - /// - /// Initializes a new instance of the class. - /// - /// - internal DefaultLoggerFactory() - { + /// Default constructor + /// + /// + /// + /// Initializes a new instance of the class. + /// + /// + internal DefaultLoggerFactory() + { } - /// - /// Create a new instance. - /// - /// The that will own the . - /// The name of the . - /// The instance for the specified name. - /// - /// - /// Create a new instance with the - /// specified name. - /// - /// - /// Called by the to create - /// new named instances. - /// - /// - /// If the is null then the root logger - /// must be returned. - /// - /// - public Logger CreateLogger(ILoggerRepository repository, string name) - { - if (name == null) - { - return new RootLogger(repository.LevelMap.LookupWithDefault(Level.Debug)); - } - - return new LoggerImpl(name); + /// + /// Create a new instance + /// + /// The that will own the . + /// The name of the . + /// The instance for the specified name. + /// + /// + /// Create a new instance with the + /// specified name. + /// + /// + /// Called by the to create + /// new named instances. + /// + /// + /// If the is null then the root logger + /// must be returned. + /// + /// + public Logger CreateLogger(ILoggerRepository repository, string name) + { + if (name == null) + { + return new RootLogger(repository.LevelMap.LookupWithDefault(Level.Debug)); + } + return new LoggerImpl(name); } - /// - /// Default internal subclass of . - /// - /// - /// - /// This subclass has no additional behavior over the - /// class but does allow instances - /// to be created. - /// - /// - internal sealed class LoggerImpl : Logger + /// + /// Default internal subclass of + /// + /// + /// + /// This subclass has no additional behavior over the + /// class but does allow instances + /// to be created. + /// + /// + internal sealed class LoggerImpl : Logger { /// - /// Initializes a new instance of the class. - /// Construct a new Logger. - /// - /// the name of the logger. - /// - /// - /// Initializes a new instance of the class - /// with the specified name. - /// - /// - internal LoggerImpl(string name) - : base(name) - { - } - } - } -} + /// Construct a new Logger + /// + /// the name of the logger + /// + /// + /// Initializes a new instance of the class + /// with the specified name. + /// + /// + internal LoggerImpl(string name) : base(name) + { + } + } + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Repository/Hierarchy/Hierarchy.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Repository/Hierarchy/Hierarchy.cs index 017a81d7d9a..8591ab3e74d 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Repository/Hierarchy/Hierarchy.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Repository/Hierarchy/Hierarchy.cs @@ -1,925 +1,909 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.Repository.Hierarchy +using System; +using System.Collections; +using log4net.Appender; +using log4net.Core; +using log4net.Repository; +using log4net.Util; + +namespace log4net.Repository.Hierarchy { - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; - using System.Collections; - - using log4net.Appender; - using log4net.Core; - using log4net.Repository; - using log4net.Util; - - /// - /// Delegate used to handle logger creation event notifications. - /// - /// The in which the has been created. - /// The event args that hold the instance that has been created. - /// - /// - /// Delegate used to handle logger creation event notifications. - /// - /// - public delegate void LoggerCreationEventHandler(object sender, LoggerCreationEventArgs e); - - /// - /// Provides data for the event. - /// - /// - /// - /// A event is raised every time a - /// is created. - /// - /// - public class LoggerCreationEventArgs : EventArgs - { - /// - /// The created. - /// + /// + /// Delegate used to handle logger creation event notifications. + /// + /// The in which the has been created. + /// The event args that hold the instance that has been created. + /// + /// + /// Delegate used to handle logger creation event notifications. + /// + /// + public delegate void LoggerCreationEventHandler(object sender, LoggerCreationEventArgs e); + + /// + /// Provides data for the event. + /// + /// + /// + /// A event is raised every time a + /// is created. + /// + /// + public class LoggerCreationEventArgs : EventArgs + { + /// + /// The created + /// private Logger m_log; /// - /// Initializes a new instance of the class. - /// Constructor. - /// - /// The that has been created. - /// - /// - /// Initializes a new instance of the event argument - /// class,with the specified . - /// - /// - public LoggerCreationEventArgs(Logger log) - { - this.m_log = log; - } - - /// - /// Gets the that has been created. - /// - /// - /// The that has been created. - /// - /// - /// - /// The that has been created. - /// - /// - public Logger Logger - { - get { return this.m_log; } - } + /// Constructor + /// + /// The that has been created. + /// + /// + /// Initializes a new instance of the event argument + /// class,with the specified . + /// + /// + public LoggerCreationEventArgs(Logger log) + { + this.m_log = log; + } + + /// + /// Gets the that has been created. + /// + /// + /// The that has been created. + /// + /// + /// + /// The that has been created. + /// + /// + public Logger Logger + { + get { return this.m_log; } + } } - /// - /// Hierarchical organization of loggers. - /// - /// - /// - /// The casual user should not have to deal with this class - /// directly. - /// - /// - /// This class is specialized in retrieving loggers by name and - /// also maintaining the logger hierarchy. Implements the - /// interface. - /// - /// - /// The structure of the logger hierarchy is maintained by the - /// method. The hierarchy is such that children - /// link to their parent but parents do not have any references to their - /// children. Moreover, loggers can be instantiated in any order, in - /// particular descendant before ancestor. - /// - /// - /// In case a descendant is created before a particular ancestor, - /// then it creates a provision node for the ancestor and adds itself - /// to the provision node. Other descendants of the same ancestor add - /// themselves to the previously created provision node. - /// - /// - /// Nicko Cadell. - /// Gert Driesen. - public class Hierarchy : LoggerRepositorySkeleton, IBasicRepositoryConfigurator, IXmlRepositoryConfigurator + /// + /// Hierarchical organization of loggers + /// + /// + /// + /// The casual user should not have to deal with this class + /// directly. + /// + /// + /// This class is specialized in retrieving loggers by name and + /// also maintaining the logger hierarchy. Implements the + /// interface. + /// + /// + /// The structure of the logger hierarchy is maintained by the + /// method. The hierarchy is such that children + /// link to their parent but parents do not have any references to their + /// children. Moreover, loggers can be instantiated in any order, in + /// particular descendant before ancestor. + /// + /// + /// In case a descendant is created before a particular ancestor, + /// then it creates a provision node for the ancestor and adds itself + /// to the provision node. Other descendants of the same ancestor add + /// themselves to the previously created provision node. + /// + /// + /// Nicko Cadell + /// Gert Driesen + public class Hierarchy : LoggerRepositorySkeleton, IBasicRepositoryConfigurator, IXmlRepositoryConfigurator { - /// - /// Event used to notify that a logger has been created. - /// - /// - /// - /// Event raised when a logger is created. - /// - /// - public event LoggerCreationEventHandler LoggerCreatedEvent - { - add { this.m_loggerCreatedEvent += value; } - remove { this.m_loggerCreatedEvent -= value; } + /// + /// Event used to notify that a logger has been created. + /// + /// + /// + /// Event raised when a logger is created. + /// + /// + public event LoggerCreationEventHandler LoggerCreatedEvent + { + add { this.m_loggerCreatedEvent += value; } + remove { this.m_loggerCreatedEvent -= value; } } /// - /// Initializes a new instance of the class. - /// Default constructor. - /// - /// - /// - /// Initializes a new instance of the class. - /// - /// - public Hierarchy() - : this(new DefaultLoggerFactory()) - { + /// Default constructor + /// + /// + /// + /// Initializes a new instance of the class. + /// + /// + public Hierarchy() : this(new DefaultLoggerFactory()) + { } /// - /// Initializes a new instance of the class. - /// Construct with properties. - /// - /// The properties to pass to this repository. - /// - /// - /// Initializes a new instance of the class. - /// - /// - public Hierarchy(PropertiesDictionary properties) - : this(properties, new DefaultLoggerFactory()) - { + /// Construct with properties + /// + /// The properties to pass to this repository. + /// + /// + /// Initializes a new instance of the class. + /// + /// + public Hierarchy(PropertiesDictionary properties) : this(properties, new DefaultLoggerFactory()) + { } /// - /// Initializes a new instance of the class. - /// Construct with a logger factory. - /// - /// The factory to use to create new logger instances. - /// - /// - /// Initializes a new instance of the class with - /// the specified . - /// - /// - public Hierarchy(ILoggerFactory loggerFactory) - : this(new PropertiesDictionary(), loggerFactory) - { + /// Construct with a logger factory + /// + /// The factory to use to create new logger instances. + /// + /// + /// Initializes a new instance of the class with + /// the specified . + /// + /// + public Hierarchy(ILoggerFactory loggerFactory) : this(new PropertiesDictionary(), loggerFactory) + { } /// - /// Initializes a new instance of the class. - /// Construct with properties and a logger factory. - /// - /// The properties to pass to this repository. - /// The factory to use to create new logger instances. - /// - /// - /// Initializes a new instance of the class with - /// the specified . - /// - /// - public Hierarchy(PropertiesDictionary properties, ILoggerFactory loggerFactory) - : base(properties) - { - if (loggerFactory == null) - { - throw new ArgumentNullException("loggerFactory"); - } - - this.m_defaultFactory = loggerFactory; - - this.m_ht = System.Collections.Hashtable.Synchronized(new System.Collections.Hashtable()); + /// Construct with properties and a logger factory + /// + /// The properties to pass to this repository. + /// The factory to use to create new logger instances. + /// + /// + /// Initializes a new instance of the class with + /// the specified . + /// + /// + public Hierarchy(PropertiesDictionary properties, ILoggerFactory loggerFactory) : base(properties) + { + if (loggerFactory == null) + { + throw new ArgumentNullException("loggerFactory"); + } + + this.m_defaultFactory = loggerFactory; + + this.m_ht = Hashtable.Synchronized(new Hashtable()); } - /// - /// Gets or sets a value indicating whether has no appender warning been emitted. - /// - /// - /// - /// Flag to indicate if we have already issued a warning - /// about not having an appender warning. - /// - /// - public bool EmittedNoAppenderWarning - { - get { return this.m_emittedNoAppenderWarning; } - set { this.m_emittedNoAppenderWarning = value; } - } - - /// - /// Gets get the root of this hierarchy. - /// - /// - /// - /// Get the root of this hierarchy. - /// - /// - public Logger Root - { - get - { - if (this.m_root == null) - { - lock (this) - { - if (this.m_root == null) - { - // Create the root logger - Logger root = this.m_defaultFactory.CreateLogger(this, null); - root.Hierarchy = this; - - // Store root - this.m_root = root; - } - } - } - - return this.m_root; - } - } - - /// - /// Gets or sets the default instance. - /// - /// The default . - /// - /// - /// The logger factory is used to create logger instances. - /// - /// - public ILoggerFactory LoggerFactory - { - get { return this.m_defaultFactory; } - - set - { - if (value == null) - { - throw new ArgumentNullException("value"); - } - - this.m_defaultFactory = value; - } + /// + /// Has no appender warning been emitted + /// + /// + /// + /// Flag to indicate if we have already issued a warning + /// about not having an appender warning. + /// + /// + public bool EmittedNoAppenderWarning + { + get { return this.m_emittedNoAppenderWarning; } + set { this.m_emittedNoAppenderWarning = value; } } - /// - /// Test if a logger exists. - /// - /// The name of the logger to lookup. - /// The Logger object with the name specified. - /// - /// - /// Check if the named logger exists in the hierarchy. If so return - /// its reference, otherwise returns null. - /// - /// - public override ILogger Exists(string name) - { - if (name == null) - { - throw new ArgumentNullException("name"); - } - - lock (this.m_ht) - { - return this.m_ht[new LoggerKey(name)] as Logger; - } - } - - /// - /// Returns all the currently defined loggers in the hierarchy as an Array. - /// - /// All the defined loggers. - /// - /// - /// Returns all the currently defined loggers in the hierarchy as an Array. - /// The root logger is not included in the returned - /// enumeration. - /// - /// - public override ILogger[] GetCurrentLoggers() - { - // The accumulation in loggers is necessary because not all elements in - // ht are Logger objects as there might be some ProvisionNodes - // as well. - lock (this.m_ht) - { - System.Collections.ArrayList loggers = new System.Collections.ArrayList(this.m_ht.Count); - - // Iterate through m_ht values - foreach (object node in this.m_ht.Values) - { - if (node is Logger) - { - loggers.Add(node); - } - } - - return (Logger[])loggers.ToArray(typeof(Logger)); - } - } - - /// - /// Return a new logger instance named as the first parameter using - /// the default factory. - /// - /// - /// - /// Return a new logger instance named as the first parameter using - /// the default factory. - /// - /// - /// If a logger of that name already exists, then it will be - /// returned. Otherwise, a new logger will be instantiated and - /// then linked with its existing ancestors as well as children. - /// - /// - /// The name of the logger to retrieve. - /// The logger object with the name specified. - public override ILogger GetLogger(string name) - { - if (name == null) - { - throw new ArgumentNullException("name"); - } - - return this.GetLogger(name, this.m_defaultFactory); - } - - /// - /// Shutting down a hierarchy will safely close and remove - /// all appenders in all loggers including the root logger. - /// - /// - /// - /// Shutting down a hierarchy will safely close and remove - /// all appenders in all loggers including the root logger. - /// - /// - /// Some appenders need to be closed before the - /// application exists. Otherwise, pending logging events might be - /// lost. - /// - /// - /// The Shutdown method is careful to close nested - /// appenders before closing regular appenders. This is allows - /// configurations where a regular appender is attached to a logger - /// and again to a nested appender. - /// - /// - public override void Shutdown() - { - LogLog.Debug(declaringType, "Shutdown called on Hierarchy [" + this.Name + "]"); - - // begin by closing nested appenders - this.Root.CloseNestedAppenders(); - - lock (this.m_ht) - { - ILogger[] currentLoggers = this.GetCurrentLoggers(); - - foreach (Logger logger in currentLoggers) - { - logger.CloseNestedAppenders(); - } - - // then, remove all appenders - this.Root.RemoveAllAppenders(); - - foreach (Logger logger in currentLoggers) - { - logger.RemoveAllAppenders(); - } - } - - base.Shutdown(); - } - - /// - /// Reset all values contained in this hierarchy instance to their default. - /// - /// - /// - /// Reset all values contained in this hierarchy instance to their - /// default. This removes all appenders from all loggers, sets - /// the level of all non-root loggers to null, - /// sets their additivity flag to true and sets the level - /// of the root logger to . Moreover, - /// message disabling is set its default "off" value. - /// - /// - /// Existing loggers are not removed. They are just reset. - /// - /// - /// This method should be used sparingly and with care as it will - /// block all logging until it is completed. - /// - /// - public override void ResetConfiguration() - { - this.Root.Level = this.LevelMap.LookupWithDefault(Level.Debug); - this.Threshold = this.LevelMap.LookupWithDefault(Level.All); - - // the synchronization is needed to prevent hashtable surprises - lock (this.m_ht) - { - this.Shutdown(); // nested locks are OK - - foreach (Logger l in this.GetCurrentLoggers()) - { - l.Level = null; - l.Additivity = true; - } - } - - base.ResetConfiguration(); - - // Notify listeners - this.OnConfigurationChanged(null); - } - - /// - /// Log the logEvent through this hierarchy. - /// - /// the event to log. - /// - /// - /// This method should not normally be used to log. - /// The interface should be used - /// for routine logging. This interface can be obtained - /// using the method. - /// - /// - /// The logEvent is delivered to the appropriate logger and - /// that logger is then responsible for logging the event. - /// - /// - public override void Log(LoggingEvent logEvent) - { - if (logEvent == null) - { - throw new ArgumentNullException("logEvent"); - } - - this.GetLogger(logEvent.LoggerName, this.m_defaultFactory).Log(logEvent); - } - - /// - /// Returns all the Appenders that are currently configured. - /// - /// An array containing all the currently configured appenders. - /// - /// - /// Returns all the instances that are currently configured. - /// All the loggers are searched for appenders. The appenders may also be containers - /// for appenders and these are also searched for additional loggers. - /// - /// - /// The list returned is unordered but does not contain duplicates. - /// - /// - public override Appender.IAppender[] GetAppenders() - { - System.Collections.ArrayList appenderList = new System.Collections.ArrayList(); - - CollectAppenders(appenderList, this.Root); - - foreach (Logger logger in this.GetCurrentLoggers()) - { - CollectAppenders(appenderList, logger); - } - - return (Appender.IAppender[])appenderList.ToArray(typeof(Appender.IAppender)); + /// + /// Get the root of this hierarchy + /// + /// + /// + /// Get the root of this hierarchy. + /// + /// + public Logger Root + { + get + { + if (this.m_root == null) + { + lock(this) + { + if (this.m_root == null) + { + // Create the root logger + Logger root = this.m_defaultFactory.CreateLogger(this, null); + root.Hierarchy = this; + + // Store root + this.m_root = root; + } + } + } + return this.m_root; + } } - /// - /// Collect the appenders from an . - /// The appender may also be a container. - /// - /// - /// - private static void CollectAppender(System.Collections.ArrayList appenderList, Appender.IAppender appender) - { - if (!appenderList.Contains(appender)) - { - appenderList.Add(appender); - - IAppenderAttachable container = appender as IAppenderAttachable; - if (container != null) - { - CollectAppenders(appenderList, container); - } - } - } - - /// - /// Collect the appenders from an container. - /// - /// - /// - private static void CollectAppenders(System.Collections.ArrayList appenderList, IAppenderAttachable container) - { - foreach (Appender.IAppender appender in container.Appenders) - { - CollectAppender(appenderList, appender); - } + /// + /// Gets or sets the default instance. + /// + /// The default + /// + /// + /// The logger factory is used to create logger instances. + /// + /// + public ILoggerFactory LoggerFactory + { + get { return this.m_defaultFactory; } + set + { + if (value == null) + { + throw new ArgumentNullException("value"); + } + + this.m_defaultFactory = value; + } } - /// - /// Initialize the log4net system using the specified appender. - /// - /// the appender to use to log all logging events. - void IBasicRepositoryConfigurator.Configure(IAppender appender) - { - this.BasicRepositoryConfigure(appender); - } - - /// - /// Initialize the log4net system using the specified appenders. - /// - /// the appenders to use to log all logging events. - void IBasicRepositoryConfigurator.Configure(params IAppender[] appenders) - { - this.BasicRepositoryConfigure(appenders); - } - - /// - /// Initialize the log4net system using the specified appenders. - /// - /// the appenders to use to log all logging events. - /// - /// - /// This method provides the same functionality as the - /// method implemented - /// on this object, but it is protected and therefore can be called by subclasses. - /// - /// - protected void BasicRepositoryConfigure(params IAppender[] appenders) - { - ArrayList configurationMessages = new ArrayList(); - - using (new LogLog.LogReceivedAdapter(configurationMessages)) - { - foreach (IAppender appender in appenders) - { - this.Root.AddAppender(appender); - } - } - - this.Configured = true; - - this.ConfigurationMessages = configurationMessages; - - // Notify listeners - this.OnConfigurationChanged(new ConfigurationChangedEventArgs(configurationMessages)); + /// + /// Test if a logger exists + /// + /// The name of the logger to lookup + /// The Logger object with the name specified + /// + /// + /// Check if the named logger exists in the hierarchy. If so return + /// its reference, otherwise returns null. + /// + /// + public override ILogger Exists(string name) + { + if (name == null) + { + throw new ArgumentNullException("name"); + } + + lock(this.m_ht) + { + return this.m_ht[new LoggerKey(name)] as Logger; + } } - /// - /// Initialize the log4net system using the specified config. - /// - /// the element containing the root of the config. - void IXmlRepositoryConfigurator.Configure(System.Xml.XmlElement element) - { - this.XmlRepositoryConfigure(element); - } - - /// - /// Initialize the log4net system using the specified config. - /// - /// the element containing the root of the config. - /// - /// - /// This method provides the same functionality as the - /// method implemented - /// on this object, but it is protected and therefore can be called by subclasses. - /// - /// - protected void XmlRepositoryConfigure(System.Xml.XmlElement element) - { - ArrayList configurationMessages = new ArrayList(); - - using (new LogLog.LogReceivedAdapter(configurationMessages)) - { - XmlHierarchyConfigurator config = new XmlHierarchyConfigurator(this); - config.Configure(element); - } - - this.Configured = true; - - this.ConfigurationMessages = configurationMessages; - - // Notify listeners - this.OnConfigurationChanged(new ConfigurationChangedEventArgs(configurationMessages)); + /// + /// Returns all the currently defined loggers in the hierarchy as an Array + /// + /// All the defined loggers + /// + /// + /// Returns all the currently defined loggers in the hierarchy as an Array. + /// The root logger is not included in the returned + /// enumeration. + /// + /// + public override ILogger[] GetCurrentLoggers() + { + // The accumulation in loggers is necessary because not all elements in + // ht are Logger objects as there might be some ProvisionNodes + // as well. + lock(this.m_ht) + { + ArrayList loggers = new ArrayList(this.m_ht.Count); + + // Iterate through m_ht values + foreach(object node in this.m_ht.Values) + { + if (node is Logger) + { + loggers.Add(node); + } + } + return (Logger[])loggers.ToArray(typeof(Logger)); + } } - /// - /// Test if this hierarchy is disabled for the specified . - /// - /// The level to check against. - /// - /// true if the repository is disabled for the level argument, false otherwise. - /// - /// - /// - /// If this hierarchy has not been configured then this method will - /// always return true. - /// - /// - /// This method will return true if this repository is - /// disabled for level object passed as parameter and - /// false otherwise. - /// - /// - /// See also the property. - /// - /// - public bool IsDisabled(Level level) - { - // Cast level to object for performance - if ((object)level == null) - { - throw new ArgumentNullException("level"); - } - - if (this.Configured) - { - return this.Threshold > level; - } - else - { - // If not configured the hierarchy is effectively disabled - return true; - } - } - - /// - /// Clear all logger definitions from the internal hashtable. - /// - /// - /// - /// This call will clear all logger definitions from the internal - /// hashtable. Invoking this method will irrevocably mess up the - /// logger hierarchy. - /// - /// - /// You should really know what you are doing before - /// invoking this method. - /// - /// - public void Clear() - { - lock (this.m_ht) - { - this.m_ht.Clear(); - } - } - - /// - /// Return a new logger instance named as the first parameter using - /// . - /// - /// The name of the logger to retrieve. - /// The factory that will make the new logger instance. - /// The logger object with the name specified. - /// - /// - /// If a logger of that name already exists, then it will be - /// returned. Otherwise, a new logger will be instantiated by the - /// parameter and linked with its existing - /// ancestors as well as children. - /// - /// - public Logger GetLogger(string name, ILoggerFactory factory) - { - if (name == null) - { - throw new ArgumentNullException("name"); - } - - if (factory == null) - { - throw new ArgumentNullException("factory"); - } - - LoggerKey key = new LoggerKey(name); - - // Synchronize to prevent write conflicts. Read conflicts (in - // GetEffectiveLevel() method) are possible only if variable - // assignments are non-atomic. - lock (this.m_ht) - { - Logger logger = null; - - object node = this.m_ht[key]; - if (node == null) - { - logger = factory.CreateLogger(this, name); - logger.Hierarchy = this; - this.m_ht[key] = logger; - this.UpdateParents(logger); - this.OnLoggerCreationEvent(logger); - return logger; - } - - Logger nodeLogger = node as Logger; - if (nodeLogger != null) - { - return nodeLogger; - } - - ProvisionNode nodeProvisionNode = node as ProvisionNode; - if (nodeProvisionNode != null) - { - logger = factory.CreateLogger(this, name); - logger.Hierarchy = this; - this.m_ht[key] = logger; - UpdateChildren(nodeProvisionNode, logger); - this.UpdateParents(logger); - this.OnLoggerCreationEvent(logger); - return logger; - } - - // It should be impossible to arrive here but let's keep the compiler happy. - return null; - } + /// + /// Return a new logger instance named as the first parameter using + /// the default factory. + /// + /// + /// + /// Return a new logger instance named as the first parameter using + /// the default factory. + /// + /// + /// If a logger of that name already exists, then it will be + /// returned. Otherwise, a new logger will be instantiated and + /// then linked with its existing ancestors as well as children. + /// + /// + /// The name of the logger to retrieve + /// The logger object with the name specified + public override ILogger GetLogger(string name) + { + if (name == null) + { + throw new ArgumentNullException("name"); + } + + return this.GetLogger(name, this.m_defaultFactory); } - /// - /// Sends a logger creation event to all registered listeners. - /// - /// The newly created logger. - /// - /// Raises the logger creation event. - /// - protected virtual void OnLoggerCreationEvent(Logger logger) - { - LoggerCreationEventHandler handler = this.m_loggerCreatedEvent; - if (handler != null) - { - handler(this, new LoggerCreationEventArgs(logger)); - } + /// + /// Shutting down a hierarchy will safely close and remove + /// all appenders in all loggers including the root logger. + /// + /// + /// + /// Shutting down a hierarchy will safely close and remove + /// all appenders in all loggers including the root logger. + /// + /// + /// Some appenders need to be closed before the + /// application exists. Otherwise, pending logging events might be + /// lost. + /// + /// + /// The Shutdown method is careful to close nested + /// appenders before closing regular appenders. This is allows + /// configurations where a regular appender is attached to a logger + /// and again to a nested appender. + /// + /// + public override void Shutdown() + { + LogLog.Debug(declaringType, "Shutdown called on Hierarchy ["+this.Name+"]"); + + // begin by closing nested appenders + this.Root.CloseNestedAppenders(); + + lock(this.m_ht) + { + ILogger[] currentLoggers = this.GetCurrentLoggers(); + + foreach(Logger logger in currentLoggers) + { + logger.CloseNestedAppenders(); + } + + // then, remove all appenders + this.Root.RemoveAllAppenders(); + + foreach(Logger logger in currentLoggers) + { + logger.RemoveAllAppenders(); + } + } + + base.Shutdown(); } - /// - /// Updates all the parents of the specified logger. - /// - /// The logger to update the parents for. - /// - /// - /// This method loops through all the potential parents of - /// . There 3 possible cases: - /// - /// - /// - /// No entry for the potential parent of exists - /// - /// We create a ProvisionNode for this potential - /// parent and insert in that provision node. - /// - /// - /// - /// The entry is of type Logger for the potential parent. - /// - /// The entry is 's nearest existing parent. We - /// update 's parent field with this entry. We also break from - /// he loop because updating our parent's parent is our parent's - /// responsibility. - /// - /// - /// - /// The entry is of type ProvisionNode for this potential parent. - /// - /// We add to the list of children for this - /// potential parent. - /// - /// - /// - /// - private void UpdateParents(Logger log) - { - string name = log.Name; - int length = name.Length; - bool parentFound = false; - - // if name = "w.x.y.z", loop through "w.x.y", "w.x" and "w", but not "w.x.y.z" - for (int i = name.LastIndexOf('.', length - 1); i >= 0; i = name.LastIndexOf('.', i - 1)) - { - string substr = name.Substring(0, i); - - LoggerKey key = new LoggerKey(substr); // simple constructor - object node = this.m_ht[key]; - - // Create a provision node for a future parent. - if (node == null) - { - ProvisionNode pn = new ProvisionNode(log); - this.m_ht[key] = pn; - } - else - { - Logger nodeLogger = node as Logger; - if (nodeLogger != null) - { - parentFound = true; - log.Parent = nodeLogger; - break; // no need to update the ancestors of the closest ancestor - } - else - { - ProvisionNode nodeProvisionNode = node as ProvisionNode; - if (nodeProvisionNode != null) - { - nodeProvisionNode.Add(log); - } - else - { - LogLog.Error(declaringType, "Unexpected object type [" + node.GetType() + "] in ht.", new LogException()); - } - } - } - - if (i == 0) - { - // logger name starts with a dot - // and we've hit the start - break; - } - } - - // If we could not find any existing parents, then link with root. - if (!parentFound) - { - log.Parent = this.Root; - } - } - - /// - /// Replace a with a in the hierarchy. - /// - /// - /// - /// - /// - /// We update the links for all the children that placed themselves - /// in the provision node 'pn'. The second argument 'log' is a - /// reference for the newly created Logger, parent of all the - /// children in 'pn'. - /// - /// - /// We loop on all the children 'c' in 'pn'. - /// - /// - /// If the child 'c' has been already linked to a child of - /// 'log' then there is no need to update 'c'. - /// - /// - /// Otherwise, we set log's parent field to c's parent and set - /// c's parent field to log. - /// - /// - private static void UpdateChildren(ProvisionNode pn, Logger log) - { - for (int i = 0; i < pn.Count; i++) - { - Logger childLogger = (Logger)pn[i]; - - // Unless this child already points to a correct (lower) parent, - // make log.Parent point to childLogger.Parent and childLogger.Parent to log. - if (!childLogger.Parent.Name.StartsWith(log.Name)) - { - log.Parent = childLogger.Parent; - childLogger.Parent = log; - } - } - } - - /// - /// Define or redefine a Level using the values in the argument. - /// - /// the level values. - /// - /// - /// Define or redefine a Level using the values in the argument. - /// - /// - /// Supports setting levels via the configuration file. - /// - /// - internal void AddLevel(LevelEntry levelEntry) - { + /// + /// Reset all values contained in this hierarchy instance to their default. + /// + /// + /// + /// Reset all values contained in this hierarchy instance to their + /// default. This removes all appenders from all loggers, sets + /// the level of all non-root loggers to null, + /// sets their additivity flag to true and sets the level + /// of the root logger to . Moreover, + /// message disabling is set its default "off" value. + /// + /// + /// Existing loggers are not removed. They are just reset. + /// + /// + /// This method should be used sparingly and with care as it will + /// block all logging until it is completed. + /// + /// + public override void ResetConfiguration() + { + this.Root.Level = this.LevelMap.LookupWithDefault(Level.Debug); + this.Threshold = this.LevelMap.LookupWithDefault(Level.All); + + // the synchronization is needed to prevent hashtable surprises + lock(this.m_ht) + { + this.Shutdown(); // nested locks are OK + + foreach(Logger l in this.GetCurrentLoggers()) + { + l.Level = null; + l.Additivity = true; + } + } + + base.ResetConfiguration(); + + // Notify listeners + this.OnConfigurationChanged(null); + } + + /// + /// Log the logEvent through this hierarchy. + /// + /// the event to log + /// + /// + /// This method should not normally be used to log. + /// The interface should be used + /// for routine logging. This interface can be obtained + /// using the method. + /// + /// + /// The logEvent is delivered to the appropriate logger and + /// that logger is then responsible for logging the event. + /// + /// + public override void Log(LoggingEvent logEvent) + { + if (logEvent == null) + { + throw new ArgumentNullException("logEvent"); + } + + this.GetLogger(logEvent.LoggerName, this.m_defaultFactory).Log(logEvent); + } + + /// + /// Returns all the Appenders that are currently configured + /// + /// An array containing all the currently configured appenders + /// + /// + /// Returns all the instances that are currently configured. + /// All the loggers are searched for appenders. The appenders may also be containers + /// for appenders and these are also searched for additional loggers. + /// + /// + /// The list returned is unordered but does not contain duplicates. + /// + /// + public override IAppender[] GetAppenders() + { + ArrayList appenderList = new ArrayList(); + + CollectAppenders(appenderList, this.Root); + + foreach(Logger logger in this.GetCurrentLoggers()) + { + CollectAppenders(appenderList, logger); + } + + return (IAppender[])appenderList.ToArray(typeof(IAppender)); + } + + /// + /// Collect the appenders from an . + /// The appender may also be a container. + /// + /// + /// + private static void CollectAppender(ArrayList appenderList, IAppender appender) + { + if (!appenderList.Contains(appender)) + { + appenderList.Add(appender); + + IAppenderAttachable container = appender as IAppenderAttachable; + if (container != null) + { + CollectAppenders(appenderList, container); + } + } + } + + /// + /// Collect the appenders from an container + /// + /// + /// + private static void CollectAppenders(ArrayList appenderList, IAppenderAttachable container) + { + foreach(IAppender appender in container.Appenders) + { + CollectAppender(appenderList, appender); + } + } + + /// + /// Initialize the log4net system using the specified appender + /// + /// the appender to use to log all logging events + void IBasicRepositoryConfigurator.Configure(IAppender appender) + { + this.BasicRepositoryConfigure(appender); + } + + /// + /// Initialize the log4net system using the specified appenders + /// + /// the appenders to use to log all logging events + void IBasicRepositoryConfigurator.Configure(params IAppender[] appenders) + { + this.BasicRepositoryConfigure(appenders); + } + + /// + /// Initialize the log4net system using the specified appenders + /// + /// the appenders to use to log all logging events + /// + /// + /// This method provides the same functionality as the + /// method implemented + /// on this object, but it is protected and therefore can be called by subclasses. + /// + /// + protected void BasicRepositoryConfigure(params IAppender[] appenders) + { + ArrayList configurationMessages = new ArrayList(); + + using (new LogLog.LogReceivedAdapter(configurationMessages)) + { + foreach (IAppender appender in appenders) + { + this.Root.AddAppender(appender); + } + } + + this.Configured = true; + + this.ConfigurationMessages = configurationMessages; + + // Notify listeners + this.OnConfigurationChanged(new ConfigurationChangedEventArgs(configurationMessages)); + } + + /// + /// Initialize the log4net system using the specified config + /// + /// the element containing the root of the config + void IXmlRepositoryConfigurator.Configure(System.Xml.XmlElement element) + { + this.XmlRepositoryConfigure(element); + } + + /// + /// Initialize the log4net system using the specified config + /// + /// the element containing the root of the config + /// + /// + /// This method provides the same functionality as the + /// method implemented + /// on this object, but it is protected and therefore can be called by subclasses. + /// + /// + protected void XmlRepositoryConfigure(System.Xml.XmlElement element) + { + ArrayList configurationMessages = new ArrayList(); + + using (new LogLog.LogReceivedAdapter(configurationMessages)) + { + XmlHierarchyConfigurator config = new XmlHierarchyConfigurator(this); + config.Configure(element); + } + + this.Configured = true; + + this.ConfigurationMessages = configurationMessages; + + // Notify listeners + this.OnConfigurationChanged(new ConfigurationChangedEventArgs(configurationMessages)); + } + + /// + /// Test if this hierarchy is disabled for the specified . + /// + /// The level to check against. + /// + /// true if the repository is disabled for the level argument, false otherwise. + /// + /// + /// + /// If this hierarchy has not been configured then this method will + /// always return true. + /// + /// + /// This method will return true if this repository is + /// disabled for level object passed as parameter and + /// false otherwise. + /// + /// + /// See also the property. + /// + /// + public bool IsDisabled(Level level) + { + // Cast level to object for performance + if ((object)level == null) + { + throw new ArgumentNullException("level"); + } + + if (this.Configured) + { + return this.Threshold > level; + } + else + { + // If not configured the hierarchy is effectively disabled + return true; + } + } + + /// + /// Clear all logger definitions from the internal hashtable + /// + /// + /// + /// This call will clear all logger definitions from the internal + /// hashtable. Invoking this method will irrevocably mess up the + /// logger hierarchy. + /// + /// + /// You should really know what you are doing before + /// invoking this method. + /// + /// + public void Clear() + { + lock(this.m_ht) + { + this.m_ht.Clear(); + } + } + + /// + /// Return a new logger instance named as the first parameter using + /// . + /// + /// The name of the logger to retrieve + /// The factory that will make the new logger instance + /// The logger object with the name specified + /// + /// + /// If a logger of that name already exists, then it will be + /// returned. Otherwise, a new logger will be instantiated by the + /// parameter and linked with its existing + /// ancestors as well as children. + /// + /// + public Logger GetLogger(string name, ILoggerFactory factory) + { + if (name == null) + { + throw new ArgumentNullException("name"); + } + if (factory == null) + { + throw new ArgumentNullException("factory"); + } + + LoggerKey key = new LoggerKey(name); + + // Synchronize to prevent write conflicts. Read conflicts (in + // GetEffectiveLevel() method) are possible only if variable + // assignments are non-atomic. + + lock(this.m_ht) + { + Logger logger = null; + + Object node = this.m_ht[key]; + if (node == null) + { + logger = factory.CreateLogger(this, name); + logger.Hierarchy = this; + this.m_ht[key] = logger; + this.UpdateParents(logger); + this.OnLoggerCreationEvent(logger); + return logger; + } + + Logger nodeLogger = node as Logger; + if (nodeLogger != null) + { + return nodeLogger; + } + + ProvisionNode nodeProvisionNode = node as ProvisionNode; + if (nodeProvisionNode != null) + { + logger = factory.CreateLogger(this, name); + logger.Hierarchy = this; + this.m_ht[key] = logger; + UpdateChildren(nodeProvisionNode, logger); + this.UpdateParents(logger); + this.OnLoggerCreationEvent(logger); + return logger; + } + + // It should be impossible to arrive here but let's keep the compiler happy. + return null; + } + } + + /// + /// Sends a logger creation event to all registered listeners + /// + /// The newly created logger + /// + /// Raises the logger creation event. + /// + protected virtual void OnLoggerCreationEvent(Logger logger) + { + LoggerCreationEventHandler handler = this.m_loggerCreatedEvent; + if (handler != null) + { + handler(this, new LoggerCreationEventArgs(logger)); + } + } + + /// + /// Updates all the parents of the specified logger + /// + /// The logger to update the parents for + /// + /// + /// This method loops through all the potential parents of + /// . There 3 possible cases: + /// + /// + /// + /// No entry for the potential parent of exists + /// + /// We create a ProvisionNode for this potential + /// parent and insert in that provision node. + /// + /// + /// + /// The entry is of type Logger for the potential parent. + /// + /// The entry is 's nearest existing parent. We + /// update 's parent field with this entry. We also break from + /// he loop because updating our parent's parent is our parent's + /// responsibility. + /// + /// + /// + /// The entry is of type ProvisionNode for this potential parent. + /// + /// We add to the list of children for this + /// potential parent. + /// + /// + /// + /// + private void UpdateParents(Logger log) + { + string name = log.Name; + int length = name.Length; + bool parentFound = false; + + // if name = "w.x.y.z", loop through "w.x.y", "w.x" and "w", but not "w.x.y.z" + for(int i = name.LastIndexOf('.', length-1); i >= 0; i = name.LastIndexOf('.', i-1)) + { + string substr = name.Substring(0, i); + + LoggerKey key = new LoggerKey(substr); // simple constructor + Object node = this.m_ht[key]; + // Create a provision node for a future parent. + if (node == null) + { + ProvisionNode pn = new ProvisionNode(log); + this.m_ht[key] = pn; + } + else + { + Logger nodeLogger = node as Logger; + if (nodeLogger != null) + { + parentFound = true; + log.Parent = nodeLogger; + break; // no need to update the ancestors of the closest ancestor + } + else + { + ProvisionNode nodeProvisionNode = node as ProvisionNode; + if (nodeProvisionNode != null) + { + nodeProvisionNode.Add(log); + } + else + { + LogLog.Error(declaringType, "Unexpected object type ["+node.GetType()+"] in ht.", new LogException()); + } + } + } + if (i == 0) { + // logger name starts with a dot + // and we've hit the start + break; + } + } + + // If we could not find any existing parents, then link with root. + if (!parentFound) + { + log.Parent = this.Root; + } + } + + /// + /// Replace a with a in the hierarchy. + /// + /// + /// + /// + /// + /// We update the links for all the children that placed themselves + /// in the provision node 'pn'. The second argument 'log' is a + /// reference for the newly created Logger, parent of all the + /// children in 'pn'. + /// + /// + /// We loop on all the children 'c' in 'pn'. + /// + /// + /// If the child 'c' has been already linked to a child of + /// 'log' then there is no need to update 'c'. + /// + /// + /// Otherwise, we set log's parent field to c's parent and set + /// c's parent field to log. + /// + /// + private static void UpdateChildren(ProvisionNode pn, Logger log) + { + for(int i = 0; i < pn.Count; i++) + { + Logger childLogger = (Logger)pn[i]; + + // Unless this child already points to a correct (lower) parent, + // make log.Parent point to childLogger.Parent and childLogger.Parent to log. + if (!childLogger.Parent.Name.StartsWith(log.Name)) + { + log.Parent = childLogger.Parent; + childLogger.Parent = log; + } + } + } + + /// + /// Define or redefine a Level using the values in the argument + /// + /// the level values + /// + /// + /// Define or redefine a Level using the values in the argument + /// + /// + /// Supports setting levels via the configuration file. + /// + /// + internal void AddLevel(LevelEntry levelEntry) + { if (levelEntry == null) { throw new ArgumentNullException("levelEntry"); @@ -931,107 +915,107 @@ internal void AddLevel(LevelEntry levelEntry) } // Lookup replacement value - if (levelEntry.Value == -1) - { - Level previousLevel = this.LevelMap[levelEntry.Name]; - if (previousLevel == null) - { - throw new InvalidOperationException("Cannot redefine level [" + levelEntry.Name + "] because it is not defined in the LevelMap. To define the level supply the level value."); - } - - levelEntry.Value = previousLevel.Value; - } - - this.LevelMap.Add(levelEntry.Name, levelEntry.Value, levelEntry.DisplayName); - } - - /// - /// A class to hold the value, name and display name for a level. - /// - /// - /// - /// A class to hold the value, name and display name for a level. - /// - /// - internal class LevelEntry - { - private int m_levelValue = -1; - private string m_levelName = null; - private string m_levelDisplayName = null; - - /// - /// Gets or sets value of the level. - /// - /// - /// - /// If the value is not set (defaults to -1) the value will be looked - /// up for the current level with the same name. - /// - /// - public int Value - { - get { return this.m_levelValue; } - set { this.m_levelValue = value; } - } - - /// - /// Gets or sets name of the level. - /// - /// - /// The name of the level. - /// - /// - /// - /// The name of the level. - /// - /// - public string Name - { - get { return this.m_levelName; } - set { this.m_levelName = value; } - } - - /// - /// Gets or sets display name for the level. - /// - /// - /// The display name of the level. - /// - /// - /// - /// The display name of the level. - /// - /// - public string DisplayName - { - get { return this.m_levelDisplayName; } - set { this.m_levelDisplayName = value; } - } - - /// - /// Override Object.ToString to return sensible debug info. - /// - /// string info about this object. - public override string ToString() - { - return "LevelEntry(Value=" + this.m_levelValue + ", Name=" + this.m_levelName + ", DisplayName=" + this.m_levelDisplayName + ")"; - } - } - - /// - /// Set a Property using the values in the argument. - /// - /// the property value. - /// - /// - /// Set a Property using the values in the argument. - /// - /// - /// Supports setting property values via the configuration file. - /// - /// - internal void AddProperty(PropertyEntry propertyEntry) - { + if (levelEntry.Value == -1) + { + Level previousLevel = this.LevelMap[levelEntry.Name]; + if (previousLevel == null) + { + throw new InvalidOperationException("Cannot redefine level ["+levelEntry.Name+"] because it is not defined in the LevelMap. To define the level supply the level value."); + } + + levelEntry.Value = previousLevel.Value; + } + + this.LevelMap.Add(levelEntry.Name, levelEntry.Value, levelEntry.DisplayName); + } + + /// + /// A class to hold the value, name and display name for a level + /// + /// + /// + /// A class to hold the value, name and display name for a level + /// + /// + internal class LevelEntry + { + private int m_levelValue = -1; + private string m_levelName = null; + private string m_levelDisplayName = null; + + /// + /// Value of the level + /// + /// + /// + /// If the value is not set (defaults to -1) the value will be looked + /// up for the current level with the same name. + /// + /// + public int Value + { + get { return this.m_levelValue; } + set { this.m_levelValue = value; } + } + + /// + /// Name of the level + /// + /// + /// The name of the level + /// + /// + /// + /// The name of the level. + /// + /// + public string Name + { + get { return this.m_levelName; } + set { this.m_levelName = value; } + } + + /// + /// Display name for the level + /// + /// + /// The display name of the level + /// + /// + /// + /// The display name of the level. + /// + /// + public string DisplayName + { + get { return this.m_levelDisplayName; } + set { this.m_levelDisplayName = value; } + } + + /// + /// Override Object.ToString to return sensible debug info + /// + /// string info about this object + public override string ToString() + { + return "LevelEntry(Value="+ this.m_levelValue+", Name="+ this.m_levelName+", DisplayName="+ this.m_levelDisplayName+")"; + } + } + + /// + /// Set a Property using the values in the argument + /// + /// the property value + /// + /// + /// Set a Property using the values in the argument. + /// + /// + /// Supports setting property values via the configuration file. + /// + /// + internal void AddProperty(PropertyEntry propertyEntry) + { if (propertyEntry == null) { throw new ArgumentNullException("propertyEntry"); @@ -1042,25 +1026,25 @@ internal void AddProperty(PropertyEntry propertyEntry) throw new ArgumentNullException("propertyEntry.Key"); } - this.Properties[propertyEntry.Key] = propertyEntry.Value; + this.Properties[propertyEntry.Key] = propertyEntry.Value; } - private ILoggerFactory m_defaultFactory; - - private System.Collections.Hashtable m_ht; - private Logger m_root; - - private bool m_emittedNoAppenderWarning = false; - + private ILoggerFactory m_defaultFactory; + + private Hashtable m_ht; + private Logger m_root; + + private bool m_emittedNoAppenderWarning = false; + private event LoggerCreationEventHandler m_loggerCreatedEvent; - /// - /// The fully qualified type of the Hierarchy class. - /// - /// - /// Used by the internal logger to record the Type of the - /// log message. - /// + /// + /// The fully qualified type of the Hierarchy class. + /// + /// + /// Used by the internal logger to record the Type of the + /// log message. + /// private static readonly Type declaringType = typeof(Hierarchy); - } -} + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Repository/Hierarchy/ILoggerFactory.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Repository/Hierarchy/ILoggerFactory.cs index d23d2238d68..88a739f49fd 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Repository/Hierarchy/ILoggerFactory.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Repository/Hierarchy/ILoggerFactory.cs @@ -1,65 +1,65 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information - -// +// // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at -// +// // http://www.apache.org/licenses/LICENSE-2.0 -// +// // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. -// -namespace log4net.Repository.Hierarchy -{ - /// - /// Interface abstracts creation of instances. - /// - /// - /// - /// This interface is used by the to - /// create new objects. - /// - /// - /// The method is called - /// to create a named . - /// - /// - /// Implement this interface to create new subclasses of . - /// - /// - /// Nicko Cadell. - /// Gert Driesen. - public interface ILoggerFactory - { - /// - /// Create a new instance. - /// - /// The that will own the . - /// The name of the . - /// The instance for the specified name. - /// - /// - /// Create a new instance with the - /// specified name. - /// - /// - /// Called by the to create - /// new named instances. - /// - /// - /// If the is null then the root logger - /// must be returned. - /// - /// - Logger CreateLogger(ILoggerRepository repository, string name); - } -} +// + +namespace log4net.Repository.Hierarchy +{ + /// + /// Interface abstracts creation of instances + /// + /// + /// + /// This interface is used by the to + /// create new objects. + /// + /// + /// The method is called + /// to create a named . + /// + /// + /// Implement this interface to create new subclasses of . + /// + /// + /// Nicko Cadell + /// Gert Driesen + public interface ILoggerFactory + { + /// + /// Create a new instance + /// + /// The that will own the . + /// The name of the . + /// The instance for the specified name. + /// + /// + /// Create a new instance with the + /// specified name. + /// + /// + /// Called by the to create + /// new named instances. + /// + /// + /// If the is null then the root logger + /// must be returned. + /// + /// + Logger CreateLogger(ILoggerRepository repository, string name); + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Repository/Hierarchy/Logger.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Repository/Hierarchy/Logger.cs index 38975447611..b3696458a13 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Repository/Hierarchy/Logger.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Repository/Hierarchy/Logger.cs @@ -1,771 +1,766 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.Repository.Hierarchy -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; - using System.Collections; - - using log4net.Appender; - using log4net.Core; - using log4net.Util; - - /// - /// Implementation of used by . - /// - /// - /// - /// Internal class used to provide implementation of - /// interface. Applications should use to get - /// logger instances. - /// - /// - /// This is one of the central classes in the log4net implementation. One of the - /// distinctive features of log4net are hierarchical loggers and their - /// evaluation. The organizes the - /// instances into a rooted tree hierarchy. - /// - /// - /// The class is abstract. Only concrete subclasses of - /// can be created. The - /// is used to create instances of this type for the . - /// - /// - /// Nicko Cadell. - /// Gert Driesen. - /// Aspi Havewala. - /// Douglas de la Torre. - public abstract class Logger : IAppenderAttachable, ILogger +using System; + +using log4net.Appender; +using log4net.Util; +using log4net.Core; + +namespace log4net.Repository.Hierarchy +{ + /// + /// Implementation of used by + /// + /// + /// + /// Internal class used to provide implementation of + /// interface. Applications should use to get + /// logger instances. + /// + /// + /// This is one of the central classes in the log4net implementation. One of the + /// distinctive features of log4net are hierarchical loggers and their + /// evaluation. The organizes the + /// instances into a rooted tree hierarchy. + /// + /// + /// The class is abstract. Only concrete subclasses of + /// can be created. The + /// is used to create instances of this type for the . + /// + /// + /// Nicko Cadell + /// Gert Driesen + /// Aspi Havewala + /// Douglas de la Torre + public abstract class Logger : IAppenderAttachable, ILogger { /// - /// Initializes a new instance of the class. - /// This constructor created a new instance and - /// sets its name. - /// - /// The name of the . - /// - /// - /// This constructor is protected and designed to be used by - /// a subclass that is not abstract. - /// - /// - /// Loggers are constructed by - /// objects. See for the default - /// logger creator. - /// - /// - protected Logger(string name) - { -#if NETCF || NETSTANDARD1_3 - // NETCF: String.Intern causes Native Exception - m_name = name; -#else - this.m_name = string.Intern(name); -#endif + /// This constructor created a new instance and + /// sets its name. + /// + /// The name of the . + /// + /// + /// This constructor is protected and designed to be used by + /// a subclass that is not abstract. + /// + /// + /// Loggers are constructed by + /// objects. See for the default + /// logger creator. + /// + /// + protected Logger(string name) + { +#if NETCF || NETSTANDARD1_3 + // NETCF: String.Intern causes Native Exception + m_name = name; +#else + this.m_name = string.Intern(name); +#endif + } + + /// + /// Gets or sets the parent logger in the hierarchy. + /// + /// + /// The parent logger in the hierarchy. + /// + /// + /// + /// Part of the Composite pattern that makes the hierarchy. + /// The hierarchy is parent linked rather than child linked. + /// + /// + public virtual Logger Parent + { + get { return this.m_parent; } + set { this.m_parent = value; } + } + + /// + /// Gets or sets a value indicating if child loggers inherit their parent's appenders. + /// + /// + /// true if child loggers inherit their parent's appenders. + /// + /// + /// + /// Additivity is set to true by default, that is children inherit + /// the appenders of their ancestors by default. If this variable is + /// set to false then the appenders found in the + /// ancestors of this logger are not used. However, the children + /// of this logger will inherit its appenders, unless the children + /// have their additivity flag set to false too. See + /// the user manual for more details. + /// + /// + public virtual bool Additivity + { + get { return this.m_additive; } + set { this.m_additive = value; } + } + + /// + /// Gets the effective level for this logger. + /// + /// The nearest level in the logger hierarchy. + /// + /// + /// Starting from this logger, searches the logger hierarchy for a + /// non-null level and returns it. Otherwise, returns the level of the + /// root logger. + /// + /// The Logger class is designed so that this method executes as + /// quickly as possible. + /// + public virtual Level EffectiveLevel + { + get + { + for(Logger c = this; c != null; c = c.m_parent) + { + Level level = c.m_level; + + // Casting level to Object for performance, otherwise the overloaded operator is called + if ((object)level != null) + { + return level; + } + } + return null; // If reached will cause an NullPointerException. + } + } + + /// + /// Gets or sets the where this + /// Logger instance is attached to. + /// + /// The hierarchy that this logger belongs to. + /// + /// + /// This logger must be attached to a single . + /// + /// + public virtual Hierarchy Hierarchy + { + get { return this.m_hierarchy; } + set { this.m_hierarchy = value; } + } + + /// + /// Gets or sets the assigned , if any, for this Logger. + /// + /// + /// The of this logger. + /// + /// + /// + /// The assigned can be null. + /// + /// + public virtual Level Level + { + get { return this.m_level; } + set { this.m_level = value; } + } + + /// + /// Add to the list of appenders of this + /// Logger instance. + /// + /// An appender to add to this logger + /// + /// + /// Add to the list of appenders of this + /// Logger instance. + /// + /// + /// If is already in the list of + /// appenders, then it won't be added again. + /// + /// + public virtual void AddAppender(IAppender newAppender) + { + if (newAppender == null) + { + throw new ArgumentNullException("newAppender"); + } + + this.m_appenderLock.AcquireWriterLock(); + try + { + if (this.m_appenderAttachedImpl == null) + { + this.m_appenderAttachedImpl = new AppenderAttachedImpl(); + } + + this.m_appenderAttachedImpl.AddAppender(newAppender); + } + finally + { + this.m_appenderLock.ReleaseWriterLock(); + } + } + + /// + /// Get the appenders contained in this logger as an + /// . + /// + /// A collection of the appenders in this logger + /// + /// + /// Get the appenders contained in this logger as an + /// . If no appenders + /// can be found, then a is returned. + /// + /// + public virtual AppenderCollection Appenders + { + get + { + this.m_appenderLock.AcquireReaderLock(); + try + { + if (this.m_appenderAttachedImpl == null) + { + return AppenderCollection.EmptyCollection; + } + else + { + return this.m_appenderAttachedImpl.Appenders; + } + } + finally + { + this.m_appenderLock.ReleaseReaderLock(); + } + } + } + + /// + /// Look for the appender named as name + /// + /// The name of the appender to lookup + /// The appender with the name specified, or null. + /// + /// + /// Returns the named appender, or null if the appender is not found. + /// + /// + public virtual IAppender GetAppender(string name) + { + this.m_appenderLock.AcquireReaderLock(); + try + { + if (this.m_appenderAttachedImpl == null || name == null) + { + return null; + } + + return this.m_appenderAttachedImpl.GetAppender(name); + } + finally + { + this.m_appenderLock.ReleaseReaderLock(); + } + } + + /// + /// Remove all previously added appenders from this Logger instance. + /// + /// + /// + /// Remove all previously added appenders from this Logger instance. + /// + /// + /// This is useful when re-reading configuration information. + /// + /// + public virtual void RemoveAllAppenders() + { + this.m_appenderLock.AcquireWriterLock(); + try + { + if (this.m_appenderAttachedImpl != null) + { + this.m_appenderAttachedImpl.RemoveAllAppenders(); + this.m_appenderAttachedImpl = null; + } + } + finally + { + this.m_appenderLock.ReleaseWriterLock(); + } + } + + /// + /// Remove the appender passed as parameter form the list of appenders. + /// + /// The appender to remove + /// The appender removed from the list + /// + /// + /// Remove the appender passed as parameter form the list of appenders. + /// The appender removed is not closed. + /// If you are discarding the appender you must call + /// on the appender removed. + /// + /// + public virtual IAppender RemoveAppender(IAppender appender) + { + this.m_appenderLock.AcquireWriterLock(); + try + { + if (appender != null && this.m_appenderAttachedImpl != null) + { + return this.m_appenderAttachedImpl.RemoveAppender(appender); + } + } + finally + { + this.m_appenderLock.ReleaseWriterLock(); + } + return null; } - /// - /// Gets or sets the parent logger in the hierarchy. - /// - /// - /// The parent logger in the hierarchy. - /// - /// - /// - /// Part of the Composite pattern that makes the hierarchy. - /// The hierarchy is parent linked rather than child linked. - /// - /// - public virtual Logger Parent - { - get { return this.m_parent; } - set { this.m_parent = value; } - } - - /// - /// Gets or sets a value indicating whether gets or sets a value indicating if child loggers inherit their parent's appenders. - /// - /// - /// true if child loggers inherit their parent's appenders. - /// - /// - /// - /// Additivity is set to true by default, that is children inherit - /// the appenders of their ancestors by default. If this variable is - /// set to false then the appenders found in the - /// ancestors of this logger are not used. However, the children - /// of this logger will inherit its appenders, unless the children - /// have their additivity flag set to false too. See - /// the user manual for more details. - /// - /// - public virtual bool Additivity - { - get { return this.m_additive; } - set { this.m_additive = value; } - } - - /// - /// Gets the effective level for this logger. - /// - /// The nearest level in the logger hierarchy. - /// - /// - /// Starting from this logger, searches the logger hierarchy for a - /// non-null level and returns it. Otherwise, returns the level of the - /// root logger. - /// - /// The Logger class is designed so that this method executes as - /// quickly as possible. - /// - public virtual Level EffectiveLevel - { - get - { - for (Logger c = this; c != null; c = c.m_parent) - { - Level level = c.m_level; - - // Casting level to Object for performance, otherwise the overloaded operator is called - if ((object)level != null) - { - return level; - } - } - - return null; // If reached will cause an NullPointerException. - } - } - - /// - /// Gets or sets the where this - /// Logger instance is attached to. - /// - /// The hierarchy that this logger belongs to. - /// - /// - /// This logger must be attached to a single . - /// - /// - public virtual Hierarchy Hierarchy - { - get { return this.m_hierarchy; } - set { this.m_hierarchy = value; } - } - - /// - /// Gets or sets the assigned , if any, for this Logger. - /// - /// - /// The of this logger. - /// - /// - /// - /// The assigned can be null. - /// - /// - public virtual Level Level - { - get { return this.m_level; } - set { this.m_level = value; } + /// + /// Remove the appender passed as parameter form the list of appenders. + /// + /// The name of the appender to remove + /// The appender removed from the list + /// + /// + /// Remove the named appender passed as parameter form the list of appenders. + /// The appender removed is not closed. + /// If you are discarding the appender you must call + /// on the appender removed. + /// + /// + public virtual IAppender RemoveAppender(string name) + { + this.m_appenderLock.AcquireWriterLock(); + try + { + if (name != null && this.m_appenderAttachedImpl != null) + { + return this.m_appenderAttachedImpl.RemoveAppender(name); + } + } + finally + { + this.m_appenderLock.ReleaseWriterLock(); + } + return null; } - /// - /// Add to the list of appenders of this - /// Logger instance. - /// - /// An appender to add to this logger. - /// - /// - /// Add to the list of appenders of this - /// Logger instance. - /// - /// - /// If is already in the list of - /// appenders, then it won't be added again. - /// - /// - public virtual void AddAppender(IAppender newAppender) - { - if (newAppender == null) - { - throw new ArgumentNullException("newAppender"); - } - - this.m_appenderLock.AcquireWriterLock(); - try - { - if (this.m_appenderAttachedImpl == null) - { - this.m_appenderAttachedImpl = new log4net.Util.AppenderAttachedImpl(); - } - - this.m_appenderAttachedImpl.AddAppender(newAppender); - } - finally - { - this.m_appenderLock.ReleaseWriterLock(); - } - } - - /// - /// Gets get the appenders contained in this logger as an - /// . - /// - /// A collection of the appenders in this logger. - /// - /// - /// Get the appenders contained in this logger as an - /// . If no appenders - /// can be found, then a is returned. - /// - /// - public virtual AppenderCollection Appenders - { - get - { - this.m_appenderLock.AcquireReaderLock(); - try - { - if (this.m_appenderAttachedImpl == null) - { - return AppenderCollection.EmptyCollection; - } - else - { - return this.m_appenderAttachedImpl.Appenders; - } - } - finally - { - this.m_appenderLock.ReleaseReaderLock(); - } - } - } - - /// - /// Look for the appender named as name. - /// - /// The name of the appender to lookup. - /// The appender with the name specified, or null. - /// - /// - /// Returns the named appender, or null if the appender is not found. - /// - /// - public virtual IAppender GetAppender(string name) - { - this.m_appenderLock.AcquireReaderLock(); - try - { - if (this.m_appenderAttachedImpl == null || name == null) - { - return null; - } - - return this.m_appenderAttachedImpl.GetAppender(name); - } - finally - { - this.m_appenderLock.ReleaseReaderLock(); - } - } - - /// - /// Remove all previously added appenders from this Logger instance. - /// - /// - /// - /// Remove all previously added appenders from this Logger instance. - /// - /// - /// This is useful when re-reading configuration information. - /// - /// - public virtual void RemoveAllAppenders() - { - this.m_appenderLock.AcquireWriterLock(); - try - { - if (this.m_appenderAttachedImpl != null) - { - this.m_appenderAttachedImpl.RemoveAllAppenders(); - this.m_appenderAttachedImpl = null; - } - } - finally - { - this.m_appenderLock.ReleaseWriterLock(); - } - } - - /// - /// Remove the appender passed as parameter form the list of appenders. - /// - /// The appender to remove. - /// The appender removed from the list. - /// - /// - /// Remove the appender passed as parameter form the list of appenders. - /// The appender removed is not closed. - /// If you are discarding the appender you must call - /// on the appender removed. - /// - /// - public virtual IAppender RemoveAppender(IAppender appender) - { - this.m_appenderLock.AcquireWriterLock(); - try - { - if (appender != null && this.m_appenderAttachedImpl != null) - { - return this.m_appenderAttachedImpl.RemoveAppender(appender); - } - } - finally - { - this.m_appenderLock.ReleaseWriterLock(); - } - - return null; - } - - /// - /// Remove the appender passed as parameter form the list of appenders. - /// - /// The name of the appender to remove. - /// The appender removed from the list. - /// - /// - /// Remove the named appender passed as parameter form the list of appenders. - /// The appender removed is not closed. - /// If you are discarding the appender you must call - /// on the appender removed. - /// - /// - public virtual IAppender RemoveAppender(string name) - { - this.m_appenderLock.AcquireWriterLock(); - try - { - if (name != null && this.m_appenderAttachedImpl != null) - { - return this.m_appenderAttachedImpl.RemoveAppender(name); - } - } - finally - { - this.m_appenderLock.ReleaseWriterLock(); - } - - return null; + /// + /// Gets the logger name. + /// + /// + /// The name of the logger. + /// + /// + /// + /// The name of this logger + /// + /// + public virtual string Name + { + get { return this.m_name; } } - /// - /// Gets the logger name. - /// - /// - /// The name of the logger. - /// - /// - /// - /// The name of this logger. - /// - /// - public virtual string Name - { - get { return this.m_name; } - } - - /// - /// This generic form is intended to be used by wrappers. - /// - /// The declaring type of the method that is - /// the stack boundary into the logging system for this call. - /// The level of the message to be logged. - /// The message object to log. - /// The exception to log, including its stack trace. - /// - /// - /// Generate a logging event for the specified using - /// the and . - /// - /// - /// This method must not throw any exception to the caller. - /// - /// - public virtual void Log(Type callerStackBoundaryDeclaringType, Level level, object message, Exception exception) - { - try - { - if (this.IsEnabledFor(level)) - { - this.ForcedLog((callerStackBoundaryDeclaringType != null) ? callerStackBoundaryDeclaringType : declaringType, level, message, exception); - } - } - catch (Exception ex) - { - log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); - } -#if !NET_2_0 && !MONO_2_0 && !MONO_3_5 && !MONO_4_0 && !NETSTANDARD1_3 - catch - { - log4net.Util.LogLog.Error(declaringType, "Exception while logging"); - } -#endif - } - - /// - /// This is the most generic printing method that is intended to be used - /// by wrappers. - /// - /// The event being logged. - /// - /// - /// Logs the specified logging event through this logger. - /// - /// - /// This method must not throw any exception to the caller. - /// - /// - public virtual void Log(LoggingEvent logEvent) - { - try - { - if (logEvent != null) - { - if (this.IsEnabledFor(logEvent.Level)) - { - this.ForcedLog(logEvent); - } - } - } - catch (Exception ex) - { - log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); - } -#if !NET_2_0 && !MONO_2_0 && !MONO_3_5 && !MONO_4_0 && !NETSTANDARD1_3 - catch - { - log4net.Util.LogLog.Error(declaringType, "Exception while logging"); - } -#endif - } - - /// - /// Checks if this logger is enabled for a given passed as parameter. - /// - /// The level to check. - /// - /// true if this logger is enabled for level, otherwise false. - /// - /// - /// - /// Test if this logger is going to log events of the specified . - /// - /// - /// This method must not throw any exception to the caller. - /// - /// - public virtual bool IsEnabledFor(Level level) - { - try - { - if (level != null) - { - if (this.m_hierarchy.IsDisabled(level)) - { - return false; - } - - return level >= this.EffectiveLevel; - } - } - catch (Exception ex) - { - log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); - } -#if !NET_2_0 && !MONO_2_0 && !MONO_3_5 && !MONO_4_0 && !NETSTANDARD1_3 - catch - { - log4net.Util.LogLog.Error(declaringType, "Exception while logging"); - } -#endif - return false; - } - - /// - /// Gets the where this - /// Logger instance is attached to. - /// - /// - /// The that this logger belongs to. - /// - /// - /// - /// Gets the where this - /// Logger instance is attached to. - /// - /// - public ILoggerRepository Repository - { - get { return this.m_hierarchy; } + /// + /// This generic form is intended to be used by wrappers. + /// + /// The declaring type of the method that is + /// the stack boundary into the logging system for this call. + /// The level of the message to be logged. + /// The message object to log. + /// The exception to log, including its stack trace. + /// + /// + /// Generate a logging event for the specified using + /// the and . + /// + /// + /// This method must not throw any exception to the caller. + /// + /// + public virtual void Log(Type callerStackBoundaryDeclaringType, Level level, object message, Exception exception) + { + try + { + if (this.IsEnabledFor(level)) + { + this.ForcedLog((callerStackBoundaryDeclaringType != null) ? callerStackBoundaryDeclaringType : declaringType, level, message, exception); + } + } + catch (Exception ex) + { + LogLog.Error(declaringType, "Exception while logging", ex); + } +#if !NET_2_0 && !MONO_2_0 && !MONO_3_5 && !MONO_4_0 && !NETSTANDARD + catch + { + log4net.Util.LogLog.Error(declaringType, "Exception while logging"); + } +#endif } - /// - /// Deliver the to the attached appenders. - /// - /// The event to log. - /// - /// - /// Call the appenders in the hierarchy starting at - /// this. If no appenders could be found, emit a - /// warning. - /// - /// - /// This method calls all the appenders inherited from the - /// hierarchy circumventing any evaluation of whether to log or not - /// to log the particular log request. - /// - /// - protected virtual void CallAppenders(LoggingEvent loggingEvent) - { - if (loggingEvent == null) - { - throw new ArgumentNullException("loggingEvent"); - } - - int writes = 0; - - for (Logger c = this; c != null; c = c.m_parent) - { - if (c.m_appenderAttachedImpl != null) - { - // Protected against simultaneous call to addAppender, removeAppender,... - c.m_appenderLock.AcquireReaderLock(); - try - { - if (c.m_appenderAttachedImpl != null) - { - writes += c.m_appenderAttachedImpl.AppendLoopOnAppenders(loggingEvent); - } - } - finally - { - c.m_appenderLock.ReleaseReaderLock(); - } - } - - if (!c.m_additive) - { - break; - } - } - - // No appenders in hierarchy, warn user only once. - // - // Note that by including the AppDomain values for the currently running - // thread, it becomes much easier to see which application the warning - // is from, which is especially helpful in a multi-AppDomain environment - // (like IIS with multiple VDIRS). Without this, it can be difficult - // or impossible to determine which .config file is missing appender - // definitions. - if (!this.m_hierarchy.EmittedNoAppenderWarning && writes == 0) - { - this.m_hierarchy.EmittedNoAppenderWarning = true; - LogLog.Debug(declaringType, "No appenders could be found for logger [" + this.Name + "] repository [" + this.Repository.Name + "]"); - LogLog.Debug(declaringType, "Please initialize the log4net system properly."); - try - { - LogLog.Debug(declaringType, " Current AppDomain context information: "); - LogLog.Debug(declaringType, " BaseDirectory : " + SystemInfo.ApplicationBaseDirectory); -#if !(NETCF || NETSTANDARD1_3) - LogLog.Debug(declaringType, " FriendlyName : " + AppDomain.CurrentDomain.FriendlyName); - LogLog.Debug(declaringType, " DynamicDirectory: " + AppDomain.CurrentDomain.DynamicDirectory); -#endif - } - catch (System.Security.SecurityException) - { - // Insufficient permissions to display info from the AppDomain - } - } - } - - /// - /// Closes all attached appenders implementing the interface. - /// - /// - /// - /// Used to ensure that the appenders are correctly shutdown. - /// - /// - public virtual void CloseNestedAppenders() - { - this.m_appenderLock.AcquireWriterLock(); - try - { - if (this.m_appenderAttachedImpl != null) - { - AppenderCollection appenders = this.m_appenderAttachedImpl.Appenders; - foreach (IAppender appender in appenders) - { - if (appender is IAppenderAttachable) - { - appender.Close(); - } - } - } - } - finally - { - this.m_appenderLock.ReleaseWriterLock(); - } - } - - /// - /// This is the most generic printing method. This generic form is intended to be used by wrappers. - /// - /// The level of the message to be logged. - /// The message object to log. - /// The exception to log, including its stack trace. - /// - /// - /// Generate a logging event for the specified using - /// the . - /// - /// - public virtual void Log(Level level, object message, Exception exception) - { - if (this.IsEnabledFor(level)) - { - this.ForcedLog(declaringType, level, message, exception); - } - } - - /// - /// Creates a new logging event and logs the event without further checks. - /// - /// The declaring type of the method that is - /// the stack boundary into the logging system for this call. - /// The level of the message to be logged. - /// The message object to log. - /// The exception to log, including its stack trace. - /// - /// - /// Generates a logging event and delivers it to the attached - /// appenders. - /// - /// - protected virtual void ForcedLog(Type callerStackBoundaryDeclaringType, Level level, object message, Exception exception) - { - this.CallAppenders(new LoggingEvent(callerStackBoundaryDeclaringType, this.Hierarchy, this.Name, level, message, exception)); - } - - /// - /// Creates a new logging event and logs the event without further checks. - /// - /// The event being logged. - /// - /// - /// Delivers the logging event to the attached appenders. - /// - /// - protected virtual void ForcedLog(LoggingEvent logEvent) - { - // The logging event may not have been created by this logger - // the Repository may not be correctly set on the event. This - // is required for the appenders to correctly lookup renderers etc... - logEvent.EnsureRepository(this.Hierarchy); - - this.CallAppenders(logEvent); + /// + /// This is the most generic printing method that is intended to be used + /// by wrappers. + /// + /// The event being logged. + /// + /// + /// Logs the specified logging event through this logger. + /// + /// + /// This method must not throw any exception to the caller. + /// + /// + public virtual void Log(LoggingEvent logEvent) + { + try + { + if (logEvent != null) + { + if (this.IsEnabledFor(logEvent.Level)) + { + this.ForcedLog(logEvent); + } + } + } + catch (Exception ex) + { + LogLog.Error(declaringType, "Exception while logging", ex); + } +#if !NET_2_0 && !MONO_2_0 && !MONO_3_5 && !MONO_4_0 && !NETSTANDARD + catch + { + log4net.Util.LogLog.Error(declaringType, "Exception while logging"); + } +#endif } - /// - /// The fully qualified type of the Logger class. - /// + /// + /// Checks if this logger is enabled for a given passed as parameter. + /// + /// The level to check. + /// + /// true if this logger is enabled for level, otherwise false. + /// + /// + /// + /// Test if this logger is going to log events of the specified . + /// + /// + /// This method must not throw any exception to the caller. + /// + /// + public virtual bool IsEnabledFor(Level level) + { + try + { + if (level != null) + { + if (this.m_hierarchy.IsDisabled(level)) + { + return false; + } + return level >= this.EffectiveLevel; + } + } + catch (Exception ex) + { + LogLog.Error(declaringType, "Exception while logging", ex); + } +#if !NET_2_0 && !MONO_2_0 && !MONO_3_5 && !MONO_4_0 && !NETSTANDARD + catch + { + log4net.Util.LogLog.Error(declaringType, "Exception while logging"); + } +#endif + return false; + } + + /// + /// Gets the where this + /// Logger instance is attached to. + /// + /// + /// The that this logger belongs to. + /// + /// + /// + /// Gets the where this + /// Logger instance is attached to. + /// + /// + public ILoggerRepository Repository + { + get { return this.m_hierarchy; } + } + + /// + /// Deliver the to the attached appenders. + /// + /// The event to log. + /// + /// + /// Call the appenders in the hierarchy starting at + /// this. If no appenders could be found, emit a + /// warning. + /// + /// + /// This method calls all the appenders inherited from the + /// hierarchy circumventing any evaluation of whether to log or not + /// to log the particular log request. + /// + /// + protected virtual void CallAppenders(LoggingEvent loggingEvent) + { + if (loggingEvent == null) + { + throw new ArgumentNullException("loggingEvent"); + } + + int writes = 0; + + for(Logger c = this; c != null; c = c.m_parent) + { + if (c.m_appenderAttachedImpl != null) + { + // Protected against simultaneous call to addAppender, removeAppender,... + c.m_appenderLock.AcquireReaderLock(); + try + { + if (c.m_appenderAttachedImpl != null) + { + writes += c.m_appenderAttachedImpl.AppendLoopOnAppenders(loggingEvent); + } + } + finally + { + c.m_appenderLock.ReleaseReaderLock(); + } + } + + if (!c.m_additive) + { + break; + } + } + + // No appenders in hierarchy, warn user only once. + // + // Note that by including the AppDomain values for the currently running + // thread, it becomes much easier to see which application the warning + // is from, which is especially helpful in a multi-AppDomain environment + // (like IIS with multiple VDIRS). Without this, it can be difficult + // or impossible to determine which .config file is missing appender + // definitions. + // + if (!this.m_hierarchy.EmittedNoAppenderWarning && writes == 0) + { + this.m_hierarchy.EmittedNoAppenderWarning = true; + LogLog.Debug(declaringType, "No appenders could be found for logger [" + this.Name + "] repository [" + this.Repository.Name + "]"); + LogLog.Debug(declaringType, "Please initialize the log4net system properly."); + try + { + LogLog.Debug(declaringType, " Current AppDomain context information: "); + LogLog.Debug(declaringType, " BaseDirectory : " + SystemInfo.ApplicationBaseDirectory); +#if !NETCF && !NETSTANDARD1_3 + LogLog.Debug(declaringType, " FriendlyName : " + AppDomain.CurrentDomain.FriendlyName); + LogLog.Debug(declaringType, " DynamicDirectory: " + AppDomain.CurrentDomain.DynamicDirectory); +#endif + } + catch(System.Security.SecurityException) + { + // Insufficient permissions to display info from the AppDomain + } + } + } + + /// + /// Closes all attached appenders implementing the interface. + /// + /// + /// + /// Used to ensure that the appenders are correctly shutdown. + /// + /// + public virtual void CloseNestedAppenders() + { + this.m_appenderLock.AcquireWriterLock(); + try + { + if (this.m_appenderAttachedImpl != null) + { + AppenderCollection appenders = this.m_appenderAttachedImpl.Appenders; + foreach(IAppender appender in appenders) + { + if (appender is IAppenderAttachable) + { + appender.Close(); + } + } + } + } + finally + { + this.m_appenderLock.ReleaseWriterLock(); + } + } + + /// + /// This is the most generic printing method. This generic form is intended to be used by wrappers + /// + /// The level of the message to be logged. + /// The message object to log. + /// The exception to log, including its stack trace. + /// + /// + /// Generate a logging event for the specified using + /// the . + /// + /// + public virtual void Log(Level level, object message, Exception exception) + { + if (this.IsEnabledFor(level)) + { + this.ForcedLog(declaringType, level, message, exception); + } + } + + /// + /// Creates a new logging event and logs the event without further checks. + /// + /// The declaring type of the method that is + /// the stack boundary into the logging system for this call. + /// The level of the message to be logged. + /// The message object to log. + /// The exception to log, including its stack trace. + /// + /// + /// Generates a logging event and delivers it to the attached + /// appenders. + /// + /// + protected virtual void ForcedLog(Type callerStackBoundaryDeclaringType, Level level, object message, Exception exception) + { + this.CallAppenders(new LoggingEvent(callerStackBoundaryDeclaringType, this.Hierarchy, this.Name, level, message, exception)); + } + + /// + /// Creates a new logging event and logs the event without further checks. + /// + /// The event being logged. + /// + /// + /// Delivers the logging event to the attached appenders. + /// + /// + protected virtual void ForcedLog(LoggingEvent logEvent) + { + // The logging event may not have been created by this logger + // the Repository may not be correctly set on the event. This + // is required for the appenders to correctly lookup renderers etc... + logEvent.EnsureRepository(this.Hierarchy); + + this.CallAppenders(logEvent); + } + + /// + /// The fully qualified type of the Logger class. + /// private static readonly Type declaringType = typeof(Logger); - /// - /// The name of this logger. - /// - private readonly string m_name; - - /// - /// The assigned level of this logger. - /// - /// - /// - /// The level variable need not be - /// assigned a value in which case it is inherited - /// form the hierarchy. - /// - /// - private Level m_level; - - /// - /// The parent of this logger. - /// - /// - /// - /// The parent of this logger. - /// All loggers have at least one ancestor which is the root logger. - /// - /// - private Logger m_parent; - - /// - /// Loggers need to know what Hierarchy they are in. - /// - /// - /// - /// Loggers need to know what Hierarchy they are in. - /// The hierarchy that this logger is a member of is stored - /// here. - /// - /// - private Hierarchy m_hierarchy; - - /// - /// Helper implementation of the interface. - /// - private log4net.Util.AppenderAttachedImpl m_appenderAttachedImpl; - - /// - /// Flag indicating if child loggers inherit their parents appenders. - /// - /// - /// - /// Additivity is set to true by default, that is children inherit - /// the appenders of their ancestors by default. If this variable is - /// set to false then the appenders found in the - /// ancestors of this logger are not used. However, the children - /// of this logger will inherit its appenders, unless the children - /// have their additivity flag set to false too. See - /// the user manual for more details. - /// - /// - private bool m_additive = true; - - /// - /// Lock to protect AppenderAttachedImpl variable m_appenderAttachedImpl. - /// + /// + /// The name of this logger. + /// + private readonly string m_name; + + /// + /// The assigned level of this logger. + /// + /// + /// + /// The level variable need not be + /// assigned a value in which case it is inherited + /// form the hierarchy. + /// + /// + private Level m_level; + + /// + /// The parent of this logger. + /// + /// + /// + /// The parent of this logger. + /// All loggers have at least one ancestor which is the root logger. + /// + /// + private Logger m_parent; + + /// + /// Loggers need to know what Hierarchy they are in. + /// + /// + /// + /// Loggers need to know what Hierarchy they are in. + /// The hierarchy that this logger is a member of is stored + /// here. + /// + /// + private Hierarchy m_hierarchy; + + /// + /// Helper implementation of the interface + /// + private AppenderAttachedImpl m_appenderAttachedImpl; + + /// + /// Flag indicating if child loggers inherit their parents appenders + /// + /// + /// + /// Additivity is set to true by default, that is children inherit + /// the appenders of their ancestors by default. If this variable is + /// set to false then the appenders found in the + /// ancestors of this logger are not used. However, the children + /// of this logger will inherit its appenders, unless the children + /// have their additivity flag set to false too. See + /// the user manual for more details. + /// + /// + private bool m_additive = true; + + /// + /// Lock to protect AppenderAttachedImpl variable m_appenderAttachedImpl + /// private readonly ReaderWriterLock m_appenderLock = new ReaderWriterLock(); - } -} + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Repository/Hierarchy/LoggerKey.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Repository/Hierarchy/LoggerKey.cs index 61362c47c7f..6d66f9397a3 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Repository/Hierarchy/LoggerKey.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Repository/Hierarchy/LoggerKey.cs @@ -1,128 +1,127 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.Repository.Hierarchy -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; +using System; - /// - /// Used internally to accelerate hash table searches. - /// - /// - /// - /// Internal class used to improve performance of - /// string keyed hashtables. - /// - /// - /// The hashcode of the string is cached for reuse. - /// The string is stored as an interned value. - /// When comparing two objects for equality - /// the reference equality of the interned strings is compared. - /// - /// - /// Nicko Cadell. - /// Gert Driesen. - internal sealed class LoggerKey +namespace log4net.Repository.Hierarchy +{ + /// + /// Used internally to accelerate hash table searches. + /// + /// + /// + /// Internal class used to improve performance of + /// string keyed hashtables. + /// + /// + /// The hashcode of the string is cached for reuse. + /// The string is stored as an interned value. + /// When comparing two objects for equality + /// the reference equality of the interned strings is compared. + /// + /// + /// Nicko Cadell + /// Gert Driesen + internal sealed class LoggerKey { /// - /// Initializes a new instance of the class. - /// Construct key with string name. - /// - /// - /// - /// Initializes a new instance of the class - /// with the specified name. - /// - /// - /// Stores the hashcode of the string and interns - /// the string key to optimize comparisons. - /// - /// - /// The Compact Framework 1.0 the - /// method does not work. On the Compact Framework - /// the string keys are not interned nor are they - /// compared by reference. - /// - /// - /// The name of the logger. - internal LoggerKey(string name) - { -#if NETCF || NETSTANDARD1_3 - // NETCF: String.Intern causes Native Exception - m_name = name; -#else - this.m_name = string.Intern(name); -#endif - this.m_hashCache = name.GetHashCode(); + /// Construct key with string name + /// + /// + /// + /// Initializes a new instance of the class + /// with the specified name. + /// + /// + /// Stores the hashcode of the string and interns + /// the string key to optimize comparisons. + /// + /// + /// The Compact Framework 1.0 the + /// method does not work. On the Compact Framework + /// the string keys are not interned nor are they + /// compared by reference. + /// + /// + /// The name of the logger. + internal LoggerKey(string name) + { +#if NETCF || NETSTANDARD1_3 + // NETCF: String.Intern causes Native Exception + m_name = name; +#else + this.m_name = string.Intern(name); +#endif + this.m_hashCache = name.GetHashCode(); } - /// - /// Returns a hash code for the current instance. - /// - /// A hash code for the current instance. - /// - /// - /// Returns the cached hashcode. - /// - /// - public override int GetHashCode() - { - return this.m_hashCache; - } - - /// - /// Determines whether two instances - /// are equal. - /// - /// The to compare with the current . - /// - /// true if the specified is equal to the current ; otherwise, false. - /// - /// - /// - /// Compares the references of the interned strings. - /// - /// - public override bool Equals(object obj) - { - // Compare reference type of this against argument - if (((object)this) == obj) - { - return true; - } - - LoggerKey objKey = obj as LoggerKey; - if (objKey != null) - { -#if NETCF || NETSTANDARD1_3 - return ( m_name == objKey.m_name ); -#else - // Compare reference types rather than string's overloaded == - return ((object)this.m_name) == ((object)objKey.m_name); -#endif - } + /// + /// Returns a hash code for the current instance. + /// + /// A hash code for the current instance. + /// + /// + /// Returns the cached hashcode. + /// + /// + public override int GetHashCode() + { + return this.m_hashCache; + } - return false; + /// + /// Determines whether two instances + /// are equal. + /// + /// The to compare with the current . + /// + /// true if the specified is equal to the current ; otherwise, false. + /// + /// + /// + /// Compares the references of the interned strings. + /// + /// + public override bool Equals(object obj) + { + // Compare reference type of this against argument + if (((object)this) == obj) + { + return true; + } + + LoggerKey objKey = obj as LoggerKey; + if (objKey != null) + { +#if NETCF || NETSTANDARD1_3 + return ( m_name == objKey.m_name ); +#else + // Compare reference types rather than string's overloaded == + return ( ((object)this.m_name) == ((object)objKey.m_name) ); +#endif + } + return false; } - private readonly string m_name; + private readonly string m_name; private readonly int m_hashCache; - } + } } + diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Repository/Hierarchy/ProvisionNode.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Repository/Hierarchy/ProvisionNode.cs index a10e91afef3..1697bbefb23 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Repository/Hierarchy/ProvisionNode.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Repository/Hierarchy/ProvisionNode.cs @@ -1,61 +1,59 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.Repository.Hierarchy -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; - using System.Collections; +using System; +using System.Collections; - /// - /// Provision nodes are used where no logger instance has been specified. - /// - /// - /// - /// instances are used in the - /// when there is no specified - /// for that node. - /// - /// - /// A provision node holds a list of child loggers on behalf of - /// a logger that does not exist. - /// - /// - /// Nicko Cadell. - /// Gert Driesen. - internal sealed class ProvisionNode : ArrayList +namespace log4net.Repository.Hierarchy +{ + /// + /// Provision nodes are used where no logger instance has been specified + /// + /// + /// + /// instances are used in the + /// when there is no specified + /// for that node. + /// + /// + /// A provision node holds a list of child loggers on behalf of + /// a logger that does not exist. + /// + /// + /// Nicko Cadell + /// Gert Driesen + internal sealed class ProvisionNode : ArrayList { /// - /// Initializes a new instance of the class. - /// Create a new provision node with child node. - /// - /// A child logger to add to this node. - /// - /// - /// Initializes a new instance of the class - /// with the specified child logger. - /// - /// - internal ProvisionNode(Logger log) - : base() - { - this.Add(log); - } - } -} + /// Create a new provision node with child node + /// + /// A child logger to add to this node. + /// + /// + /// Initializes a new instance of the class + /// with the specified child logger. + /// + /// + internal ProvisionNode(Logger log) : base() + { + this.Add(log); + } + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Repository/Hierarchy/RootLogger.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Repository/Hierarchy/RootLogger.cs index 7d22ba3ba8f..19e5b940062 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Repository/Hierarchy/RootLogger.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Repository/Hierarchy/RootLogger.cs @@ -1,125 +1,122 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.Repository.Hierarchy -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; +using System; - using log4net.Core; - using log4net.Util; +using log4net.Util; +using log4net.Core; - /// - /// The sits at the root of the logger hierarchy tree. - /// - /// - /// - /// The is a regular except - /// that it provides several guarantees. - /// - /// - /// First, it cannot be assigned a null - /// level. Second, since the root logger cannot have a parent, the - /// property always returns the value of the - /// level field without walking the hierarchy. - /// - /// - /// Nicko Cadell. - /// Gert Driesen. - public class RootLogger : Logger +namespace log4net.Repository.Hierarchy +{ + /// + /// The sits at the root of the logger hierarchy tree. + /// + /// + /// + /// The is a regular except + /// that it provides several guarantees. + /// + /// + /// First, it cannot be assigned a null + /// level. Second, since the root logger cannot have a parent, the + /// property always returns the value of the + /// level field without walking the hierarchy. + /// + /// + /// Nicko Cadell + /// Gert Driesen + public class RootLogger : Logger { /// - /// Initializes a new instance of the class. - /// Construct a . - /// - /// The level to assign to the root logger. - /// - /// - /// Initializes a new instance of the class with - /// the specified logging level. - /// - /// - /// The root logger names itself as "root". However, the root - /// logger cannot be retrieved by name. - /// - /// - public RootLogger(Level level) - : base("root") - { - this.Level = level; + /// Construct a + /// + /// The level to assign to the root logger. + /// + /// + /// Initializes a new instance of the class with + /// the specified logging level. + /// + /// + /// The root logger names itself as "root". However, the root + /// logger cannot be retrieved by name. + /// + /// + public RootLogger(Level level) : base("root") + { + this.Level = level; } - /// - /// Gets the assigned level value without walking the logger hierarchy. - /// - /// The assigned level value without walking the logger hierarchy. - /// - /// - /// Because the root logger cannot have a parent and its level - /// must not be null this property just returns the - /// value of . - /// - /// - public override Level EffectiveLevel - { - get - { - return base.Level; - } - } - - /// - /// Gets or sets the assigned for the root logger. - /// - /// - /// The of the root logger. - /// - /// - /// - /// Setting the level of the root logger to a null reference - /// may have catastrophic results. We prevent this here. - /// - /// - public override Level Level - { - get { return base.Level; } + /// + /// Gets the assigned level value without walking the logger hierarchy. + /// + /// The assigned level value without walking the logger hierarchy. + /// + /// + /// Because the root logger cannot have a parent and its level + /// must not be null this property just returns the + /// value of . + /// + /// + public override Level EffectiveLevel + { + get + { + return base.Level; + } + } - set - { - if (value == null) - { - LogLog.Error(declaringType, "You have tried to set a null level to root.", new LogException()); - } - else - { - base.Level = value; - } - } + /// + /// Gets or sets the assigned for the root logger. + /// + /// + /// The of the root logger. + /// + /// + /// + /// Setting the level of the root logger to a null reference + /// may have catastrophic results. We prevent this here. + /// + /// + public override Level Level + { + get { return base.Level; } + set + { + if (value == null) + { + LogLog.Error(declaringType, "You have tried to set a null level to root.", new LogException()); + } + else + { + base.Level = value; + } + } } - /// - /// The fully qualified type of the RootLogger class. - /// - /// - /// Used by the internal logger to record the Type of the - /// log message. - /// + /// + /// The fully qualified type of the RootLogger class. + /// + /// + /// Used by the internal logger to record the Type of the + /// log message. + /// private static readonly Type declaringType = typeof(RootLogger); - } -} + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Repository/Hierarchy/XmlHierarchyConfigurator.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Repository/Hierarchy/XmlHierarchyConfigurator.cs index 45456f8f4de..63ab6062b62 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Repository/Hierarchy/XmlHierarchyConfigurator.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Repository/Hierarchy/XmlHierarchyConfigurator.cs @@ -1,1150 +1,1141 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.Repository.Hierarchy -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; - using System.Collections; - using System.Globalization; - using System.Reflection; - using System.Xml; - - using log4net.Appender; - using log4net.Core; - using log4net.ObjectRenderer; - using log4net.Util; - - /// - /// Initializes the log4net environment using an XML DOM. - /// - /// - /// - /// Configures a using an XML DOM. - /// - /// - /// Nicko Cadell. - /// Gert Driesen. - public class XmlHierarchyConfigurator - { - private enum ConfigUpdateMode - { - Merge, - Overwrite, +using System; +using System.Collections; +using System.Globalization; +using System.Reflection; +using System.Xml; + +using log4net.Appender; +using log4net.Util; +using log4net.Core; +using log4net.ObjectRenderer; + +namespace log4net.Repository.Hierarchy +{ + /// + /// Initializes the log4net environment using an XML DOM. + /// + /// + /// + /// Configures a using an XML DOM. + /// + /// + /// Nicko Cadell + /// Gert Driesen + public class XmlHierarchyConfigurator + { + private enum ConfigUpdateMode + { + Merge, + Overwrite } /// - /// Initializes a new instance of the class. - /// Construct the configurator for a hierarchy. - /// - /// The hierarchy to build. - /// - /// - /// Initializes a new instance of the class - /// with the specified . - /// - /// - public XmlHierarchyConfigurator(Hierarchy hierarchy) - { - this.m_hierarchy = hierarchy; - this.m_appenderBag = new Hashtable(); + /// Construct the configurator for a hierarchy + /// + /// The hierarchy to build. + /// + /// + /// Initializes a new instance of the class + /// with the specified . + /// + /// + public XmlHierarchyConfigurator(Hierarchy hierarchy) + { + this.m_hierarchy = hierarchy; + this.m_appenderBag = new Hashtable(); } - /// - /// Configure the hierarchy by parsing a DOM tree of XML elements. - /// - /// The root element to parse. - /// - /// - /// Configure the hierarchy by parsing a DOM tree of XML elements. - /// - /// - public void Configure(XmlElement element) - { - if (element == null || this.m_hierarchy == null) - { - return; - } - - string rootElementName = element.LocalName; - - if (rootElementName != CONFIGURATION_TAG) - { - LogLog.Error(declaringType, "Xml element is - not a <" + CONFIGURATION_TAG + "> element."); - return; - } - - if (!LogLog.EmitInternalMessages) - { - // Look for a emitDebug attribute to enable internal debug - string emitDebugAttribute = element.GetAttribute(EMIT_INTERNAL_DEBUG_ATTR); - LogLog.Debug(declaringType, EMIT_INTERNAL_DEBUG_ATTR + " attribute [" + emitDebugAttribute + "]."); - - if (emitDebugAttribute.Length > 0 && emitDebugAttribute != "null") - { - LogLog.EmitInternalMessages = OptionConverter.ToBoolean(emitDebugAttribute, true); - } - else - { - LogLog.Debug(declaringType, "Ignoring " + EMIT_INTERNAL_DEBUG_ATTR + " attribute."); - } - } - - if (!LogLog.InternalDebugging) - { - // Look for a debug attribute to enable internal debug - string debugAttribute = element.GetAttribute(INTERNAL_DEBUG_ATTR); - LogLog.Debug(declaringType, INTERNAL_DEBUG_ATTR + " attribute [" + debugAttribute + "]."); - - if (debugAttribute.Length > 0 && debugAttribute != "null") - { - LogLog.InternalDebugging = OptionConverter.ToBoolean(debugAttribute, true); - } - else - { - LogLog.Debug(declaringType, "Ignoring " + INTERNAL_DEBUG_ATTR + " attribute."); - } - - string confDebug = element.GetAttribute(CONFIG_DEBUG_ATTR); - if (confDebug.Length > 0 && confDebug != "null") - { - LogLog.Warn(declaringType, "The \"" + CONFIG_DEBUG_ATTR + "\" attribute is deprecated."); - LogLog.Warn(declaringType, "Use the \"" + INTERNAL_DEBUG_ATTR + "\" attribute instead."); - LogLog.InternalDebugging = OptionConverter.ToBoolean(confDebug, true); - } - } - - // Default mode is merge - ConfigUpdateMode configUpdateMode = ConfigUpdateMode.Merge; - - // Look for the config update attribute - string configUpdateModeAttribute = element.GetAttribute(CONFIG_UPDATE_MODE_ATTR); - if (configUpdateModeAttribute != null && configUpdateModeAttribute.Length > 0) - { - // Parse the attribute - try - { - configUpdateMode = (ConfigUpdateMode)OptionConverter.ConvertStringTo(typeof(ConfigUpdateMode), configUpdateModeAttribute); - } - catch - { - LogLog.Error(declaringType, "Invalid " + CONFIG_UPDATE_MODE_ATTR + " attribute value [" + configUpdateModeAttribute + "]"); - } - } - - // IMPL: The IFormatProvider argument to Enum.ToString() is deprecated in .NET 2.0 - LogLog.Debug(declaringType, "Configuration update mode [" + configUpdateMode.ToString() + "]."); - - // Only reset configuration if overwrite flag specified - if (configUpdateMode == ConfigUpdateMode.Overwrite) - { - // Reset to original unset configuration - this.m_hierarchy.ResetConfiguration(); - LogLog.Debug(declaringType, "Configuration reset before reading config."); - } - - /* Building Appender objects, placing them in a local namespace - for future reference */ - - /* Process all the top level elements */ - - foreach (XmlNode currentNode in element.ChildNodes) - { - if (currentNode.NodeType == XmlNodeType.Element) - { - XmlElement currentElement = (XmlElement)currentNode; - - if (currentElement.LocalName == LOGGER_TAG) - { - this.ParseLogger(currentElement); - } - else if (currentElement.LocalName == CATEGORY_TAG) - { - // TODO: deprecated use of category - this.ParseLogger(currentElement); - } - else if (currentElement.LocalName == ROOT_TAG) - { - this.ParseRoot(currentElement); - } - else if (currentElement.LocalName == RENDERER_TAG) - { - this.ParseRenderer(currentElement); - } - else if (currentElement.LocalName == APPENDER_TAG) - { - // We ignore appenders in this pass. They will - // be found and loaded if they are referenced. - } - else - { - // Read the param tags and set properties on the hierarchy - this.SetParameter(currentElement, this.m_hierarchy); - } - } - } - - // Lastly set the hierarchy threshold - string thresholdStr = element.GetAttribute(THRESHOLD_ATTR); - LogLog.Debug(declaringType, "Hierarchy Threshold [" + thresholdStr + "]"); - if (thresholdStr.Length > 0 && thresholdStr != "null") - { - Level thresholdLevel = (Level)this.ConvertStringTo(typeof(Level), thresholdStr); - if (thresholdLevel != null) - { - this.m_hierarchy.Threshold = thresholdLevel; - } - else - { - LogLog.Warn(declaringType, "Unable to set hierarchy threshold using value [" + thresholdStr + "] (with acceptable conversion types)"); - } - } - - // Done reading config + /// + /// Configure the hierarchy by parsing a DOM tree of XML elements. + /// + /// The root element to parse. + /// + /// + /// Configure the hierarchy by parsing a DOM tree of XML elements. + /// + /// + public void Configure(XmlElement element) + { + if (element == null || this.m_hierarchy == null) + { + return; + } + + string rootElementName = element.LocalName; + + if (rootElementName != CONFIGURATION_TAG) + { + LogLog.Error(declaringType, "Xml element is - not a <" + CONFIGURATION_TAG + "> element."); + return; + } + + if (!LogLog.EmitInternalMessages) + { + // Look for a emitDebug attribute to enable internal debug + string emitDebugAttribute = element.GetAttribute(EMIT_INTERNAL_DEBUG_ATTR); + LogLog.Debug(declaringType, EMIT_INTERNAL_DEBUG_ATTR + " attribute [" + emitDebugAttribute + "]."); + + if (emitDebugAttribute.Length > 0 && emitDebugAttribute != "null") + { + LogLog.EmitInternalMessages = OptionConverter.ToBoolean(emitDebugAttribute, true); + } + else + { + LogLog.Debug(declaringType, "Ignoring " + EMIT_INTERNAL_DEBUG_ATTR + " attribute."); + } + } + + if (!LogLog.InternalDebugging) + { + // Look for a debug attribute to enable internal debug + string debugAttribute = element.GetAttribute(INTERNAL_DEBUG_ATTR); + LogLog.Debug(declaringType, INTERNAL_DEBUG_ATTR+" attribute [" + debugAttribute + "]."); + + if (debugAttribute.Length > 0 && debugAttribute != "null") + { + LogLog.InternalDebugging = OptionConverter.ToBoolean(debugAttribute, true); + } + else + { + LogLog.Debug(declaringType, "Ignoring " + INTERNAL_DEBUG_ATTR + " attribute."); + } + + string confDebug = element.GetAttribute(CONFIG_DEBUG_ATTR); + if (confDebug.Length > 0 && confDebug != "null") + { + LogLog.Warn(declaringType, "The \"" + CONFIG_DEBUG_ATTR + "\" attribute is deprecated."); + LogLog.Warn(declaringType, "Use the \"" + INTERNAL_DEBUG_ATTR + "\" attribute instead."); + LogLog.InternalDebugging = OptionConverter.ToBoolean(confDebug, true); + } + } + + // Default mode is merge + ConfigUpdateMode configUpdateMode = ConfigUpdateMode.Merge; + + // Look for the config update attribute + string configUpdateModeAttribute = element.GetAttribute(CONFIG_UPDATE_MODE_ATTR); + if (configUpdateModeAttribute != null && configUpdateModeAttribute.Length > 0) + { + // Parse the attribute + try + { + configUpdateMode = (ConfigUpdateMode)OptionConverter.ConvertStringTo(typeof(ConfigUpdateMode), configUpdateModeAttribute); + } + catch + { + LogLog.Error(declaringType, "Invalid " + CONFIG_UPDATE_MODE_ATTR + " attribute value [" + configUpdateModeAttribute + "]"); + } + } + + // IMPL: The IFormatProvider argument to Enum.ToString() is deprecated in .NET 2.0 + LogLog.Debug(declaringType, "Configuration update mode [" + configUpdateMode.ToString() + "]."); + + // Only reset configuration if overwrite flag specified + if (configUpdateMode == ConfigUpdateMode.Overwrite) + { + // Reset to original unset configuration + this.m_hierarchy.ResetConfiguration(); + LogLog.Debug(declaringType, "Configuration reset before reading config."); + } + + /* Building Appender objects, placing them in a local namespace + for future reference */ + + /* Process all the top level elements */ + + foreach (XmlNode currentNode in element.ChildNodes) + { + if (currentNode.NodeType == XmlNodeType.Element) + { + XmlElement currentElement = (XmlElement)currentNode; + + if (currentElement.LocalName == LOGGER_TAG) + { + this.ParseLogger(currentElement); + } + else if (currentElement.LocalName == CATEGORY_TAG) + { + // TODO: deprecated use of category + this.ParseLogger(currentElement); + } + else if (currentElement.LocalName == ROOT_TAG) + { + this.ParseRoot(currentElement); + } + else if (currentElement.LocalName == RENDERER_TAG) + { + this.ParseRenderer(currentElement); + } + else if (currentElement.LocalName == APPENDER_TAG) + { + // We ignore appenders in this pass. They will + // be found and loaded if they are referenced. + } + else + { + // Read the param tags and set properties on the hierarchy + this.SetParameter(currentElement, this.m_hierarchy); + } + } + } + + // Lastly set the hierarchy threshold + string thresholdStr = element.GetAttribute(THRESHOLD_ATTR); + LogLog.Debug(declaringType, "Hierarchy Threshold [" + thresholdStr + "]"); + if (thresholdStr.Length > 0 && thresholdStr != "null") + { + Level thresholdLevel = (Level)this.ConvertStringTo(typeof(Level), thresholdStr); + if (thresholdLevel != null) + { + this.m_hierarchy.Threshold = thresholdLevel; + } + else + { + LogLog.Warn(declaringType, "Unable to set hierarchy threshold using value [" + thresholdStr + "] (with acceptable conversion types)"); + } + } + + // Done reading config } - /// - /// Parse appenders by IDREF. - /// - /// The appender ref element. - /// The instance of the appender that the ref refers to. - /// - /// - /// Parse an XML element that represents an appender and return - /// the appender. - /// - /// - protected IAppender FindAppenderByReference(XmlElement appenderRef) - { - string appenderName = appenderRef.GetAttribute(REF_ATTR); - - IAppender appender = (IAppender)this.m_appenderBag[appenderName]; - if (appender != null) - { - return appender; - } - else - { - // Find the element with that id - XmlElement element = null; - - if (appenderName != null && appenderName.Length > 0) - { - foreach (XmlElement curAppenderElement in appenderRef.OwnerDocument.GetElementsByTagName(APPENDER_TAG)) - { - if (curAppenderElement.GetAttribute("name") == appenderName) - { - element = curAppenderElement; - break; - } - } - } - - if (element == null) - { - LogLog.Error(declaringType, "XmlHierarchyConfigurator: No appender named [" + appenderName + "] could be found."); - return null; - } - else - { - appender = this.ParseAppender(element); - if (appender != null) - { - this.m_appenderBag[appenderName] = appender; - } - - return appender; - } - } - } - - /// - /// Parses an appender element. - /// - /// The appender element. - /// The appender instance or null when parsing failed. - /// - /// - /// Parse an XML element that represents an appender and return - /// the appender instance. - /// - /// - protected IAppender ParseAppender(XmlElement appenderElement) - { - string appenderName = appenderElement.GetAttribute(NAME_ATTR); - string typeName = appenderElement.GetAttribute(TYPE_ATTR); - - LogLog.Debug(declaringType, "Loading Appender [" + appenderName + "] type: [" + typeName + "]"); - try - { -#if NETSTANDARD1_3 - IAppender appender = (IAppender)Activator.CreateInstance(SystemInfo.GetTypeFromString(this.GetType().GetTypeInfo().Assembly, typeName, true, true)); -#else - IAppender appender = (IAppender)Activator.CreateInstance(SystemInfo.GetTypeFromString(typeName, true, true)); -#endif - appender.Name = appenderName; - - foreach (XmlNode currentNode in appenderElement.ChildNodes) - { - /* We're only interested in Elements */ - if (currentNode.NodeType == XmlNodeType.Element) - { - XmlElement currentElement = (XmlElement)currentNode; - - // Look for the appender ref tag - if (currentElement.LocalName == APPENDER_REF_TAG) - { - string refName = currentElement.GetAttribute(REF_ATTR); - - IAppenderAttachable appenderContainer = appender as IAppenderAttachable; - if (appenderContainer != null) - { - LogLog.Debug(declaringType, "Attaching appender named [" + refName + "] to appender named [" + appender.Name + "]."); - - IAppender referencedAppender = this.FindAppenderByReference(currentElement); - if (referencedAppender != null) - { - appenderContainer.AddAppender(referencedAppender); - } - } - else - { - LogLog.Error(declaringType, "Requesting attachment of appender named [" + refName + "] to appender named [" + appender.Name + "] which does not implement log4net.Core.IAppenderAttachable."); - } - } - else - { - // For all other tags we use standard set param method - this.SetParameter(currentElement, appender); - } - } - } - - IOptionHandler optionHandler = appender as IOptionHandler; - if (optionHandler != null) - { - optionHandler.ActivateOptions(); - } - - LogLog.Debug(declaringType, "Created Appender [" + appenderName + "]"); - return appender; - } - catch (Exception ex) - { - // Yes, it's ugly. But all exceptions point to the same problem: we can't create an Appender - LogLog.Error(declaringType, "Could not create Appender [" + appenderName + "] of type [" + typeName + "]. Reported error follows.", ex); - return null; - } - } - - /// - /// Parses a logger element. - /// - /// The logger element. - /// - /// - /// Parse an XML element that represents a logger. - /// - /// - protected void ParseLogger(XmlElement loggerElement) - { - // Create a new log4net.Logger object from the element. - string loggerName = loggerElement.GetAttribute(NAME_ATTR); - - LogLog.Debug(declaringType, "Retrieving an instance of log4net.Repository.Logger for logger [" + loggerName + "]."); - Logger log = this.m_hierarchy.GetLogger(loggerName) as Logger; - - // Setting up a logger needs to be an atomic operation, in order - // to protect potential log operations while logger - // configuration is in progress. - lock (log) - { - bool additivity = OptionConverter.ToBoolean(loggerElement.GetAttribute(ADDITIVITY_ATTR), true); - - LogLog.Debug(declaringType, "Setting [" + log.Name + "] additivity to [" + additivity + "]."); - log.Additivity = additivity; - this.ParseChildrenOfLoggerElement(loggerElement, log, false); - } - } - - /// - /// Parses the root logger element. - /// - /// The root element. - /// - /// - /// Parse an XML element that represents the root logger. - /// - /// - protected void ParseRoot(XmlElement rootElement) - { - Logger root = this.m_hierarchy.Root; - - // logger configuration needs to be atomic - lock (root) - { - this.ParseChildrenOfLoggerElement(rootElement, root, true); - } - } - - /// - /// Parses the children of a logger element. - /// - /// The category element. - /// The logger instance. - /// Flag to indicate if the logger is the root logger. - /// - /// - /// Parse the child elements of a <logger> element. - /// - /// - protected void ParseChildrenOfLoggerElement(XmlElement catElement, Logger log, bool isRoot) - { - // Remove all existing appenders from log. They will be - // reconstructed if need be. - log.RemoveAllAppenders(); - - foreach (XmlNode currentNode in catElement.ChildNodes) - { - if (currentNode.NodeType == XmlNodeType.Element) - { - XmlElement currentElement = (XmlElement)currentNode; - - if (currentElement.LocalName == APPENDER_REF_TAG) - { - IAppender appender = this.FindAppenderByReference(currentElement); - string refName = currentElement.GetAttribute(REF_ATTR); - if (appender != null) - { - LogLog.Debug(declaringType, "Adding appender named [" + refName + "] to logger [" + log.Name + "]."); - log.AddAppender(appender); - } - else - { - LogLog.Error(declaringType, "Appender named [" + refName + "] not found."); - } - } - else if (currentElement.LocalName == LEVEL_TAG || currentElement.LocalName == PRIORITY_TAG) - { - this.ParseLevel(currentElement, log, isRoot); - } - else - { - this.SetParameter(currentElement, log); - } - } - } - - IOptionHandler optionHandler = log as IOptionHandler; - if (optionHandler != null) - { - optionHandler.ActivateOptions(); - } - } - - /// - /// Parses an object renderer. - /// - /// The renderer element. - /// - /// - /// Parse an XML element that represents a renderer. - /// - /// - protected void ParseRenderer(XmlElement element) - { - string renderingClassName = element.GetAttribute(RENDERING_TYPE_ATTR); - string renderedClassName = element.GetAttribute(RENDERED_TYPE_ATTR); - - LogLog.Debug(declaringType, "Rendering class [" + renderingClassName + "], Rendered class [" + renderedClassName + "]."); - IObjectRenderer renderer = (IObjectRenderer)OptionConverter.InstantiateByClassName(renderingClassName, typeof(IObjectRenderer), null); - if (renderer == null) - { - LogLog.Error(declaringType, "Could not instantiate renderer [" + renderingClassName + "]."); - return; - } - else - { - try - { -#if NETSTANDARD1_3 - m_hierarchy.RendererMap.Put(SystemInfo.GetTypeFromString(this.GetType().GetTypeInfo().Assembly, renderedClassName, true, true), renderer); -#else - this.m_hierarchy.RendererMap.Put(SystemInfo.GetTypeFromString(renderedClassName, true, true), renderer); -#endif - } - catch (Exception e) - { - LogLog.Error(declaringType, "Could not find class [" + renderedClassName + "].", e); - } - } - } - - /// - /// Parses a level element. - /// - /// The level element. - /// The logger object to set the level on. - /// Flag to indicate if the logger is the root logger. - /// - /// - /// Parse an XML element that represents a level. - /// - /// - protected void ParseLevel(XmlElement element, Logger log, bool isRoot) - { - string loggerName = log.Name; - if (isRoot) - { - loggerName = "root"; - } - - string levelStr = element.GetAttribute(VALUE_ATTR); - LogLog.Debug(declaringType, "Logger [" + loggerName + "] Level string is [" + levelStr + "]."); - - if (levelStr == INHERITED) - { - if (isRoot) - { - LogLog.Error(declaringType, "Root level cannot be inherited. Ignoring directive."); - } - else - { - LogLog.Debug(declaringType, "Logger [" + loggerName + "] level set to inherit from parent."); - log.Level = null; - } - } - else - { - log.Level = log.Hierarchy.LevelMap[levelStr]; - if (log.Level == null) - { - LogLog.Error(declaringType, "Undefined level [" + levelStr + "] on Logger [" + loggerName + "]."); - } - else - { - LogLog.Debug(declaringType, "Logger [" + loggerName + "] level set to [name=\"" + log.Level.Name + "\",value=" + log.Level.Value + "]."); - } - } - } - - /// - /// Sets a parameter on an object. - /// - /// The parameter element. - /// The object to set the parameter on. - /// - /// The parameter name must correspond to a writable property - /// on the object. The value of the parameter is a string, - /// therefore this function will attempt to set a string - /// property first. If unable to set a string property it - /// will inspect the property and its argument type. It will - /// attempt to call a static method called Parse on the - /// type of the property. This method will take a single - /// string argument and return a value that can be used to - /// set the property. - /// - protected void SetParameter(XmlElement element, object target) - { - // Get the property name - string name = element.GetAttribute(NAME_ATTR); - - // If the name attribute does not exist then use the name of the element - if (element.LocalName != PARAM_TAG || name == null || name.Length == 0) - { - name = element.LocalName; - } - - // Look for the property on the target object - Type targetType = target.GetType(); - Type propertyType = null; - - PropertyInfo propInfo = null; - MethodInfo methInfo = null; - - // Try to find a writable property - propInfo = targetType.GetProperty(name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.IgnoreCase); - if (propInfo != null && propInfo.CanWrite) - { - // found a property - propertyType = propInfo.PropertyType; - } - else - { - propInfo = null; - - // look for a method with the signature Add(type) - methInfo = this.FindMethodInfo(targetType, name); - - if (methInfo != null) - { - propertyType = methInfo.GetParameters()[0].ParameterType; - } - } - - if (propertyType == null) - { - LogLog.Error(declaringType, "XmlHierarchyConfigurator: Cannot find Property [" + name + "] to set object on [" + target.ToString() + "]"); - } - else - { - string propertyValue = null; - - if (element.GetAttributeNode(VALUE_ATTR) != null) - { - propertyValue = element.GetAttribute(VALUE_ATTR); - } - else if (element.HasChildNodes) - { - // Concatenate the CDATA and Text nodes together - foreach (XmlNode childNode in element.ChildNodes) - { - if (childNode.NodeType == XmlNodeType.CDATA || childNode.NodeType == XmlNodeType.Text) - { - if (propertyValue == null) - { - propertyValue = childNode.InnerText; - } - else - { - propertyValue += childNode.InnerText; - } - } - } - } - - if (propertyValue != null) - { -#if !(NETCF || NETSTANDARD1_3) // NETSTANDARD1_3: System.Runtime.InteropServices.RuntimeInformation not available on desktop 4.6 - try - { - // Expand environment variables in the string. - IDictionary environmentVariables = Environment.GetEnvironmentVariables(); - if (this.HasCaseInsensitiveEnvironment) + /// + /// Parse appenders by IDREF. + /// + /// The appender ref element. + /// The instance of the appender that the ref refers to. + /// + /// + /// Parse an XML element that represents an appender and return + /// the appender. + /// + /// + protected IAppender FindAppenderByReference(XmlElement appenderRef) + { + string appenderName = appenderRef.GetAttribute(REF_ATTR); + + IAppender appender = (IAppender)this.m_appenderBag[appenderName]; + if (appender != null) + { + return appender; + } + else + { + // Find the element with that id + XmlElement element = null; + + if (appenderName != null && appenderName.Length > 0) + { + foreach (XmlElement curAppenderElement in appenderRef.OwnerDocument.GetElementsByTagName(APPENDER_TAG)) + { + if (curAppenderElement.GetAttribute("name") == appenderName) { - environmentVariables = this.CreateCaseInsensitiveWrapper(environmentVariables); - } - - propertyValue = OptionConverter.SubstituteVariables(propertyValue, environmentVariables); - } - catch (System.Security.SecurityException) - { - // This security exception will occur if the caller does not have - // unrestricted environment permission. If this occurs the expansion - // will be skipped with the following warning message. - LogLog.Debug(declaringType, "Security exception while trying to expand environment variables. Error Ignored. No Expansion."); - } -#endif - - Type parsedObjectConversionTargetType = null; - - // Check if a specific subtype is specified on the element using the 'type' attribute - string subTypeString = element.GetAttribute(TYPE_ATTR); - if (subTypeString != null && subTypeString.Length > 0) - { - // Read the explicit subtype - try - { -#if NETSTANDARD1_3 - Type subType = SystemInfo.GetTypeFromString(this.GetType().GetTypeInfo().Assembly, subTypeString, true, true); -#else - Type subType = SystemInfo.GetTypeFromString(subTypeString, true, true); -#endif - - LogLog.Debug(declaringType, "Parameter [" + name + "] specified subtype [" + subType.FullName + "]"); - - if (!propertyType.IsAssignableFrom(subType)) - { - // Check if there is an appropriate type converter - if (OptionConverter.CanConvertTypeTo(subType, propertyType)) - { - // Must re-convert to the real property type - parsedObjectConversionTargetType = propertyType; - - // Use sub type as intermediary type - propertyType = subType; - } - else - { - LogLog.Error(declaringType, "subtype [" + subType.FullName + "] set on [" + name + "] is not a subclass of property type [" + propertyType.FullName + "] and there are no acceptable type conversions."); - } - } - else - { - // The subtype specified is found and is actually a subtype of the property - // type, therefore we can switch to using this type. - propertyType = subType; - } - } - catch (Exception ex) - { - LogLog.Error(declaringType, "Failed to find type [" + subTypeString + "] set on [" + name + "]", ex); - } - } - - // Now try to convert the string value to an acceptable type - // to pass to this property. - object convertedValue = this.ConvertStringTo(propertyType, propertyValue); - - // Check if we need to do an additional conversion - if (convertedValue != null && parsedObjectConversionTargetType != null) - { - LogLog.Debug(declaringType, "Performing additional conversion of value from [" + convertedValue.GetType().Name + "] to [" + parsedObjectConversionTargetType.Name + "]"); - convertedValue = OptionConverter.ConvertTypeTo(convertedValue, parsedObjectConversionTargetType); - } - - if (convertedValue != null) - { - if (propInfo != null) - { - // Got a converted result - LogLog.Debug(declaringType, "Setting Property [" + propInfo.Name + "] to " + convertedValue.GetType().Name + " value [" + convertedValue.ToString() + "]"); - - try - { - // Pass to the property -#if NETSTANDARD1_3 // TODO BindingFlags is available for netstandard1.5 - propInfo.SetValue(target, convertedValue, null); -#else - propInfo.SetValue(target, convertedValue, BindingFlags.SetProperty, null, null, CultureInfo.InvariantCulture); -#endif - } - catch (TargetInvocationException targetInvocationEx) - { - LogLog.Error(declaringType, "Failed to set parameter [" + propInfo.Name + "] on object [" + target + "] using value [" + convertedValue + "]", targetInvocationEx.InnerException); - } - } - else if (methInfo != null) - { - // Got a converted result - LogLog.Debug(declaringType, "Setting Collection Property [" + methInfo.Name + "] to " + convertedValue.GetType().Name + " value [" + convertedValue.ToString() + "]"); - - try - { - // Pass to the property -#if NETSTANDARD1_3 // TODO BindingFlags is available for netstandard1.5 - methInfo.Invoke(target, new[] { convertedValue }); -#else - methInfo.Invoke(target, BindingFlags.InvokeMethod, null, new object[] { convertedValue }, CultureInfo.InvariantCulture); -#endif - } - catch (TargetInvocationException targetInvocationEx) - { - LogLog.Error(declaringType, "Failed to set parameter [" + name + "] on object [" + target + "] using value [" + convertedValue + "]", targetInvocationEx.InnerException); - } - } - } - else - { - LogLog.Warn(declaringType, "Unable to set property [" + name + "] on object [" + target + "] using value [" + propertyValue + "] (with acceptable conversion types)"); - } - } - else - { - object createdObject = null; - - if (propertyType == typeof(string) && !this.HasAttributesOrElements(element)) - { - // If the property is a string and the element is empty (no attributes - // or child elements) then we special case the object value to an empty string. - // This is necessary because while the String is a class it does not have - // a default constructor that creates an empty string, which is the behavior - // we are trying to simulate and would be expected from CreateObjectFromXml - createdObject = string.Empty; - } - else - { - // No value specified - Type defaultObjectType = null; - if (IsTypeConstructible(propertyType)) - { - defaultObjectType = propertyType; - } - - createdObject = this.CreateObjectFromXml(element, defaultObjectType, propertyType); - } - - if (createdObject == null) - { - LogLog.Error(declaringType, "Failed to create object to set param: " + name); - } - else - { - if (propInfo != null) - { - // Got a converted result - LogLog.Debug(declaringType, "Setting Property [" + propInfo.Name + "] to object [" + createdObject + "]"); - - try - { - // Pass to the property -#if NETSTANDARD1_3 // TODO BindingFlags is available for netstandard1.5 - propInfo.SetValue(target, createdObject, null); -#else - propInfo.SetValue(target, createdObject, BindingFlags.SetProperty, null, null, CultureInfo.InvariantCulture); -#endif - } - catch (TargetInvocationException targetInvocationEx) - { - LogLog.Error(declaringType, "Failed to set parameter [" + propInfo.Name + "] on object [" + target + "] using value [" + createdObject + "]", targetInvocationEx.InnerException); - } - } - else if (methInfo != null) - { - // Got a converted result - LogLog.Debug(declaringType, "Setting Collection Property [" + methInfo.Name + "] to object [" + createdObject + "]"); - - try - { - // Pass to the property -#if NETSTANDARD1_3 // TODO BindingFlags is available for netstandard1.5 - methInfo.Invoke(target, new[] { createdObject }); -#else - methInfo.Invoke(target, BindingFlags.InvokeMethod, null, new object[] { createdObject }, CultureInfo.InvariantCulture); -#endif - } - catch (TargetInvocationException targetInvocationEx) - { - LogLog.Error(declaringType, "Failed to set parameter [" + methInfo.Name + "] on object [" + target + "] using value [" + createdObject + "]", targetInvocationEx.InnerException); - } - } - } - } - } - } - - /// - /// Test if an element has no attributes or child elements. - /// - /// the element to inspect. - /// true if the element has any attributes or child elements, false otherwise. - private bool HasAttributesOrElements(XmlElement element) - { - foreach (XmlNode node in element.ChildNodes) - { - if (node.NodeType == XmlNodeType.Attribute || node.NodeType == XmlNodeType.Element) - { - return true; - } - } - - return false; - } - - /// - /// Test if a is constructible with Activator.CreateInstance. - /// - /// the type to inspect. - /// true if the type is creatable using a default constructor, false otherwise. - private static bool IsTypeConstructible(Type type) - { -#if NETSTANDARD1_3 - TypeInfo typeInfo = type.GetTypeInfo(); - if (typeInfo.IsClass && !typeInfo.IsAbstract) -#else - if (type.IsClass && !type.IsAbstract) -#endif - { - ConstructorInfo defaultConstructor = type.GetConstructor(new Type[0]); - if (defaultConstructor != null && !defaultConstructor.IsAbstract && !defaultConstructor.IsPrivate) - { - return true; - } - } - - return false; - } - - /// - /// Look for a method on the that matches the supplied. - /// - /// the type that has the method. - /// the name of the method. - /// the method info found. - /// - /// - /// The method must be a public instance method on the . - /// The method must be named or "Add" followed by . - /// The method must take a single parameter. - /// - /// - private MethodInfo FindMethodInfo(Type targetType, string name) - { - string requiredMethodNameA = name; - string requiredMethodNameB = "Add" + name; - - MethodInfo[] methods = targetType.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); - - foreach (MethodInfo methInfo in methods) - { - if (!methInfo.IsStatic) - { - string methodInfoName = methInfo.Name; - - if (SystemInfo.EqualsIgnoringCase(methodInfoName, requiredMethodNameA) || - SystemInfo.EqualsIgnoringCase(methodInfoName, requiredMethodNameB)) - { - // Found matching method name - - // Look for version with one arg only - System.Reflection.ParameterInfo[] methParams = methInfo.GetParameters(); - if (methParams.Length == 1) - { - return methInfo; - } - } - } - } - - return null; - } - - /// - /// Converts a string value to a target type. - /// - /// The type of object to convert the string to. - /// The string value to use as the value of the object. - /// - /// - /// An object of type with value or - /// null when the conversion could not be performed. - /// - /// - protected object ConvertStringTo(Type type, string value) - { - // Hack to allow use of Level in property - if (typeof(Level) == type) - { - // Property wants a level - Level levelValue = this.m_hierarchy.LevelMap[value]; - - if (levelValue == null) - { - LogLog.Error(declaringType, "XmlHierarchyConfigurator: Unknown Level Specified [" + value + "]"); - } - - return levelValue; - } - - return OptionConverter.ConvertStringTo(type, value); - } - - /// - /// Creates an object as specified in XML. - /// - /// The XML element that contains the definition of the object. - /// The object type to use if not explicitly specified. - /// The type that the returned object must be or must inherit from. - /// The object or null. - /// - /// - /// Parse an XML element and create an object instance based on the configuration - /// data. - /// - /// - /// The type of the instance may be specified in the XML. If not - /// specified then the is used - /// as the type. However the type is specified it must support the - /// type. - /// - /// - protected object CreateObjectFromXml(XmlElement element, Type defaultTargetType, Type typeConstraint) - { - Type objectType = null; - - // Get the object type - string objectTypeString = element.GetAttribute(TYPE_ATTR); - if (objectTypeString == null || objectTypeString.Length == 0) - { - if (defaultTargetType == null) - { - LogLog.Error(declaringType, "Object type not specified. Cannot create object of type [" + typeConstraint.FullName + "]. Missing Value or Type."); - return null; - } - else - { - // Use the default object type - objectType = defaultTargetType; - } - } - else - { - // Read the explicit object type - try - { -#if NETSTANDARD1_3 - objectType = SystemInfo.GetTypeFromString(this.GetType().GetTypeInfo().Assembly, objectTypeString, true, true); -#else - objectType = SystemInfo.GetTypeFromString(objectTypeString, true, true); -#endif - } - catch (Exception ex) - { - LogLog.Error(declaringType, "Failed to find type [" + objectTypeString + "]", ex); - return null; - } - } - - bool requiresConversion = false; - - // Got the object type. Check that it meets the typeConstraint - if (typeConstraint != null) - { - if (!typeConstraint.IsAssignableFrom(objectType)) - { - // Check if there is an appropriate type converter - if (OptionConverter.CanConvertTypeTo(objectType, typeConstraint)) - { - requiresConversion = true; - } - else - { - LogLog.Error(declaringType, "Object type [" + objectType.FullName + "] is not assignable to type [" + typeConstraint.FullName + "]. There are no acceptable type conversions."); - return null; - } - } - } - - // Create using the default constructor - object createdObject = null; - try - { - createdObject = Activator.CreateInstance(objectType); - } - catch (Exception createInstanceEx) - { - LogLog.Error(declaringType, "XmlHierarchyConfigurator: Failed to construct object of type [" + objectType.FullName + "] Exception: " + createInstanceEx.ToString()); - } - - // Set any params on object - foreach (XmlNode currentNode in element.ChildNodes) - { - if (currentNode.NodeType == XmlNodeType.Element) - { - this.SetParameter((XmlElement)currentNode, createdObject); - } - } - - // Check if we need to call ActivateOptions - IOptionHandler optionHandler = createdObject as IOptionHandler; - if (optionHandler != null) - { - optionHandler.ActivateOptions(); - } - - // Ok object should be initialized - if (requiresConversion) - { - // Convert the object type - return OptionConverter.ConvertTypeTo(createdObject, typeConstraint); - } - else - { - // The object is of the correct type - return createdObject; - } + element = curAppenderElement; + break; + } + } + } + + if (element == null) + { + LogLog.Error(declaringType, "XmlHierarchyConfigurator: No appender named [" + appenderName + "] could be found."); + return null; + } + else + { + appender = this.ParseAppender(element); + if (appender != null) + { + this.m_appenderBag[appenderName] = appender; + } + return appender; + } + } } -#if !(NETCF || NETSTANDARD1_3) // NETSTANDARD1_3: System.Runtime.InteropServices.RuntimeInformation not available on desktop 4.6 - private bool HasCaseInsensitiveEnvironment - { - get + /// + /// Parses an appender element. + /// + /// The appender element. + /// The appender instance or null when parsing failed. + /// + /// + /// Parse an XML element that represents an appender and return + /// the appender instance. + /// + /// + protected IAppender ParseAppender(XmlElement appenderElement) + { + string appenderName = appenderElement.GetAttribute(NAME_ATTR); + string typeName = appenderElement.GetAttribute(TYPE_ATTR); + + LogLog.Debug(declaringType, "Loading Appender [" + appenderName + "] type: [" + typeName + "]"); + try + { +#if NETSTANDARD1_3 + IAppender appender = (IAppender)Activator.CreateInstance(SystemInfo.GetTypeFromString(this.GetType().GetTypeInfo().Assembly, typeName, true, true)); +#else + IAppender appender = (IAppender)Activator.CreateInstance(SystemInfo.GetTypeFromString(typeName, true, true)); +#endif + appender.Name = appenderName; + + foreach (XmlNode currentNode in appenderElement.ChildNodes) + { + /* We're only interested in Elements */ + if (currentNode.NodeType == XmlNodeType.Element) + { + XmlElement currentElement = (XmlElement)currentNode; + + // Look for the appender ref tag + if (currentElement.LocalName == APPENDER_REF_TAG) + { + string refName = currentElement.GetAttribute(REF_ATTR); + + IAppenderAttachable appenderContainer = appender as IAppenderAttachable; + if (appenderContainer != null) + { + LogLog.Debug(declaringType, "Attaching appender named [" + refName + "] to appender named [" + appender.Name + "]."); + + IAppender referencedAppender = this.FindAppenderByReference(currentElement); + if (referencedAppender != null) + { + appenderContainer.AddAppender(referencedAppender); + } + } + else + { + LogLog.Error(declaringType, "Requesting attachment of appender named [" + refName + "] to appender named [" + appender.Name + "] which does not implement log4net.Core.IAppenderAttachable."); + } + } + else + { + // For all other tags we use standard set param method + this.SetParameter(currentElement, appender); + } + } + } + + IOptionHandler optionHandler = appender as IOptionHandler; + if (optionHandler != null) + { + optionHandler.ActivateOptions(); + } + + LogLog.Debug(declaringType, "Created Appender [" + appenderName + "]"); + return appender; + } + catch (Exception ex) + { + // Yes, it's ugly. But all exceptions point to the same problem: we can't create an Appender + + LogLog.Error(declaringType, "Could not create Appender [" + appenderName + "] of type [" + typeName + "]. Reported error follows.", ex); + return null; + } + } + + /// + /// Parses a logger element. + /// + /// The logger element. + /// + /// + /// Parse an XML element that represents a logger. + /// + /// + protected void ParseLogger(XmlElement loggerElement) + { + // Create a new log4net.Logger object from the element. + string loggerName = loggerElement.GetAttribute(NAME_ATTR); + + LogLog.Debug(declaringType, "Retrieving an instance of log4net.Repository.Logger for logger [" + loggerName + "]."); + Logger log = this.m_hierarchy.GetLogger(loggerName) as Logger; + + // Setting up a logger needs to be an atomic operation, in order + // to protect potential log operations while logger + // configuration is in progress. + lock(log) + { + bool additivity = OptionConverter.ToBoolean(loggerElement.GetAttribute(ADDITIVITY_ATTR), true); + + LogLog.Debug(declaringType, "Setting [" + log.Name + "] additivity to [" + additivity + "]."); + log.Additivity = additivity; + this.ParseChildrenOfLoggerElement(loggerElement, log, false); + } + } + + /// + /// Parses the root logger element. + /// + /// The root element. + /// + /// + /// Parse an XML element that represents the root logger. + /// + /// + protected void ParseRoot(XmlElement rootElement) + { + Logger root = this.m_hierarchy.Root; + // logger configuration needs to be atomic + lock(root) + { + this.ParseChildrenOfLoggerElement(rootElement, root, true); + } + } + + /// + /// Parses the children of a logger element. + /// + /// The category element. + /// The logger instance. + /// Flag to indicate if the logger is the root logger. + /// + /// + /// Parse the child elements of a <logger> element. + /// + /// + protected void ParseChildrenOfLoggerElement(XmlElement catElement, Logger log, bool isRoot) + { + // Remove all existing appenders from log. They will be + // reconstructed if need be. + log.RemoveAllAppenders(); + + foreach (XmlNode currentNode in catElement.ChildNodes) + { + if (currentNode.NodeType == XmlNodeType.Element) + { + XmlElement currentElement = (XmlElement) currentNode; + + if (currentElement.LocalName == APPENDER_REF_TAG) + { + IAppender appender = this.FindAppenderByReference(currentElement); + string refName = currentElement.GetAttribute(REF_ATTR); + if (appender != null) + { + LogLog.Debug(declaringType, "Adding appender named [" + refName + "] to logger [" + log.Name + "]."); + log.AddAppender(appender); + } + else + { + LogLog.Error(declaringType, "Appender named [" + refName + "] not found."); + } + } + else if (currentElement.LocalName == LEVEL_TAG || currentElement.LocalName == PRIORITY_TAG) + { + this.ParseLevel(currentElement, log, isRoot); + } + else + { + this.SetParameter(currentElement, log); + } + } + } + + IOptionHandler optionHandler = log as IOptionHandler; + if (optionHandler != null) { -#if NET_1_0 || NET_1_1 || CLI_1_0 - // actually there is no guarantee, but we don't know better - return true; -#elif MONO_1_0 - // see above - return false; -#else - PlatformID platform = Environment.OSVersion.Platform; - return platform != PlatformID.Unix && platform != PlatformID.MacOSX; -#endif - } - } - - private IDictionary CreateCaseInsensitiveWrapper(IDictionary dict) - { - if (dict == null) + optionHandler.ActivateOptions(); + } + } + + /// + /// Parses an object renderer. + /// + /// The renderer element. + /// + /// + /// Parse an XML element that represents a renderer. + /// + /// + protected void ParseRenderer(XmlElement element) + { + string renderingClassName = element.GetAttribute(RENDERING_TYPE_ATTR); + string renderedClassName = element.GetAttribute(RENDERED_TYPE_ATTR); + + LogLog.Debug(declaringType, "Rendering class [" + renderingClassName + "], Rendered class [" + renderedClassName + "]."); + IObjectRenderer renderer = (IObjectRenderer)OptionConverter.InstantiateByClassName(renderingClassName, typeof(IObjectRenderer), null); + if (renderer == null) + { + LogLog.Error(declaringType, "Could not instantiate renderer [" + renderingClassName + "]."); + return; + } + else { - return dict; - } + try + { +#if NETSTANDARD1_3 + m_hierarchy.RendererMap.Put(SystemInfo.GetTypeFromString(this.GetType().GetTypeInfo().Assembly, renderedClassName, true, true), renderer); +#else + this.m_hierarchy.RendererMap.Put(SystemInfo.GetTypeFromString(renderedClassName, true, true), renderer); +#endif + } + catch(Exception e) + { + LogLog.Error(declaringType, "Could not find class [" + renderedClassName + "].", e); + } + } + } - Hashtable hash = SystemInfo.CreateCaseInsensitiveHashtable(); - foreach (DictionaryEntry entry in dict) + /// + /// Parses a level element. + /// + /// The level element. + /// The logger object to set the level on. + /// Flag to indicate if the logger is the root logger. + /// + /// + /// Parse an XML element that represents a level. + /// + /// + protected void ParseLevel(XmlElement element, Logger log, bool isRoot) + { + string loggerName = log.Name; + if (isRoot) { - hash[entry.Key] = entry.Value; - } + loggerName = "root"; + } - return hash; + string levelStr = element.GetAttribute(VALUE_ATTR); + LogLog.Debug(declaringType, "Logger [" + loggerName + "] Level string is [" + levelStr + "]."); + + if (INHERITED == levelStr) + { + if (isRoot) + { + LogLog.Error(declaringType, "Root level cannot be inherited. Ignoring directive."); + } + else + { + LogLog.Debug(declaringType, "Logger [" + loggerName + "] level set to inherit from parent."); + log.Level = null; + } + } + else + { + log.Level = log.Hierarchy.LevelMap[levelStr]; + if (log.Level == null) + { + LogLog.Error(declaringType, "Undefined level [" + levelStr + "] on Logger [" + loggerName + "]."); + } + else + { + LogLog.Debug(declaringType, "Logger [" + loggerName + "] level set to [name=\"" + log.Level.Name + "\",value=" + log.Level.Value + "]."); + } + } } -#endif + + /// + /// Sets a parameter on an object. + /// + /// The parameter element. + /// The object to set the parameter on. + /// + /// The parameter name must correspond to a writable property + /// on the object. The value of the parameter is a string, + /// therefore this function will attempt to set a string + /// property first. If unable to set a string property it + /// will inspect the property and its argument type. It will + /// attempt to call a static method called Parse on the + /// type of the property. This method will take a single + /// string argument and return a value that can be used to + /// set the property. + /// + protected void SetParameter(XmlElement element, object target) + { + // Get the property name + string name = element.GetAttribute(NAME_ATTR); + + // If the name attribute does not exist then use the name of the element + if (element.LocalName != PARAM_TAG || name == null || name.Length == 0) + { + name = element.LocalName; + } + + // Look for the property on the target object + Type targetType = target.GetType(); + Type propertyType = null; + + PropertyInfo propInfo = null; + MethodInfo methInfo = null; + + // Try to find a writable property + propInfo = targetType.GetProperty(name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.IgnoreCase); + if (propInfo != null && propInfo.CanWrite) + { + // found a property + propertyType = propInfo.PropertyType; + } + else + { + propInfo = null; + + // look for a method with the signature Add(type) + methInfo = this.FindMethodInfo(targetType, name); + + if (methInfo != null) + { + propertyType = methInfo.GetParameters()[0].ParameterType; + } + } + + if (propertyType == null) + { + LogLog.Error(declaringType, "XmlHierarchyConfigurator: Cannot find Property [" + name + "] to set object on [" + target.ToString() + "]"); + } + else + { + string propertyValue = null; + + if (element.GetAttributeNode(VALUE_ATTR) != null) + { + propertyValue = element.GetAttribute(VALUE_ATTR); + } + else if (element.HasChildNodes) + { + // Concatenate the CDATA and Text nodes together + foreach(XmlNode childNode in element.ChildNodes) + { + if (childNode.NodeType == XmlNodeType.CDATA || childNode.NodeType == XmlNodeType.Text) + { + if (propertyValue == null) + { + propertyValue = childNode.InnerText; + } + else + { + propertyValue += childNode.InnerText; + } + } + } + } + + if(propertyValue != null) + { +#if !NETCF && !NETSTANDARD1_3 // NETSTANDARD1_3: System.Runtime.InteropServices.RuntimeInformation not available on desktop 4.6 + try + { + // Expand environment variables in the string. + IDictionary environmentVariables = Environment.GetEnvironmentVariables(); + if (this.HasCaseInsensitiveEnvironment) + { + environmentVariables = this.CreateCaseInsensitiveWrapper(environmentVariables); + } + propertyValue = OptionConverter.SubstituteVariables(propertyValue, environmentVariables); + } + catch(System.Security.SecurityException) + { + // This security exception will occur if the caller does not have + // unrestricted environment permission. If this occurs the expansion + // will be skipped with the following warning message. + LogLog.Debug(declaringType, "Security exception while trying to expand environment variables. Error Ignored. No Expansion."); + } +#endif + + Type parsedObjectConversionTargetType = null; + + // Check if a specific subtype is specified on the element using the 'type' attribute + string subTypeString = element.GetAttribute(TYPE_ATTR); + if (subTypeString != null && subTypeString.Length > 0) + { + // Read the explicit subtype + try + { +#if NETSTANDARD1_3 + Type subType = SystemInfo.GetTypeFromString(this.GetType().GetTypeInfo().Assembly, subTypeString, true, true); +#else + Type subType = SystemInfo.GetTypeFromString(subTypeString, true, true); +#endif + + LogLog.Debug(declaringType, "Parameter [" + name + "] specified subtype [" + subType.FullName + "]"); + + if (!propertyType.IsAssignableFrom(subType)) + { + // Check if there is an appropriate type converter + if (OptionConverter.CanConvertTypeTo(subType, propertyType)) + { + // Must re-convert to the real property type + parsedObjectConversionTargetType = propertyType; + + // Use sub type as intermediary type + propertyType = subType; + } + else + { + LogLog.Error(declaringType, "subtype [" + subType.FullName + "] set on [" + name + "] is not a subclass of property type [" + propertyType.FullName + "] and there are no acceptable type conversions."); + } + } + else + { + // The subtype specified is found and is actually a subtype of the property + // type, therefore we can switch to using this type. + propertyType = subType; + } + } + catch(Exception ex) + { + LogLog.Error(declaringType, "Failed to find type [" + subTypeString + "] set on [" + name + "]", ex); + } + } + + // Now try to convert the string value to an acceptable type + // to pass to this property. + + object convertedValue = this.ConvertStringTo(propertyType, propertyValue); + + // Check if we need to do an additional conversion + if (convertedValue != null && parsedObjectConversionTargetType != null) + { + LogLog.Debug(declaringType, "Performing additional conversion of value from [" + convertedValue.GetType().Name + "] to [" + parsedObjectConversionTargetType.Name + "]"); + convertedValue = OptionConverter.ConvertTypeTo(convertedValue, parsedObjectConversionTargetType); + } + + if (convertedValue != null) + { + if (propInfo != null) + { + // Got a converted result + LogLog.Debug(declaringType, "Setting Property [" + propInfo.Name + "] to " + convertedValue.GetType().Name + " value [" + convertedValue.ToString() + "]"); + + try + { + // Pass to the property +#if NETSTANDARD1_3 // TODO BindingFlags is available for netstandard1.5 + propInfo.SetValue(target, convertedValue, null); +#else + propInfo.SetValue(target, convertedValue, BindingFlags.SetProperty, null, null, CultureInfo.InvariantCulture); +#endif + } + catch(TargetInvocationException targetInvocationEx) + { + LogLog.Error(declaringType, "Failed to set parameter [" + propInfo.Name + "] on object [" + target + "] using value [" + convertedValue + "]", targetInvocationEx.InnerException); + } + } + else if (methInfo != null) + { + // Got a converted result + LogLog.Debug(declaringType, "Setting Collection Property [" + methInfo.Name + "] to " + convertedValue.GetType().Name + " value [" + convertedValue.ToString() + "]"); + + try + { + // Pass to the property +#if NETSTANDARD1_3 // TODO BindingFlags is available for netstandard1.5 + methInfo.Invoke(target, new[] { convertedValue }); +#else + methInfo.Invoke(target, BindingFlags.InvokeMethod, null, new object[] { convertedValue }, CultureInfo.InvariantCulture); +#endif + } + catch(TargetInvocationException targetInvocationEx) + { + LogLog.Error(declaringType, "Failed to set parameter [" + name + "] on object [" + target + "] using value [" + convertedValue + "]", targetInvocationEx.InnerException); + } + } + } + else + { + LogLog.Warn(declaringType, "Unable to set property [" + name + "] on object [" + target + "] using value [" + propertyValue + "] (with acceptable conversion types)"); + } + } + else + { + object createdObject = null; + + if (propertyType == typeof(string) && !this.HasAttributesOrElements(element)) + { + // If the property is a string and the element is empty (no attributes + // or child elements) then we special case the object value to an empty string. + // This is necessary because while the String is a class it does not have + // a default constructor that creates an empty string, which is the behavior + // we are trying to simulate and would be expected from CreateObjectFromXml + createdObject = string.Empty; + } + else + { + // No value specified + Type defaultObjectType = null; + if (IsTypeConstructible(propertyType)) + { + defaultObjectType = propertyType; + } + + createdObject = this.CreateObjectFromXml(element, defaultObjectType, propertyType); + } + + if (createdObject == null) + { + LogLog.Error(declaringType, "Failed to create object to set param: " + name); + } + else + { + if (propInfo != null) + { + // Got a converted result + LogLog.Debug(declaringType, "Setting Property [" + propInfo.Name + "] to object [" + createdObject + "]"); + + try + { + // Pass to the property +#if NETSTANDARD1_3 // TODO BindingFlags is available for netstandard1.5 + propInfo.SetValue(target, createdObject, null); +#else + propInfo.SetValue(target, createdObject, BindingFlags.SetProperty, null, null, CultureInfo.InvariantCulture); +#endif + } + catch(TargetInvocationException targetInvocationEx) + { + LogLog.Error(declaringType, "Failed to set parameter [" + propInfo.Name + "] on object [" + target + "] using value [" + createdObject + "]", targetInvocationEx.InnerException); + } + } + else if (methInfo != null) + { + // Got a converted result + LogLog.Debug(declaringType, "Setting Collection Property [" + methInfo.Name + "] to object [" + createdObject + "]"); + + try + { + // Pass to the property +#if NETSTANDARD1_3 // TODO BindingFlags is available for netstandard1.5 + methInfo.Invoke(target, new[] { createdObject }); +#else + methInfo.Invoke(target, BindingFlags.InvokeMethod, null, new object[] {createdObject}, CultureInfo.InvariantCulture); +#endif + } + catch(TargetInvocationException targetInvocationEx) + { + LogLog.Error(declaringType, "Failed to set parameter [" + methInfo.Name + "] on object [" + target + "] using value [" + createdObject + "]", targetInvocationEx.InnerException); + } + } + } + } + } + } + + /// + /// Test if an element has no attributes or child elements + /// + /// the element to inspect + /// true if the element has any attributes or child elements, false otherwise + private bool HasAttributesOrElements(XmlElement element) + { + foreach(XmlNode node in element.ChildNodes) + { + if (node.NodeType == XmlNodeType.Attribute || node.NodeType == XmlNodeType.Element) + { + return true; + } + } + return false; + } + + /// + /// Test if a is constructible with Activator.CreateInstance. + /// + /// the type to inspect + /// true if the type is creatable using a default constructor, false otherwise + private static bool IsTypeConstructible(Type type) + { +#if NETSTANDARD1_3 + TypeInfo typeInfo = type.GetTypeInfo(); + if (typeInfo.IsClass && !typeInfo.IsAbstract) +#else + if (type.IsClass && !type.IsAbstract) +#endif + { + ConstructorInfo defaultConstructor = type.GetConstructor(new Type[0]); + if (defaultConstructor != null && !defaultConstructor.IsAbstract && !defaultConstructor.IsPrivate) + { + return true; + } + } + return false; + } + + /// + /// Look for a method on the that matches the supplied + /// + /// the type that has the method + /// the name of the method + /// the method info found + /// + /// + /// The method must be a public instance method on the . + /// The method must be named or "Add" followed by . + /// The method must take a single parameter. + /// + /// + private MethodInfo FindMethodInfo(Type targetType, string name) + { + string requiredMethodNameA = name; + string requiredMethodNameB = "Add" + name; + + MethodInfo[] methods = targetType.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); + + foreach(MethodInfo methInfo in methods) + { + if (!methInfo.IsStatic) + { + string methodInfoName = methInfo.Name; + + if (SystemInfo.EqualsIgnoringCase(methodInfoName, requiredMethodNameA) || + SystemInfo.EqualsIgnoringCase(methodInfoName, requiredMethodNameB)) + { + // Found matching method name + + // Look for version with one arg only + ParameterInfo[] methParams = methInfo.GetParameters(); + if (methParams.Length == 1) + { + return methInfo; + } + } + } + } + return null; + } + + /// + /// Converts a string value to a target type. + /// + /// The type of object to convert the string to. + /// The string value to use as the value of the object. + /// + /// + /// An object of type with value or + /// null when the conversion could not be performed. + /// + /// + protected object ConvertStringTo(Type type, string value) + { + // Hack to allow use of Level in property + if (typeof(Level) == type) + { + // Property wants a level + Level levelValue = this.m_hierarchy.LevelMap[value]; + + if (levelValue == null) + { + LogLog.Error(declaringType, "XmlHierarchyConfigurator: Unknown Level Specified [" + value + "]"); + } + + return levelValue; + } + return OptionConverter.ConvertStringTo(type, value); + } + + /// + /// Creates an object as specified in XML. + /// + /// The XML element that contains the definition of the object. + /// The object type to use if not explicitly specified. + /// The type that the returned object must be or must inherit from. + /// The object or null + /// + /// + /// Parse an XML element and create an object instance based on the configuration + /// data. + /// + /// + /// The type of the instance may be specified in the XML. If not + /// specified then the is used + /// as the type. However the type is specified it must support the + /// type. + /// + /// + protected object CreateObjectFromXml(XmlElement element, Type defaultTargetType, Type typeConstraint) + { + Type objectType = null; + + // Get the object type + string objectTypeString = element.GetAttribute(TYPE_ATTR); + if (objectTypeString == null || objectTypeString.Length == 0) + { + if (defaultTargetType == null) + { + LogLog.Error(declaringType, "Object type not specified. Cannot create object of type [" + typeConstraint.FullName + "]. Missing Value or Type."); + return null; + } + else + { + // Use the default object type + objectType = defaultTargetType; + } + } + else + { + // Read the explicit object type + try + { +#if NETSTANDARD1_3 + objectType = SystemInfo.GetTypeFromString(this.GetType().GetTypeInfo().Assembly, objectTypeString, true, true); +#else + objectType = SystemInfo.GetTypeFromString(objectTypeString, true, true); +#endif + } + catch(Exception ex) + { + LogLog.Error(declaringType, "Failed to find type [" + objectTypeString + "]", ex); + return null; + } + } + + bool requiresConversion = false; + + // Got the object type. Check that it meets the typeConstraint + if (typeConstraint != null) + { + if (!typeConstraint.IsAssignableFrom(objectType)) + { + // Check if there is an appropriate type converter + if (OptionConverter.CanConvertTypeTo(objectType, typeConstraint)) + { + requiresConversion = true; + } + else + { + LogLog.Error(declaringType, "Object type [" + objectType.FullName + "] is not assignable to type [" + typeConstraint.FullName + "]. There are no acceptable type conversions."); + return null; + } + } + } + + // Create using the default constructor + object createdObject = null; + try + { + createdObject = Activator.CreateInstance(objectType); + } + catch(Exception createInstanceEx) + { + LogLog.Error(declaringType, "XmlHierarchyConfigurator: Failed to construct object of type [" + objectType.FullName + "] Exception: " + createInstanceEx.ToString()); + } + + // Set any params on object + foreach (XmlNode currentNode in element.ChildNodes) + { + if (currentNode.NodeType == XmlNodeType.Element) + { + this.SetParameter((XmlElement)currentNode, createdObject); + } + } + + // Check if we need to call ActivateOptions + IOptionHandler optionHandler = createdObject as IOptionHandler; + if (optionHandler != null) + { + optionHandler.ActivateOptions(); + } + + // Ok object should be initialized + + if (requiresConversion) + { + // Convert the object type + return OptionConverter.ConvertTypeTo(createdObject, typeConstraint); + } + else + { + // The object is of the correct type + return createdObject; + } + } + +#if !NETCF && !NETSTANDARD1_3 // NETSTANDARD1_3: System.Runtime.InteropServices.RuntimeInformation not available on desktop 4.6 + private bool HasCaseInsensitiveEnvironment + { + get + { +#if NET_1_0 || NET_1_1 || CLI_1_0 + // actually there is no guarantee, but we don't know better + return true; +#elif MONO_1_0 + // see above + return false; +#else + PlatformID platform = Environment.OSVersion.Platform; + return platform != PlatformID.Unix && platform != PlatformID.MacOSX; +#endif + } + } + + private IDictionary CreateCaseInsensitiveWrapper(IDictionary dict) + { + if (dict == null) + { + return dict; + } + Hashtable hash = SystemInfo.CreateCaseInsensitiveHashtable(); + foreach (DictionaryEntry entry in dict) { + hash[entry.Key] = entry.Value; + } + return hash; + } +#endif // String constants used while parsing the XML data - private const string CONFIGURATION_TAG = "log4net"; - private const string RENDERER_TAG = "renderer"; - private const string APPENDER_TAG = "appender"; - private const string APPENDER_REF_TAG = "appender-ref"; - private const string PARAM_TAG = "param"; - - // TODO: Deprecate use of category tags - private const string CATEGORY_TAG = "category"; - - // TODO: Deprecate use of priority tag - private const string PRIORITY_TAG = "priority"; - - private const string LOGGER_TAG = "logger"; - private const string NAME_ATTR = "name"; - private const string TYPE_ATTR = "type"; - private const string VALUE_ATTR = "value"; - private const string ROOT_TAG = "root"; - private const string LEVEL_TAG = "level"; - private const string REF_ATTR = "ref"; - private const string ADDITIVITY_ATTR = "additivity"; - private const string THRESHOLD_ATTR = "threshold"; - private const string CONFIG_DEBUG_ATTR = "configDebug"; - private const string INTERNAL_DEBUG_ATTR = "debug"; - private const string EMIT_INTERNAL_DEBUG_ATTR = "emitDebug"; - private const string CONFIG_UPDATE_MODE_ATTR = "update"; - private const string RENDERING_TYPE_ATTR = "renderingClass"; - private const string RENDERED_TYPE_ATTR = "renderedClass"; - - // flag used on the level element + private const string CONFIGURATION_TAG = "log4net"; + private const string RENDERER_TAG = "renderer"; + private const string APPENDER_TAG = "appender"; + private const string APPENDER_REF_TAG = "appender-ref"; + private const string PARAM_TAG = "param"; + + // TODO: Deprecate use of category tags + private const string CATEGORY_TAG = "category"; + // TODO: Deprecate use of priority tag + private const string PRIORITY_TAG = "priority"; + + private const string LOGGER_TAG = "logger"; + private const string NAME_ATTR = "name"; + private const string TYPE_ATTR = "type"; + private const string VALUE_ATTR = "value"; + private const string ROOT_TAG = "root"; + private const string LEVEL_TAG = "level"; + private const string REF_ATTR = "ref"; + private const string ADDITIVITY_ATTR = "additivity"; + private const string THRESHOLD_ATTR = "threshold"; + private const string CONFIG_DEBUG_ATTR = "configDebug"; + private const string INTERNAL_DEBUG_ATTR = "debug"; + private const string EMIT_INTERNAL_DEBUG_ATTR = "emitDebug"; + private const string CONFIG_UPDATE_MODE_ATTR = "update"; + private const string RENDERING_TYPE_ATTR = "renderingClass"; + private const string RENDERED_TYPE_ATTR = "renderedClass"; + + // flag used on the level element private const string INHERITED = "inherited"; - /// - /// key: appenderName, value: appender. - /// - private Hashtable m_appenderBag; - - /// - /// The Hierarchy being configured. - /// + /// + /// key: appenderName, value: appender. + /// + private Hashtable m_appenderBag; + + /// + /// The Hierarchy being configured. + /// private readonly Hierarchy m_hierarchy; - /// - /// The fully qualified type of the XmlHierarchyConfigurator class. - /// - /// - /// Used by the internal logger to record the Type of the - /// log message. - /// + /// + /// The fully qualified type of the XmlHierarchyConfigurator class. + /// + /// + /// Used by the internal logger to record the Type of the + /// log message. + /// private static readonly Type declaringType = typeof(XmlHierarchyConfigurator); - } -} + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Repository/IBasicRepositoryConfigurator.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Repository/IBasicRepositoryConfigurator.cs index 8561a51c911..a0162ab4db0 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Repository/IBasicRepositoryConfigurator.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Repository/IBasicRepositoryConfigurator.cs @@ -1,64 +1,64 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information - -// +// // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at -// +// // http://www.apache.org/licenses/LICENSE-2.0 -// +// // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. -// -namespace log4net.Repository -{ - /// - /// Basic Configurator interface for repositories. - /// - /// - /// - /// Interface used by basic configurator to configure a - /// with a default . - /// - /// - /// A should implement this interface to support - /// configuration by the . - /// - /// - /// Nicko Cadell. - /// Gert Driesen. - public interface IBasicRepositoryConfigurator - { - /// - /// Initialize the repository using the specified appender. - /// - /// the appender to use to log all logging events. - /// - /// - /// Configure the repository to route all logging events to the - /// specified appender. - /// - /// - void Configure(Appender.IAppender appender); - - /// - /// Initialize the repository using the specified appenders. - /// - /// the appenders to use to log all logging events. - /// - /// - /// Configure the repository to route all logging events to the - /// specified appenders. - /// - /// - void Configure(params Appender.IAppender[] appenders); - } -} +// + +namespace log4net.Repository +{ + /// + /// Basic Configurator interface for repositories + /// + /// + /// + /// Interface used by basic configurator to configure a + /// with a default . + /// + /// + /// A should implement this interface to support + /// configuration by the . + /// + /// + /// Nicko Cadell + /// Gert Driesen + public interface IBasicRepositoryConfigurator + { + /// + /// Initialize the repository using the specified appender + /// + /// the appender to use to log all logging events + /// + /// + /// Configure the repository to route all logging events to the + /// specified appender. + /// + /// + void Configure(Appender.IAppender appender); + + /// + /// Initialize the repository using the specified appenders + /// + /// the appenders to use to log all logging events + /// + /// + /// Configure the repository to route all logging events to the + /// specified appenders. + /// + /// + void Configure(params Appender.IAppender[] appenders); + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Repository/ILoggerRepository.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Repository/ILoggerRepository.cs index ddf598730a9..8e90dbebd9e 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Repository/ILoggerRepository.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Repository/ILoggerRepository.cs @@ -1,339 +1,338 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.Repository -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; - using System.Collections; - - using log4net; - using log4net.Core; - using log4net.ObjectRenderer; - using log4net.Plugin; - using log4net.Repository.Hierarchy; - using log4net.Util; +using System; +using System.Collections; +using log4net; +using log4net.ObjectRenderer; +using log4net.Core; +using log4net.Plugin; +using log4net.Repository.Hierarchy; +using log4net.Util; - /// - /// Delegate used to handle logger repository shutdown event notifications. - /// - /// The that is shutting down. - /// Empty event args. - /// - /// - /// Delegate used to handle logger repository shutdown event notifications. - /// - /// +namespace log4net.Repository +{ + /// + /// Delegate used to handle logger repository shutdown event notifications + /// + /// The that is shutting down. + /// Empty event args + /// + /// + /// Delegate used to handle logger repository shutdown event notifications. + /// + /// public delegate void LoggerRepositoryShutdownEventHandler(object sender, EventArgs e); - /// - /// Delegate used to handle logger repository configuration reset event notifications. - /// - /// The that has had its configuration reset. - /// Empty event args. - /// - /// - /// Delegate used to handle logger repository configuration reset event notifications. - /// - /// + /// + /// Delegate used to handle logger repository configuration reset event notifications + /// + /// The that has had its configuration reset. + /// Empty event args + /// + /// + /// Delegate used to handle logger repository configuration reset event notifications. + /// + /// public delegate void LoggerRepositoryConfigurationResetEventHandler(object sender, EventArgs e); - /// - /// Delegate used to handle event notifications for logger repository configuration changes. - /// - /// The that has had its configuration changed. - /// Empty event arguments. - /// - /// - /// Delegate used to handle event notifications for logger repository configuration changes. - /// - /// + /// + /// Delegate used to handle event notifications for logger repository configuration changes. + /// + /// The that has had its configuration changed. + /// Empty event arguments. + /// + /// + /// Delegate used to handle event notifications for logger repository configuration changes. + /// + /// public delegate void LoggerRepositoryConfigurationChangedEventHandler(object sender, EventArgs e); - /// - /// Interface implemented by logger repositories. - /// - /// - /// - /// This interface is implemented by logger repositories. e.g. - /// . - /// - /// - /// This interface is used by the - /// to obtain interfaces. - /// - /// - /// Nicko Cadell. - /// Gert Driesen. - public interface ILoggerRepository - { - /// - /// Gets or sets the name of the repository. - /// - /// - /// The name of the repository. - /// - /// - /// - /// The name of the repository. - /// - /// - string Name { get; set; } - - /// - /// Gets rendererMap accesses the object renderer map for this repository. - /// - /// - /// RendererMap accesses the object renderer map for this repository. - /// - /// - /// - /// RendererMap accesses the object renderer map for this repository. - /// - /// - /// The RendererMap holds a mapping between types and - /// objects. - /// - /// - RendererMap RendererMap { get; } - - /// - /// Gets the plugin map for this repository. - /// - /// - /// The plugin map for this repository. - /// - /// - /// - /// The plugin map holds the instances - /// that have been attached to this repository. - /// - /// - PluginMap PluginMap { get; } - - /// - /// Gets get the level map for the Repository. - /// - /// - /// - /// Get the level map for the Repository. - /// - /// - /// The level map defines the mappings between - /// level names and objects in - /// this repository. - /// - /// - LevelMap LevelMap { get; } - - /// - /// Gets or sets the threshold for all events in this repository. - /// - /// - /// The threshold for all events in this repository. - /// - /// - /// - /// The threshold for all events in this repository. - /// - /// - Level Threshold { get; set; } - - /// - /// Check if the named logger exists in the repository. If so return - /// its reference, otherwise returns null. - /// - /// The name of the logger to lookup. - /// The Logger object with the name specified. - /// - /// - /// If the names logger exists it is returned, otherwise - /// null is returned. - /// - /// - ILogger Exists(string name); - - /// - /// Returns all the currently defined loggers as an Array. - /// - /// All the defined loggers. - /// - /// - /// Returns all the currently defined loggers as an Array. - /// - /// - ILogger[] GetCurrentLoggers(); - - /// - /// Returns a named logger instance. - /// - /// The name of the logger to retrieve. - /// The logger object with the name specified. - /// - /// - /// Returns a named logger instance. - /// - /// - /// If a logger of that name already exists, then it will be - /// returned. Otherwise, a new logger will be instantiated and - /// then linked with its existing ancestors as well as children. - /// - /// - ILogger GetLogger(string name); - - /// Shutdown the repository. - /// - /// - /// Shutting down a repository will safely close and remove - /// all appenders in all loggers including the root logger. - /// - /// - /// Some appenders need to be closed before the - /// application exists. Otherwise, pending logging events might be - /// lost. - /// - /// - /// The method is careful to close nested - /// appenders before closing regular appenders. This is allows - /// configurations where a regular appender is attached to a logger - /// and again to a nested appender. - /// - /// - void Shutdown(); - - /// - /// Reset the repositories configuration to a default state. - /// - /// - /// - /// Reset all values contained in this instance to their - /// default state. - /// - /// - /// Existing loggers are not removed. They are just reset. - /// - /// - /// This method should be used sparingly and with care as it will - /// block all logging until it is completed. - /// - /// - void ResetConfiguration(); - - /// - /// Log the through this repository. - /// - /// the event to log. - /// - /// - /// This method should not normally be used to log. - /// The interface should be used - /// for routine logging. This interface can be obtained - /// using the method. - /// - /// - /// The logEvent is delivered to the appropriate logger and - /// that logger is then responsible for logging the event. - /// - /// - void Log(LoggingEvent logEvent); - - /// - /// Gets or sets a value indicating whether flag indicates if this repository has been configured. - /// - /// - /// Flag indicates if this repository has been configured. - /// - /// - /// - /// Flag indicates if this repository has been configured. - /// - /// - bool Configured { get; set; } - - /// - /// Gets or sets collection of internal messages captured during the most - /// recent configuration process. - /// - ICollection ConfigurationMessages { get; set; } - - /// - /// Event to notify that the repository has been shutdown. - /// - /// - /// Event to notify that the repository has been shutdown. - /// - /// - /// - /// Event raised when the repository has been shutdown. - /// - /// - event LoggerRepositoryShutdownEventHandler ShutdownEvent; - - /// - /// Event to notify that the repository has had its configuration reset. - /// - /// - /// Event to notify that the repository has had its configuration reset. - /// - /// - /// - /// Event raised when the repository's configuration has been - /// reset to default. - /// - /// - event LoggerRepositoryConfigurationResetEventHandler ConfigurationReset; - - /// - /// Event to notify that the repository has had its configuration changed. - /// - /// - /// Event to notify that the repository has had its configuration changed. - /// - /// - /// - /// Event raised when the repository's configuration has been changed. - /// - /// - event LoggerRepositoryConfigurationChangedEventHandler ConfigurationChanged; - - /// - /// Gets repository specific properties. - /// - /// - /// Repository specific properties. - /// - /// - /// - /// These properties can be specified on a repository specific basis. - /// - /// - PropertiesDictionary Properties { get; } - - /// - /// Returns all the Appenders that are configured as an Array. - /// - /// All the Appenders. - /// - /// - /// Returns all the Appenders that are configured as an Array. - /// - /// - log4net.Appender.IAppender[] GetAppenders(); - } -} + /// + /// Interface implemented by logger repositories. + /// + /// + /// + /// This interface is implemented by logger repositories. e.g. + /// . + /// + /// + /// This interface is used by the + /// to obtain interfaces. + /// + /// + /// Nicko Cadell + /// Gert Driesen + public interface ILoggerRepository + { + /// + /// The name of the repository + /// + /// + /// The name of the repository + /// + /// + /// + /// The name of the repository. + /// + /// + string Name { get; set; } + + /// + /// RendererMap accesses the object renderer map for this repository. + /// + /// + /// RendererMap accesses the object renderer map for this repository. + /// + /// + /// + /// RendererMap accesses the object renderer map for this repository. + /// + /// + /// The RendererMap holds a mapping between types and + /// objects. + /// + /// + RendererMap RendererMap { get; } + + /// + /// The plugin map for this repository. + /// + /// + /// The plugin map for this repository. + /// + /// + /// + /// The plugin map holds the instances + /// that have been attached to this repository. + /// + /// + PluginMap PluginMap { get; } + + /// + /// Get the level map for the Repository. + /// + /// + /// + /// Get the level map for the Repository. + /// + /// + /// The level map defines the mappings between + /// level names and objects in + /// this repository. + /// + /// + LevelMap LevelMap { get; } + + /// + /// The threshold for all events in this repository + /// + /// + /// The threshold for all events in this repository + /// + /// + /// + /// The threshold for all events in this repository. + /// + /// + Level Threshold { get; set; } + + /// + /// Check if the named logger exists in the repository. If so return + /// its reference, otherwise returns null. + /// + /// The name of the logger to lookup + /// The Logger object with the name specified + /// + /// + /// If the names logger exists it is returned, otherwise + /// null is returned. + /// + /// + ILogger Exists(string name); + + /// + /// Returns all the currently defined loggers as an Array. + /// + /// All the defined loggers + /// + /// + /// Returns all the currently defined loggers as an Array. + /// + /// + ILogger[] GetCurrentLoggers(); + + /// + /// Returns a named logger instance + /// + /// The name of the logger to retrieve + /// The logger object with the name specified + /// + /// + /// Returns a named logger instance. + /// + /// + /// If a logger of that name already exists, then it will be + /// returned. Otherwise, a new logger will be instantiated and + /// then linked with its existing ancestors as well as children. + /// + /// + ILogger GetLogger(string name); + + /// Shutdown the repository + /// + /// + /// Shutting down a repository will safely close and remove + /// all appenders in all loggers including the root logger. + /// + /// + /// Some appenders need to be closed before the + /// application exists. Otherwise, pending logging events might be + /// lost. + /// + /// + /// The method is careful to close nested + /// appenders before closing regular appenders. This is allows + /// configurations where a regular appender is attached to a logger + /// and again to a nested appender. + /// + /// + void Shutdown(); + + /// + /// Reset the repositories configuration to a default state + /// + /// + /// + /// Reset all values contained in this instance to their + /// default state. + /// + /// + /// Existing loggers are not removed. They are just reset. + /// + /// + /// This method should be used sparingly and with care as it will + /// block all logging until it is completed. + /// + /// + void ResetConfiguration(); + + /// + /// Log the through this repository. + /// + /// the event to log + /// + /// + /// This method should not normally be used to log. + /// The interface should be used + /// for routine logging. This interface can be obtained + /// using the method. + /// + /// + /// The logEvent is delivered to the appropriate logger and + /// that logger is then responsible for logging the event. + /// + /// + void Log(LoggingEvent logEvent); + + /// + /// Flag indicates if this repository has been configured. + /// + /// + /// Flag indicates if this repository has been configured. + /// + /// + /// + /// Flag indicates if this repository has been configured. + /// + /// + bool Configured { get; set; } + + /// + /// Collection of internal messages captured during the most + /// recent configuration process. + /// + ICollection ConfigurationMessages { get; set; } + + /// + /// Event to notify that the repository has been shutdown. + /// + /// + /// Event to notify that the repository has been shutdown. + /// + /// + /// + /// Event raised when the repository has been shutdown. + /// + /// + event LoggerRepositoryShutdownEventHandler ShutdownEvent; + + /// + /// Event to notify that the repository has had its configuration reset. + /// + /// + /// Event to notify that the repository has had its configuration reset. + /// + /// + /// + /// Event raised when the repository's configuration has been + /// reset to default. + /// + /// + event LoggerRepositoryConfigurationResetEventHandler ConfigurationReset; + + /// + /// Event to notify that the repository has had its configuration changed. + /// + /// + /// Event to notify that the repository has had its configuration changed. + /// + /// + /// + /// Event raised when the repository's configuration has been changed. + /// + /// + event LoggerRepositoryConfigurationChangedEventHandler ConfigurationChanged; + + /// + /// Repository specific properties + /// + /// + /// Repository specific properties + /// + /// + /// + /// These properties can be specified on a repository specific basis. + /// + /// + PropertiesDictionary Properties { get; } + + /// + /// Returns all the Appenders that are configured as an Array. + /// + /// All the Appenders + /// + /// + /// Returns all the Appenders that are configured as an Array. + /// + /// + Appender.IAppender[] GetAppenders(); + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Repository/IXmlRepositoryConfigurator.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Repository/IXmlRepositoryConfigurator.cs index a1786a3a931..b5159963908 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Repository/IXmlRepositoryConfigurator.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Repository/IXmlRepositoryConfigurator.cs @@ -1,56 +1,55 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.Repository -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; - using System.Collections; +using System; +using System.Collections; +using log4net.Util; - using log4net.Util; - - /// - /// Configure repository using XML. - /// - /// - /// - /// Interface used by Xml configurator to configure a . - /// - /// - /// A should implement this interface to support - /// configuration by the . - /// - /// - /// Nicko Cadell. - /// Gert Driesen. - public interface IXmlRepositoryConfigurator - { - /// - /// Initialize the repository using the specified config. - /// - /// the element containing the root of the config. - /// - /// - /// The schema for the XML configuration data is defined by - /// the implementation. - /// - /// - void Configure(System.Xml.XmlElement element); - } -} +namespace log4net.Repository +{ + /// + /// Configure repository using XML + /// + /// + /// + /// Interface used by Xml configurator to configure a . + /// + /// + /// A should implement this interface to support + /// configuration by the . + /// + /// + /// Nicko Cadell + /// Gert Driesen + public interface IXmlRepositoryConfigurator + { + /// + /// Initialize the repository using the specified config + /// + /// the element containing the root of the config + /// + /// + /// The schema for the XML configuration data is defined by + /// the implementation. + /// + /// + void Configure(System.Xml.XmlElement element); + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Repository/LoggerRepositorySkeleton.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Repository/LoggerRepositorySkeleton.cs index 9d7f7365df7..98bf60f154c 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Repository/LoggerRepositorySkeleton.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Repository/LoggerRepositorySkeleton.cs @@ -1,577 +1,567 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.Repository -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; - using System.Collections; - using System.Threading; - - using log4net.Core; - using log4net.ObjectRenderer; - using log4net.Plugin; - using log4net.Util; - - /// - /// Base implementation of . - /// - /// - /// - /// Default abstract implementation of the interface. - /// - /// - /// Skeleton implementation of the interface. - /// All types can extend this type. - /// - /// - /// Nicko Cadell. - /// Gert Driesen. - public abstract class LoggerRepositorySkeleton : ILoggerRepository, Appender.IFlushable +using System; +using System.Collections; +using log4net.ObjectRenderer; +using log4net.Core; +using log4net.Util; +using log4net.Plugin; +using System.Threading; + +namespace log4net.Repository +{ + /// + /// Base implementation of + /// + /// + /// + /// Default abstract implementation of the interface. + /// + /// + /// Skeleton implementation of the interface. + /// All types can extend this type. + /// + /// + /// Nicko Cadell + /// Gert Driesen + public abstract class LoggerRepositorySkeleton : ILoggerRepository, Appender.IFlushable { - private string m_name; - private RendererMap m_rendererMap; - private PluginMap m_pluginMap; - private LevelMap m_levelMap; - private Level m_threshold; - private bool m_configured; - private ICollection m_configurationMessages; + private string m_name; + private RendererMap m_rendererMap; + private PluginMap m_pluginMap; + private LevelMap m_levelMap; + private Level m_threshold; + private bool m_configured; + private ICollection m_configurationMessages; + private event LoggerRepositoryShutdownEventHandler m_shutdownEvent; + private event LoggerRepositoryConfigurationResetEventHandler m_configurationResetEvent; + private event LoggerRepositoryConfigurationChangedEventHandler m_configurationChangedEvent; + private PropertiesDictionary m_properties; + + /// + /// Default Constructor + /// + /// + /// + /// Initializes the repository with default (empty) properties. + /// + /// + protected LoggerRepositorySkeleton() : this(new PropertiesDictionary()) + { + } - private event LoggerRepositoryShutdownEventHandler m_shutdownEvent; + /// + /// Construct the repository using specific properties + /// + /// the properties to set for this repository + /// + /// + /// Initializes the repository with specified properties. + /// + /// + protected LoggerRepositorySkeleton(PropertiesDictionary properties) + { + this.m_properties = properties; + this.m_rendererMap = new RendererMap(); + this.m_pluginMap = new PluginMap(this); + this.m_levelMap = new LevelMap(); + this.m_configurationMessages = EmptyCollection.Instance; + this.m_configured = false; - private event LoggerRepositoryConfigurationResetEventHandler m_configurationResetEvent; + this.AddBuiltinLevels(); - private event LoggerRepositoryConfigurationChangedEventHandler m_configurationChangedEvent; + // Don't disable any levels by default. + this.m_threshold = Level.All; + } - private PropertiesDictionary m_properties; + /// + /// The name of the repository + /// + /// + /// The string name of the repository + /// + /// + /// + /// The name of this repository. The name is + /// used to store and lookup the repositories + /// stored by the . + /// + /// + public virtual string Name + { + get { return this.m_name; } + set { this.m_name = value; } + } + + /// + /// The threshold for all events in this repository + /// + /// + /// The threshold for all events in this repository + /// + /// + /// + /// The threshold for all events in this repository + /// + /// + public virtual Level Threshold + { + get { return this.m_threshold; } + set + { + if (value != null) + { + this.m_threshold = value; + } + else + { + // Must not set threshold to null + LogLog.Warn(declaringType, "LoggerRepositorySkeleton: Threshold cannot be set to null. Setting to ALL"); + this.m_threshold = Level.All; + } + } + } + + /// + /// RendererMap accesses the object renderer map for this repository. + /// + /// + /// RendererMap accesses the object renderer map for this repository. + /// + /// + /// + /// RendererMap accesses the object renderer map for this repository. + /// + /// + /// The RendererMap holds a mapping between types and + /// objects. + /// + /// + public virtual RendererMap RendererMap + { + get { return this.m_rendererMap; } + } + + /// + /// The plugin map for this repository. + /// + /// + /// The plugin map for this repository. + /// + /// + /// + /// The plugin map holds the instances + /// that have been attached to this repository. + /// + /// + public virtual PluginMap PluginMap + { + get { return this.m_pluginMap; } + } + + /// + /// Get the level map for the Repository. + /// + /// + /// + /// Get the level map for the Repository. + /// + /// + /// The level map defines the mappings between + /// level names and objects in + /// this repository. + /// + /// + public virtual LevelMap LevelMap + { + get { return this.m_levelMap; } + } + + /// + /// Test if logger exists + /// + /// The name of the logger to lookup + /// The Logger object with the name specified + /// + /// + /// Check if the named logger exists in the repository. If so return + /// its reference, otherwise returns null. + /// + /// + public abstract ILogger Exists(string name); + + /// + /// Returns all the currently defined loggers in the repository + /// + /// All the defined loggers + /// + /// + /// Returns all the currently defined loggers in the repository as an Array. + /// + /// + public abstract ILogger[] GetCurrentLoggers(); + + /// + /// Return a new logger instance + /// + /// The name of the logger to retrieve + /// The logger object with the name specified + /// + /// + /// Return a new logger instance. + /// + /// + /// If a logger of that name already exists, then it will be + /// returned. Otherwise, a new logger will be instantiated and + /// then linked with its existing ancestors as well as children. + /// + /// + public abstract ILogger GetLogger(string name); + + /// + /// Shutdown the repository + /// + /// + /// + /// Shutdown the repository. Can be overridden in a subclass. + /// This base class implementation notifies the + /// listeners and all attached plugins of the shutdown event. + /// + /// + public virtual void Shutdown() + { + // Shutdown attached plugins + foreach(IPlugin plugin in this.PluginMap.AllPlugins) + { + plugin.Shutdown(); + } + + // Notify listeners + this.OnShutdown(null); + } + + /// + /// Reset the repositories configuration to a default state + /// + /// + /// + /// Reset all values contained in this instance to their + /// default state. + /// + /// + /// Existing loggers are not removed. They are just reset. + /// + /// + /// This method should be used sparingly and with care as it will + /// block all logging until it is completed. + /// + /// + public virtual void ResetConfiguration() + { + // Clear internal data structures + this.m_rendererMap.Clear(); + this.m_levelMap.Clear(); + this.m_configurationMessages = EmptyCollection.Instance; + + // Add the predefined levels to the map + this.AddBuiltinLevels(); + + this.Configured = false; + + // Notify listeners + this.OnConfigurationReset(null); + } /// - /// Initializes a new instance of the class. - /// Default Constructor. - /// - /// - /// - /// Initializes the repository with default (empty) properties. - /// - /// - protected LoggerRepositorySkeleton() - : this(new PropertiesDictionary()) - { + /// Log the logEvent through this repository. + /// + /// the event to log + /// + /// + /// This method should not normally be used to log. + /// The interface should be used + /// for routine logging. This interface can be obtained + /// using the method. + /// + /// + /// The logEvent is delivered to the appropriate logger and + /// that logger is then responsible for logging the event. + /// + /// + public abstract void Log(LoggingEvent logEvent); + + /// + /// Flag indicates if this repository has been configured. + /// + /// + /// Flag indicates if this repository has been configured. + /// + /// + /// + /// Flag indicates if this repository has been configured. + /// + /// + public virtual bool Configured + { + get { return this.m_configured; } + set { this.m_configured = value; } + } + + /// + /// Contains a list of internal messages captures during the + /// last configuration. + /// + public virtual ICollection ConfigurationMessages + { + get { return this.m_configurationMessages; } + set { this.m_configurationMessages = value; } + } + + /// + /// Event to notify that the repository has been shutdown. + /// + /// + /// Event to notify that the repository has been shutdown. + /// + /// + /// + /// Event raised when the repository has been shutdown. + /// + /// + public event LoggerRepositoryShutdownEventHandler ShutdownEvent + { + add { this.m_shutdownEvent += value; } + remove { this.m_shutdownEvent -= value; } } /// - /// Initializes a new instance of the class. - /// Construct the repository using specific properties. - /// - /// the properties to set for this repository. - /// - /// - /// Initializes the repository with specified properties. - /// - /// - protected LoggerRepositorySkeleton(PropertiesDictionary properties) - { - this.m_properties = properties; - this.m_rendererMap = new RendererMap(); - this.m_pluginMap = new PluginMap(this); - this.m_levelMap = new LevelMap(); - this.m_configurationMessages = EmptyCollection.Instance; - this.m_configured = false; - - this.AddBuiltinLevels(); - - // Don't disable any levels by default. - this.m_threshold = Level.All; + /// Event to notify that the repository has had its configuration reset. + /// + /// + /// Event to notify that the repository has had its configuration reset. + /// + /// + /// + /// Event raised when the repository's configuration has been + /// reset to default. + /// + /// + public event LoggerRepositoryConfigurationResetEventHandler ConfigurationReset + { + add { this.m_configurationResetEvent += value; } + remove { this.m_configurationResetEvent -= value; } } - /// - /// Gets or sets the name of the repository. - /// - /// - /// The string name of the repository. - /// - /// - /// - /// The name of this repository. The name is - /// used to store and lookup the repositories - /// stored by the . - /// - /// - public virtual string Name - { - get { return this.m_name; } - set { this.m_name = value; } - } - - /// - /// Gets or sets the threshold for all events in this repository. - /// - /// - /// The threshold for all events in this repository. - /// - /// - /// - /// The threshold for all events in this repository. - /// - /// - public virtual Level Threshold - { - get { return this.m_threshold; } - - set - { - if (value != null) - { - this.m_threshold = value; - } - else - { - // Must not set threshold to null - LogLog.Warn(declaringType, "LoggerRepositorySkeleton: Threshold cannot be set to null. Setting to ALL"); - this.m_threshold = Level.All; - } - } - } - - /// - /// Gets rendererMap accesses the object renderer map for this repository. - /// - /// - /// RendererMap accesses the object renderer map for this repository. - /// - /// - /// - /// RendererMap accesses the object renderer map for this repository. - /// - /// - /// The RendererMap holds a mapping between types and - /// objects. - /// - /// - public virtual RendererMap RendererMap - { - get { return this.m_rendererMap; } - } - - /// - /// Gets the plugin map for this repository. - /// - /// - /// The plugin map for this repository. - /// - /// - /// - /// The plugin map holds the instances - /// that have been attached to this repository. - /// - /// - public virtual PluginMap PluginMap - { - get { return this.m_pluginMap; } - } - - /// - /// Gets get the level map for the Repository. - /// - /// - /// - /// Get the level map for the Repository. - /// - /// - /// The level map defines the mappings between - /// level names and objects in - /// this repository. - /// - /// - public virtual LevelMap LevelMap - { - get { return this.m_levelMap; } - } - - /// - /// Test if logger exists. - /// - /// The name of the logger to lookup. - /// The Logger object with the name specified. - /// - /// - /// Check if the named logger exists in the repository. If so return - /// its reference, otherwise returns null. - /// - /// - public abstract ILogger Exists(string name); - - /// - /// Returns all the currently defined loggers in the repository. - /// - /// All the defined loggers. - /// - /// - /// Returns all the currently defined loggers in the repository as an Array. - /// - /// - public abstract ILogger[] GetCurrentLoggers(); - - /// - /// Return a new logger instance. - /// - /// The name of the logger to retrieve. - /// The logger object with the name specified. - /// - /// - /// Return a new logger instance. - /// - /// - /// If a logger of that name already exists, then it will be - /// returned. Otherwise, a new logger will be instantiated and - /// then linked with its existing ancestors as well as children. - /// - /// - public abstract ILogger GetLogger(string name); - - /// - /// Shutdown the repository. - /// - /// - /// - /// Shutdown the repository. Can be overridden in a subclass. - /// This base class implementation notifies the - /// listeners and all attached plugins of the shutdown event. - /// - /// - public virtual void Shutdown() - { - // Shutdown attached plugins - foreach (IPlugin plugin in this.PluginMap.AllPlugins) - { - plugin.Shutdown(); - } - - // Notify listeners - this.OnShutdown(null); - } - - /// - /// Reset the repositories configuration to a default state. - /// - /// - /// - /// Reset all values contained in this instance to their - /// default state. - /// - /// - /// Existing loggers are not removed. They are just reset. - /// - /// - /// This method should be used sparingly and with care as it will - /// block all logging until it is completed. - /// - /// - public virtual void ResetConfiguration() - { - // Clear internal data structures - this.m_rendererMap.Clear(); - this.m_levelMap.Clear(); - this.m_configurationMessages = EmptyCollection.Instance; - - // Add the predefined levels to the map - this.AddBuiltinLevels(); - - this.Configured = false; - - // Notify listeners - this.OnConfigurationReset(null); - } - - /// - /// Log the logEvent through this repository. - /// - /// the event to log. - /// - /// - /// This method should not normally be used to log. - /// The interface should be used - /// for routine logging. This interface can be obtained - /// using the method. - /// - /// - /// The logEvent is delivered to the appropriate logger and - /// that logger is then responsible for logging the event. - /// - /// - public abstract void Log(LoggingEvent logEvent); - - /// - /// Gets or sets a value indicating whether flag indicates if this repository has been configured. - /// - /// - /// Flag indicates if this repository has been configured. - /// - /// - /// - /// Flag indicates if this repository has been configured. - /// - /// - public virtual bool Configured - { - get { return this.m_configured; } - set { this.m_configured = value; } - } - - /// - /// Gets or sets contains a list of internal messages captures during the - /// last configuration. - /// - public virtual ICollection ConfigurationMessages - { - get { return this.m_configurationMessages; } - set { this.m_configurationMessages = value; } - } - - /// - /// Event to notify that the repository has been shutdown. - /// - /// - /// Event to notify that the repository has been shutdown. - /// - /// - /// - /// Event raised when the repository has been shutdown. - /// - /// - public event LoggerRepositoryShutdownEventHandler ShutdownEvent - { - add { this.m_shutdownEvent += value; } - remove { this.m_shutdownEvent -= value; } - } - - /// - /// Event to notify that the repository has had its configuration reset. - /// - /// - /// Event to notify that the repository has had its configuration reset. - /// - /// - /// - /// Event raised when the repository's configuration has been - /// reset to default. - /// - /// - public event LoggerRepositoryConfigurationResetEventHandler ConfigurationReset - { - add { this.m_configurationResetEvent += value; } - remove { this.m_configurationResetEvent -= value; } - } - - /// - /// Event to notify that the repository has had its configuration changed. - /// - /// - /// Event to notify that the repository has had its configuration changed. - /// - /// - /// - /// Event raised when the repository's configuration has been changed. - /// - /// - public event LoggerRepositoryConfigurationChangedEventHandler ConfigurationChanged - { - add { this.m_configurationChangedEvent += value; } - remove { this.m_configurationChangedEvent -= value; } - } - - /// - /// Gets repository specific properties. - /// - /// - /// Repository specific properties. - /// - /// - /// These properties can be specified on a repository specific basis. - /// - public PropertiesDictionary Properties - { - get { return this.m_properties; } - } - - /// - /// Returns all the Appenders that are configured as an Array. - /// - /// All the Appenders. - /// - /// - /// Returns all the Appenders that are configured as an Array. - /// - /// - public abstract log4net.Appender.IAppender[] GetAppenders(); - - /// - /// The fully qualified type of the LoggerRepositorySkeleton class. - /// - /// - /// Used by the internal logger to record the Type of the - /// log message. - /// + /// + /// Event to notify that the repository has had its configuration changed. + /// + /// + /// Event to notify that the repository has had its configuration changed. + /// + /// + /// + /// Event raised when the repository's configuration has been changed. + /// + /// + public event LoggerRepositoryConfigurationChangedEventHandler ConfigurationChanged + { + add { this.m_configurationChangedEvent += value; } + remove { this.m_configurationChangedEvent -= value; } + } + + /// + /// Repository specific properties + /// + /// + /// Repository specific properties + /// + /// + /// These properties can be specified on a repository specific basis + /// + public PropertiesDictionary Properties + { + get { return this.m_properties; } + } + + /// + /// Returns all the Appenders that are configured as an Array. + /// + /// All the Appenders + /// + /// + /// Returns all the Appenders that are configured as an Array. + /// + /// + public abstract Appender.IAppender[] GetAppenders(); + + /// + /// The fully qualified type of the LoggerRepositorySkeleton class. + /// + /// + /// Used by the internal logger to record the Type of the + /// log message. + /// private static readonly Type declaringType = typeof(LoggerRepositorySkeleton); - private void AddBuiltinLevels() - { - // Add the predefined levels to the map - this.m_levelMap.Add(Level.Off); - - // Unrecoverable errors - this.m_levelMap.Add(Level.Emergency); - this.m_levelMap.Add(Level.Fatal); - this.m_levelMap.Add(Level.Alert); - - // Recoverable errors - this.m_levelMap.Add(Level.Critical); - this.m_levelMap.Add(Level.Severe); - this.m_levelMap.Add(Level.Error); - this.m_levelMap.Add(Level.Warn); - - // Information - this.m_levelMap.Add(Level.Notice); - this.m_levelMap.Add(Level.Info); - - // Debug - this.m_levelMap.Add(Level.Debug); - this.m_levelMap.Add(Level.Fine); - this.m_levelMap.Add(Level.Trace); - this.m_levelMap.Add(Level.Finer); - this.m_levelMap.Add(Level.Verbose); - this.m_levelMap.Add(Level.Finest); - - this.m_levelMap.Add(Level.All); - } - - /// - /// Adds an object renderer for a specific class. - /// - /// The type that will be rendered by the renderer supplied. - /// The object renderer used to render the object. - /// - /// - /// Adds an object renderer for a specific class. - /// - /// - public virtual void AddRenderer(Type typeToRender, IObjectRenderer rendererInstance) - { - if (typeToRender == null) - { - throw new ArgumentNullException("typeToRender"); - } - - if (rendererInstance == null) - { - throw new ArgumentNullException("rendererInstance"); - } - - this.m_rendererMap.Put(typeToRender, rendererInstance); - } - - /// - /// Notify the registered listeners that the repository is shutting down. - /// - /// Empty EventArgs. - /// - /// - /// Notify any listeners that this repository is shutting down. - /// - /// - protected virtual void OnShutdown(EventArgs e) - { - if (e == null) - { - e = EventArgs.Empty; - } - - LoggerRepositoryShutdownEventHandler handler = this.m_shutdownEvent; - if (handler != null) - { - handler(this, e); - } - } - - /// - /// Notify the registered listeners that the repository has had its configuration reset. - /// - /// Empty EventArgs. - /// - /// - /// Notify any listeners that this repository's configuration has been reset. - /// - /// - protected virtual void OnConfigurationReset(EventArgs e) - { - if (e == null) - { - e = EventArgs.Empty; - } - - LoggerRepositoryConfigurationResetEventHandler handler = this.m_configurationResetEvent; - if (handler != null) - { - handler(this, e); - } - } - - /// - /// Notify the registered listeners that the repository has had its configuration changed. - /// - /// Empty EventArgs. - /// - /// - /// Notify any listeners that this repository's configuration has changed. - /// - /// - protected virtual void OnConfigurationChanged(EventArgs e) - { - if (e == null) - { - e = EventArgs.Empty; - } - - LoggerRepositoryConfigurationChangedEventHandler handler = this.m_configurationChangedEvent; - if (handler != null) - { - handler(this, e); - } - } - - /// - /// Raise a configuration changed event on this repository. - /// - /// EventArgs.Empty. - /// - /// - /// Applications that programmatically change the configuration of the repository should - /// raise this event notification to notify listeners. - /// - /// - public void RaiseConfigurationChanged(EventArgs e) - { - this.OnConfigurationChanged(e); - } - - private static int GetWaitTime(DateTime startTimeUtc, int millisecondsTimeout) - { + private void AddBuiltinLevels() + { + // Add the predefined levels to the map + this.m_levelMap.Add(Level.Off); + + // Unrecoverable errors + this.m_levelMap.Add(Level.Emergency); + this.m_levelMap.Add(Level.Fatal); + this.m_levelMap.Add(Level.Alert); + + // Recoverable errors + this.m_levelMap.Add(Level.Critical); + this.m_levelMap.Add(Level.Severe); + this.m_levelMap.Add(Level.Error); + this.m_levelMap.Add(Level.Warn); + + // Information + this.m_levelMap.Add(Level.Notice); + this.m_levelMap.Add(Level.Info); + + // Debug + this.m_levelMap.Add(Level.Debug); + this.m_levelMap.Add(Level.Fine); + this.m_levelMap.Add(Level.Trace); + this.m_levelMap.Add(Level.Finer); + this.m_levelMap.Add(Level.Verbose); + this.m_levelMap.Add(Level.Finest); + + this.m_levelMap.Add(Level.All); + } + + /// + /// Adds an object renderer for a specific class. + /// + /// The type that will be rendered by the renderer supplied. + /// The object renderer used to render the object. + /// + /// + /// Adds an object renderer for a specific class. + /// + /// + public virtual void AddRenderer(Type typeToRender, IObjectRenderer rendererInstance) + { + if (typeToRender == null) + { + throw new ArgumentNullException("typeToRender"); + } + if (rendererInstance == null) + { + throw new ArgumentNullException("rendererInstance"); + } + + this.m_rendererMap.Put(typeToRender, rendererInstance); + } + + /// + /// Notify the registered listeners that the repository is shutting down + /// + /// Empty EventArgs + /// + /// + /// Notify any listeners that this repository is shutting down. + /// + /// + protected virtual void OnShutdown(EventArgs e) + { + if (e == null) + { + e = EventArgs.Empty; + } + + LoggerRepositoryShutdownEventHandler handler = this.m_shutdownEvent; + if (handler != null) + { + handler(this, e); + } + } + + /// + /// Notify the registered listeners that the repository has had its configuration reset + /// + /// Empty EventArgs + /// + /// + /// Notify any listeners that this repository's configuration has been reset. + /// + /// + protected virtual void OnConfigurationReset(EventArgs e) + { + if (e == null) + { + e = EventArgs.Empty; + } + + LoggerRepositoryConfigurationResetEventHandler handler = this.m_configurationResetEvent; + if (handler != null) + { + handler(this, e); + } + } + + /// + /// Notify the registered listeners that the repository has had its configuration changed + /// + /// Empty EventArgs + /// + /// + /// Notify any listeners that this repository's configuration has changed. + /// + /// + protected virtual void OnConfigurationChanged(EventArgs e) + { + if (e == null) + { + e = EventArgs.Empty; + } + + LoggerRepositoryConfigurationChangedEventHandler handler = this.m_configurationChangedEvent; + if (handler != null) + { + handler(this, e); + } + } + + /// + /// Raise a configuration changed event on this repository + /// + /// EventArgs.Empty + /// + /// + /// Applications that programmatically change the configuration of the repository should + /// raise this event notification to notify listeners. + /// + /// + public void RaiseConfigurationChanged(EventArgs e) + { + this.OnConfigurationChanged(e); + } + + private static int GetWaitTime(DateTime startTimeUtc, int millisecondsTimeout) + { if (millisecondsTimeout == Timeout.Infinite) { return Timeout.Infinite; @@ -582,74 +572,74 @@ private static int GetWaitTime(DateTime startTimeUtc, int millisecondsTimeout) return 0; } - int elapsedMilliseconds = (int)(DateTime.UtcNow - startTimeUtc).TotalMilliseconds; - int timeout = millisecondsTimeout - elapsedMilliseconds; + int elapsedMilliseconds = (int)(DateTime.UtcNow - startTimeUtc).TotalMilliseconds; + int timeout = millisecondsTimeout - elapsedMilliseconds; if (timeout < 0) { timeout = 0; } - return timeout; - } - - /// - /// Flushes all configured Appenders that implement . - /// - /// The maximum time in milliseconds to wait for logging events from asycnhronous appenders to be flushed, - /// or to wait indefinitely. - /// True if all logging events were flushed successfully, else false. - public bool Flush(int millisecondsTimeout) - { + return timeout; + } + + /// + /// Flushes all configured Appenders that implement . + /// + /// The maximum time in milliseconds to wait for logging events from asycnhronous appenders to be flushed, + /// or to wait indefinitely. + /// True if all logging events were flushed successfully, else false. + public bool Flush(int millisecondsTimeout) + { if (millisecondsTimeout < -1) { throw new ArgumentOutOfRangeException("millisecondsTimeout", "Timeout must be -1 (Timeout.Infinite) or non-negative"); } // Assume success until one of the appenders fails - bool result = true; - - // Use DateTime.UtcNow rather than a System.Diagnostics.Stopwatch for compatibility with .NET 1.x - DateTime startTimeUtc = DateTime.UtcNow; - - // Do buffering appenders first. These may be forwarding to other appenders - foreach (log4net.Appender.IAppender appender in this.GetAppenders()) - { - log4net.Appender.IFlushable flushable = appender as log4net.Appender.IFlushable; + bool result = true; + + // Use DateTime.UtcNow rather than a System.Diagnostics.Stopwatch for compatibility with .NET 1.x + DateTime startTimeUtc = DateTime.UtcNow; + + // Do buffering appenders first. These may be forwarding to other appenders + foreach(Appender.IAppender appender in this.GetAppenders()) + { + Appender.IFlushable flushable = appender as Appender.IFlushable; if (flushable == null) { continue; } - if (appender is Appender.BufferingAppenderSkeleton) - { - int timeout = GetWaitTime(startTimeUtc, millisecondsTimeout); + if (appender is Appender.BufferingAppenderSkeleton) + { + int timeout = GetWaitTime(startTimeUtc, millisecondsTimeout); if (!flushable.Flush(timeout)) { result = false; } - } - } - - // Do non-buffering appenders. - foreach (log4net.Appender.IAppender appender in this.GetAppenders()) - { - log4net.Appender.IFlushable flushable = appender as log4net.Appender.IFlushable; + } + } + + // Do non-buffering appenders. + foreach (Appender.IAppender appender in this.GetAppenders()) + { + Appender.IFlushable flushable = appender as Appender.IFlushable; if (flushable == null) { continue; } - if (!(appender is Appender.BufferingAppenderSkeleton)) - { - int timeout = GetWaitTime(startTimeUtc, millisecondsTimeout); + if (!(appender is Appender.BufferingAppenderSkeleton)) + { + int timeout = GetWaitTime(startTimeUtc, millisecondsTimeout); if (!flushable.Flush(timeout)) { result = false; } - } - } - - return result; - } - } -} + } + } + + return result; + } + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/ThreadContext.cs b/DNN Platform/DotNetNuke.Log4net/log4net/ThreadContext.cs index 1a034245725..545effdf3e8 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/ThreadContext.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/ThreadContext.cs @@ -1,129 +1,128 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; - using System.Collections; +using System; +using System.Collections; - using log4net.Util; +using log4net.Util; - /// - /// The log4net Thread Context. - /// - /// - /// - /// The ThreadContext provides a location for thread specific debugging - /// information to be stored. - /// The ThreadContext properties override any - /// properties with the same name. - /// - /// - /// The thread context has a properties map and a stack. - /// The properties and stack can - /// be included in the output of log messages. The - /// supports selecting and outputting these properties. - /// - /// - /// The Thread Context provides a diagnostic context for the current thread. - /// This is an instrument for distinguishing interleaved log - /// output from different sources. Log output is typically interleaved - /// when a server handles multiple clients near-simultaneously. - /// - /// - /// The Thread Context is managed on a per thread basis. - /// - /// - /// Example of using the thread context properties to store a username. - /// - /// ThreadContext.Properties["user"] = userName; - /// log.Info("This log message has a ThreadContext Property called 'user'"); - /// - /// - /// Example of how to push a message into the context stack. - /// - /// using(ThreadContext.Stacks["NDC"].Push("my context message")) - /// { - /// log.Info("This log message has a ThreadContext Stack message that includes 'my context message'"); - /// - /// } // at the end of the using block the message is automatically popped - /// - /// - /// - /// Nicko Cadell. - public sealed class ThreadContext +namespace log4net +{ + /// + /// The log4net Thread Context. + /// + /// + /// + /// The ThreadContext provides a location for thread specific debugging + /// information to be stored. + /// The ThreadContext properties override any + /// properties with the same name. + /// + /// + /// The thread context has a properties map and a stack. + /// The properties and stack can + /// be included in the output of log messages. The + /// supports selecting and outputting these properties. + /// + /// + /// The Thread Context provides a diagnostic context for the current thread. + /// This is an instrument for distinguishing interleaved log + /// output from different sources. Log output is typically interleaved + /// when a server handles multiple clients near-simultaneously. + /// + /// + /// The Thread Context is managed on a per thread basis. + /// + /// + /// Example of using the thread context properties to store a username. + /// + /// ThreadContext.Properties["user"] = userName; + /// log.Info("This log message has a ThreadContext Property called 'user'"); + /// + /// + /// Example of how to push a message into the context stack + /// + /// using(ThreadContext.Stacks["NDC"].Push("my context message")) + /// { + /// log.Info("This log message has a ThreadContext Stack message that includes 'my context message'"); + /// + /// } // at the end of the using block the message is automatically popped + /// + /// + /// + /// Nicko Cadell + public sealed class ThreadContext { /// - /// Initializes a new instance of the class. - /// Private Constructor. - /// - /// - /// - /// Uses a private access modifier to prevent instantiation of this class. - /// - /// - private ThreadContext() - { + /// Private Constructor. + /// + /// + /// + /// Uses a private access modifier to prevent instantiation of this class. + /// + /// + private ThreadContext() + { } - /// - /// Gets the thread properties map. - /// - /// - /// The thread properties map. - /// - /// - /// - /// The ThreadContext properties override any - /// properties with the same name. - /// - /// - public static ThreadContextProperties Properties - { - get { return s_properties; } - } - - /// - /// Gets the thread stacks. - /// - /// - /// stack map. - /// - /// - /// - /// The thread local stacks. - /// - /// - public static ThreadContextStacks Stacks - { - get { return s_stacks; } + /// + /// The thread properties map + /// + /// + /// The thread properties map + /// + /// + /// + /// The ThreadContext properties override any + /// properties with the same name. + /// + /// + public static ThreadContextProperties Properties + { + get { return s_properties; } + } + + /// + /// The thread stacks + /// + /// + /// stack map + /// + /// + /// + /// The thread local stacks. + /// + /// + public static ThreadContextStacks Stacks + { + get { return s_stacks; } } - /// - /// The thread context properties instance. - /// - private static readonly ThreadContextProperties s_properties = new ThreadContextProperties(); - - /// - /// The thread context stacks instance. - /// + /// + /// The thread context properties instance + /// + private static readonly ThreadContextProperties s_properties = new ThreadContextProperties(); + + /// + /// The thread context stacks instance + /// private static readonly ThreadContextStacks s_stacks = new ThreadContextStacks(s_properties); - } -} + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/AppenderAttachedImpl.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/AppenderAttachedImpl.cs index 895706c770c..94c062b454c 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/AppenderAttachedImpl.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/AppenderAttachedImpl.cs @@ -1,363 +1,355 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.Util -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; +using System; - using log4net.Appender; - using log4net.Core; +using log4net.Core; +using log4net.Appender; - /// - /// A straightforward implementation of the interface. - /// - /// - /// - /// This is the default implementation of the - /// interface. Implementors of the interface - /// should aggregate an instance of this type. - /// - /// - /// Nicko Cadell. - /// Gert Driesen. - public class AppenderAttachedImpl : IAppenderAttachable +namespace log4net.Util +{ + /// + /// A straightforward implementation of the interface. + /// + /// + /// + /// This is the default implementation of the + /// interface. Implementors of the interface + /// should aggregate an instance of this type. + /// + /// + /// Nicko Cadell + /// Gert Driesen + public class AppenderAttachedImpl : IAppenderAttachable { /// - /// Initializes a new instance of the class. - /// Constructor. - /// - /// - /// - /// Initializes a new instance of the class. - /// - /// - public AppenderAttachedImpl() - { + /// Constructor + /// + /// + /// + /// Initializes a new instance of the class. + /// + /// + public AppenderAttachedImpl() + { } - /// - /// Append on on all attached appenders. - /// - /// The event being logged. - /// The number of appenders called. - /// - /// - /// Calls the method on all - /// attached appenders. - /// - /// - public int AppendLoopOnAppenders(LoggingEvent loggingEvent) - { - if (loggingEvent == null) - { - throw new ArgumentNullException("loggingEvent"); - } - - // m_appenderList is null when empty - if (this.m_appenderList == null) - { - return 0; - } - - if (this.m_appenderArray == null) - { - this.m_appenderArray = this.m_appenderList.ToArray(); - } - - foreach (IAppender appender in this.m_appenderArray) - { - try - { - appender.DoAppend(loggingEvent); - } - catch (Exception ex) - { - LogLog.Error(declaringType, "Failed to append to appender [" + appender.Name + "]", ex); - } - } + /// + /// Append on on all attached appenders. + /// + /// The event being logged. + /// The number of appenders called. + /// + /// + /// Calls the method on all + /// attached appenders. + /// + /// + public int AppendLoopOnAppenders(LoggingEvent loggingEvent) + { + if (loggingEvent == null) + { + throw new ArgumentNullException("loggingEvent"); + } + + // m_appenderList is null when empty + if (this.m_appenderList == null) + { + return 0; + } - return this.m_appenderList.Count; - } - - /// - /// Append on on all attached appenders. - /// - /// The array of events being logged. - /// The number of appenders called. - /// - /// - /// Calls the method on all - /// attached appenders. - /// - /// - public int AppendLoopOnAppenders(LoggingEvent[] loggingEvents) - { - if (loggingEvents == null) - { - throw new ArgumentNullException("loggingEvents"); - } + if (this.m_appenderArray == null) + { + this.m_appenderArray = this.m_appenderList.ToArray(); + } - if (loggingEvents.Length == 0) - { - throw new ArgumentException("loggingEvents array must not be empty", "loggingEvents"); - } + foreach(IAppender appender in this.m_appenderArray) + { + try + { + appender.DoAppend(loggingEvent); + } + catch(Exception ex) + { + LogLog.Error(declaringType, "Failed to append to appender [" + appender.Name + "]", ex); + } + } + return this.m_appenderList.Count; + } - if (loggingEvents.Length == 1) - { - // Fall back to single event path - return this.AppendLoopOnAppenders(loggingEvents[0]); - } - - // m_appenderList is null when empty - if (this.m_appenderList == null) - { - return 0; - } - - if (this.m_appenderArray == null) - { - this.m_appenderArray = this.m_appenderList.ToArray(); - } - - foreach (IAppender appender in this.m_appenderArray) - { - try - { - CallAppend(appender, loggingEvents); - } - catch (Exception ex) - { - LogLog.Error(declaringType, "Failed to append to appender [" + appender.Name + "]", ex); - } - } + /// + /// Append on on all attached appenders. + /// + /// The array of events being logged. + /// The number of appenders called. + /// + /// + /// Calls the method on all + /// attached appenders. + /// + /// + public int AppendLoopOnAppenders(LoggingEvent[] loggingEvents) + { + if (loggingEvents == null) + { + throw new ArgumentNullException("loggingEvents"); + } + if (loggingEvents.Length == 0) + { + throw new ArgumentException("loggingEvents array must not be empty", "loggingEvents"); + } + if (loggingEvents.Length == 1) + { + // Fall back to single event path + return this.AppendLoopOnAppenders(loggingEvents[0]); + } - return this.m_appenderList.Count; + // m_appenderList is null when empty + if (this.m_appenderList == null) + { + return 0; + } + + if (this.m_appenderArray == null) + { + this.m_appenderArray = this.m_appenderList.ToArray(); + } + + foreach(IAppender appender in this.m_appenderArray) + { + try + { + CallAppend(appender, loggingEvents); + } + catch(Exception ex) + { + LogLog.Error(declaringType, "Failed to append to appender [" + appender.Name + "]", ex); + } + } + return this.m_appenderList.Count; } - /// - /// Calls the DoAppende method on the with - /// the objects supplied. - /// - /// The appender. - /// The events. - /// - /// - /// If the supports the - /// interface then the will be passed - /// through using that interface. Otherwise the - /// objects in the array will be passed one at a time. - /// - /// - private static void CallAppend(IAppender appender, LoggingEvent[] loggingEvents) - { - IBulkAppender bulkAppender = appender as IBulkAppender; - if (bulkAppender != null) - { - bulkAppender.DoAppend(loggingEvents); - } - else - { - foreach (LoggingEvent loggingEvent in loggingEvents) - { - appender.DoAppend(loggingEvent); - } - } + /// + /// Calls the DoAppende method on the with + /// the objects supplied. + /// + /// The appender + /// The events + /// + /// + /// If the supports the + /// interface then the will be passed + /// through using that interface. Otherwise the + /// objects in the array will be passed one at a time. + /// + /// + private static void CallAppend(IAppender appender, LoggingEvent[] loggingEvents) + { + IBulkAppender bulkAppender = appender as IBulkAppender; + if (bulkAppender != null) + { + bulkAppender.DoAppend(loggingEvents); + } + else + { + foreach(LoggingEvent loggingEvent in loggingEvents) + { + appender.DoAppend(loggingEvent); + } + } } - /// - /// Attaches an appender. - /// - /// The appender to add. - /// - /// - /// If the appender is already in the list it won't be added again. - /// - /// - public void AddAppender(IAppender newAppender) - { - // Null values for newAppender parameter are strictly forbidden. - if (newAppender == null) - { - throw new ArgumentNullException("newAppender"); - } - - this.m_appenderArray = null; - if (this.m_appenderList == null) - { - this.m_appenderList = new AppenderCollection(1); - } + /// + /// Attaches an appender. + /// + /// The appender to add. + /// + /// + /// If the appender is already in the list it won't be added again. + /// + /// + public void AddAppender(IAppender newAppender) + { + // Null values for newAppender parameter are strictly forbidden. + if (newAppender == null) + { + throw new ArgumentNullException("newAppender"); + } - if (!this.m_appenderList.Contains(newAppender)) - { - this.m_appenderList.Add(newAppender); - } - } - - /// - /// Gets all attached appenders. - /// - /// - /// A collection of attached appenders, or null if there - /// are no attached appenders. - /// - /// - /// - /// The read only collection of all currently attached appenders. - /// - /// - public AppenderCollection Appenders - { - get - { - if (this.m_appenderList == null) - { - // We must always return a valid collection - return AppenderCollection.EmptyCollection; - } - else - { - return AppenderCollection.ReadOnly(this.m_appenderList); - } - } - } - - /// - /// Gets an attached appender with the specified name. - /// - /// The name of the appender to get. - /// - /// The appender with the name specified, or null if no appender with the - /// specified name is found. - /// - /// - /// - /// Lookup an attached appender by name. - /// - /// - public IAppender GetAppender(string name) - { - if (this.m_appenderList != null && name != null) - { - foreach (IAppender appender in this.m_appenderList) - { - if (name == appender.Name) - { - return appender; - } - } - } + this.m_appenderArray = null; + if (this.m_appenderList == null) + { + this.m_appenderList = new AppenderCollection(1); + } + if (!this.m_appenderList.Contains(newAppender)) + { + this.m_appenderList.Add(newAppender); + } + } - return null; - } - - /// - /// Removes all attached appenders. - /// - /// - /// - /// Removes and closes all attached appenders. - /// - /// - public void RemoveAllAppenders() - { - if (this.m_appenderList != null) - { - foreach (IAppender appender in this.m_appenderList) - { - try - { - appender.Close(); - } - catch (Exception ex) - { - LogLog.Error(declaringType, "Failed to Close appender [" + appender.Name + "]", ex); - } - } + /// + /// Gets all attached appenders. + /// + /// + /// A collection of attached appenders, or null if there + /// are no attached appenders. + /// + /// + /// + /// The read only collection of all currently attached appenders. + /// + /// + public AppenderCollection Appenders + { + get + { + if (this.m_appenderList == null) + { + // We must always return a valid collection + return AppenderCollection.EmptyCollection; + } + else + { + return AppenderCollection.ReadOnly(this.m_appenderList); + } + } + } - this.m_appenderList = null; - this.m_appenderArray = null; - } - } - - /// - /// Removes the specified appender from the list of attached appenders. - /// - /// The appender to remove. - /// The appender removed from the list. - /// - /// - /// The appender removed is not closed. - /// If you are discarding the appender you must call - /// on the appender removed. - /// - /// - public IAppender RemoveAppender(IAppender appender) - { - if (appender != null && this.m_appenderList != null) - { - this.m_appenderList.Remove(appender); - if (this.m_appenderList.Count == 0) - { - this.m_appenderList = null; - } + /// + /// Gets an attached appender with the specified name. + /// + /// The name of the appender to get. + /// + /// The appender with the name specified, or null if no appender with the + /// specified name is found. + /// + /// + /// + /// Lookup an attached appender by name. + /// + /// + public IAppender GetAppender(string name) + { + if (this.m_appenderList != null && name != null) + { + foreach(IAppender appender in this.m_appenderList) + { + if (name == appender.Name) + { + return appender; + } + } + } + return null; + } - this.m_appenderArray = null; - } + /// + /// Removes all attached appenders. + /// + /// + /// + /// Removes and closes all attached appenders + /// + /// + public void RemoveAllAppenders() + { + if (this.m_appenderList != null) + { + foreach(IAppender appender in this.m_appenderList) + { + try + { + appender.Close(); + } + catch(Exception ex) + { + LogLog.Error(declaringType, "Failed to Close appender ["+appender.Name+"]", ex); + } + } + + this.m_appenderList = null; + this.m_appenderArray = null; + } + } + + /// + /// Removes the specified appender from the list of attached appenders. + /// + /// The appender to remove. + /// The appender removed from the list + /// + /// + /// The appender removed is not closed. + /// If you are discarding the appender you must call + /// on the appender removed. + /// + /// + public IAppender RemoveAppender(IAppender appender) + { + if (appender != null && this.m_appenderList != null) + { + this.m_appenderList.Remove(appender); + if (this.m_appenderList.Count == 0) + { + this.m_appenderList = null; + } + + this.m_appenderArray = null; + } + return appender; + } - return appender; - } - - /// - /// Removes the appender with the specified name from the list of appenders. - /// - /// The name of the appender to remove. - /// The appender removed from the list. - /// - /// - /// The appender removed is not closed. - /// If you are discarding the appender you must call - /// on the appender removed. - /// - /// - public IAppender RemoveAppender(string name) - { - return this.RemoveAppender(this.GetAppender(name)); + /// + /// Removes the appender with the specified name from the list of appenders. + /// + /// The name of the appender to remove. + /// The appender removed from the list + /// + /// + /// The appender removed is not closed. + /// If you are discarding the appender you must call + /// on the appender removed. + /// + /// + public IAppender RemoveAppender(string name) + { + return this.RemoveAppender(this.GetAppender(name)); } - /// - /// List of appenders. - /// - private AppenderCollection m_appenderList; - - /// - /// Array of appenders, used to cache the m_appenderList. - /// + /// + /// List of appenders + /// + private AppenderCollection m_appenderList; + + /// + /// Array of appenders, used to cache the m_appenderList + /// private IAppender[] m_appenderArray; - /// - /// The fully qualified type of the AppenderAttachedImpl class. - /// - /// - /// Used by the internal logger to record the Type of the - /// log message. - /// + /// + /// The fully qualified type of the AppenderAttachedImpl class. + /// + /// + /// Used by the internal logger to record the Type of the + /// log message. + /// private static readonly Type declaringType = typeof(AppenderAttachedImpl); - } -} + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/CompositeProperties.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/CompositeProperties.cs index dd58e8970b2..9db54b497cb 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/CompositeProperties.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/CompositeProperties.cs @@ -1,142 +1,140 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.Util -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; - using System.Collections; +using System; +using System.Collections; - /// - /// This class aggregates several PropertiesDictionary collections together. - /// - /// - /// - /// Provides a dictionary style lookup over an ordered list of - /// collections. - /// - /// - /// Nicko Cadell. - public sealed class CompositeProperties +namespace log4net.Util +{ + /// + /// This class aggregates several PropertiesDictionary collections together. + /// + /// + /// + /// Provides a dictionary style lookup over an ordered list of + /// collections. + /// + /// + /// Nicko Cadell + public sealed class CompositeProperties { - private PropertiesDictionary m_flattened = null; + private PropertiesDictionary m_flattened = null; private ArrayList m_nestedProperties = new ArrayList(); /// - /// Initializes a new instance of the class. - /// Constructor. - /// - /// - /// - /// Initializes a new instance of the class. - /// - /// - internal CompositeProperties() - { + /// Constructor + /// + /// + /// + /// Initializes a new instance of the class. + /// + /// + internal CompositeProperties() + { } - /// - /// Gets the value of a property. - /// - /// - /// The value for the property with the specified key. - /// - /// - /// - /// Looks up the value for the specified. - /// The collections are searched - /// in the order in which they were added to this collection. The value - /// returned is the value held by the first collection that contains - /// the specified key. - /// - /// - /// If none of the collections contain the specified key then - /// null is returned. - /// - /// - public object this[string key] - { - get - { - // Look in the flattened properties first - if (this.m_flattened != null) - { - return this.m_flattened[key]; - } - - // Look for the key in all the nested properties - foreach (ReadOnlyPropertiesDictionary cur in this.m_nestedProperties) - { - if (cur.Contains(key)) - { - return cur[key]; - } - } + /// + /// Gets the value of a property + /// + /// + /// The value for the property with the specified key + /// + /// + /// + /// Looks up the value for the specified. + /// The collections are searched + /// in the order in which they were added to this collection. The value + /// returned is the value held by the first collection that contains + /// the specified key. + /// + /// + /// If none of the collections contain the specified key then + /// null is returned. + /// + /// + public object this[string key] + { + get + { + // Look in the flattened properties first + if (this.m_flattened != null) + { + return this.m_flattened[key]; + } - return null; - } + // Look for the key in all the nested properties + foreach(ReadOnlyPropertiesDictionary cur in this.m_nestedProperties) + { + if (cur.Contains(key)) + { + return cur[key]; + } + } + return null; + } } - /// - /// Add a Properties Dictionary to this composite collection. - /// - /// the properties to add. - /// - /// - /// Properties dictionaries added first take precedence over dictionaries added - /// later. - /// - /// - public void Add(ReadOnlyPropertiesDictionary properties) - { - this.m_flattened = null; - this.m_nestedProperties.Add(properties); - } - - /// - /// Flatten this composite collection into a single properties dictionary. - /// - /// the flattened dictionary. - /// - /// - /// Reduces the collection of ordered dictionaries to a single dictionary - /// containing the resultant values for the keys. - /// - /// - public PropertiesDictionary Flatten() - { - if (this.m_flattened == null) - { - this.m_flattened = new PropertiesDictionary(); - - for (int i = this.m_nestedProperties.Count; --i >= 0;) - { - ReadOnlyPropertiesDictionary cur = (ReadOnlyPropertiesDictionary)this.m_nestedProperties[i]; - - foreach (DictionaryEntry entry in cur) - { - this.m_flattened[(string)entry.Key] = entry.Value; - } - } - } + /// + /// Add a Properties Dictionary to this composite collection + /// + /// the properties to add + /// + /// + /// Properties dictionaries added first take precedence over dictionaries added + /// later. + /// + /// + public void Add(ReadOnlyPropertiesDictionary properties) + { + this.m_flattened = null; + this.m_nestedProperties.Add(properties); + } - return this.m_flattened; + /// + /// Flatten this composite collection into a single properties dictionary + /// + /// the flattened dictionary + /// + /// + /// Reduces the collection of ordered dictionaries to a single dictionary + /// containing the resultant values for the keys. + /// + /// + public PropertiesDictionary Flatten() + { + if (this.m_flattened == null) + { + this.m_flattened = new PropertiesDictionary(); + + for(int i = this.m_nestedProperties.Count; --i >= 0; ) + { + ReadOnlyPropertiesDictionary cur = (ReadOnlyPropertiesDictionary)this.m_nestedProperties[i]; + + foreach(DictionaryEntry entry in cur) + { + this.m_flattened[(string)entry.Key] = entry.Value; + } + } + } + return this.m_flattened; } - } + } } + diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/ContextPropertiesBase.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/ContextPropertiesBase.cs index 30773457f72..fb15abc6ba4 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/ContextPropertiesBase.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/ContextPropertiesBase.cs @@ -1,50 +1,51 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.Util -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; - using System.Collections; +using System; +using System.Collections; - /// - /// Base class for Context Properties implementations. - /// - /// - /// - /// This class defines a basic property get set accessor. - /// - /// - /// Nicko Cadell. - public abstract class ContextPropertiesBase - { - /// - /// Gets or sets the value of a property. - /// - /// - /// The value for the property with the specified key. - /// - /// - /// - /// Gets or sets the value of a property. - /// - /// - public abstract object this[string key] { get; set; } - } +namespace log4net.Util +{ + /// + /// Base class for Context Properties implementations + /// + /// + /// + /// This class defines a basic property get set accessor + /// + /// + /// Nicko Cadell + public abstract class ContextPropertiesBase + { + /// + /// Gets or sets the value of a property + /// + /// + /// The value for the property with the specified key + /// + /// + /// + /// Gets or sets the value of a property + /// + /// + public abstract object this[string key] { get; set; } + } } + diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/ConverterInfo.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/ConverterInfo.cs index f89b61397db..ca28dbf39af 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/ConverterInfo.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/ConverterInfo.cs @@ -1,99 +1,93 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.Util -{ - /* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * -*/ - - using System; +using System; - /// - /// Wrapper class used to map converter names to converter types. - /// - /// - /// - /// Pattern converter info class used during configuration by custom - /// PatternString and PatternLayer converters. - /// - /// - public sealed class ConverterInfo - { - private string m_name; - private Type m_type; +namespace log4net.Util +{ + /// + /// Wrapper class used to map converter names to converter types + /// + /// + /// + /// Pattern converter info class used during configuration by custom + /// PatternString and PatternLayer converters. + /// + /// + public sealed class ConverterInfo + { + private string m_name; + private Type m_type; private readonly PropertiesDictionary properties = new PropertiesDictionary(); /// - /// Initializes a new instance of the class. - /// default constructor. - /// - public ConverterInfo() - { - } - - /// - /// Gets or sets the name of the conversion pattern. - /// - /// - /// - /// The name of the pattern in the format string. - /// - /// - public string Name - { - get { return this.m_name; } - set { this.m_name = value; } - } - - /// - /// Gets or sets the type of the converter. - /// - /// - /// - /// The value specified must extend the - /// type. - /// - /// - public Type Type - { - get { return this.m_type; } - set { this.m_type = value; } - } - - /// - /// - /// - /// - public void AddProperty(PropertyEntry entry) - { - this.properties[entry.Key] = entry.Value; - } - - /// - /// - /// - public PropertiesDictionary Properties - { - get { return this.properties; } - } - } -} + /// default constructor + /// + public ConverterInfo() + { + } + + /// + /// Gets or sets the name of the conversion pattern + /// + /// + /// + /// The name of the pattern in the format string + /// + /// + public string Name + { + get { return this.m_name; } + set { this.m_name = value; } + } + + /// + /// Gets or sets the type of the converter + /// + /// + /// + /// The value specified must extend the + /// type. + /// + /// + public Type Type + { + get { return this.m_type; } + set { this.m_type = value; } + } + + /// + /// + /// + /// + public void AddProperty(PropertyEntry entry) + { + this.properties[entry.Key] = entry.Value; + } + + /// + /// + /// + public PropertiesDictionary Properties + { + get { return this.properties; } + } + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/CountingQuietTextWriter.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/CountingQuietTextWriter.cs index 661bb2615cd..adca07f51a6 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/CountingQuietTextWriter.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/CountingQuietTextWriter.cs @@ -1,167 +1,165 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.Util -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; - using System.IO; +using System; +using System.IO; - using log4net.Core; +using log4net.Core; - /// - /// Subclass of that maintains a count of - /// the number of bytes written. - /// - /// - /// - /// This writer counts the number of bytes written. - /// - /// - /// Nicko Cadell. - /// Gert Driesen. - public class CountingQuietTextWriter : QuietTextWriter +namespace log4net.Util +{ + /// + /// Subclass of that maintains a count of + /// the number of bytes written. + /// + /// + /// + /// This writer counts the number of bytes written. + /// + /// + /// Nicko Cadell + /// Gert Driesen + public class CountingQuietTextWriter : QuietTextWriter { /// - /// Initializes a new instance of the class. - /// Constructor. - /// - /// The to actually write to. - /// The to report errors to. - /// - /// - /// Creates a new instance of the class - /// with the specified and . - /// - /// - public CountingQuietTextWriter(TextWriter writer, IErrorHandler errorHandler) - : base(writer, errorHandler) - { - this.m_countBytes = 0; + /// Constructor + /// + /// The to actually write to. + /// The to report errors to. + /// + /// + /// Creates a new instance of the class + /// with the specified and . + /// + /// + public CountingQuietTextWriter(TextWriter writer, IErrorHandler errorHandler) : base(writer, errorHandler) + { + this.m_countBytes = 0; } - /// - /// Writes a character to the underlying writer and counts the number of bytes written. - /// - /// the char to write. - /// - /// - /// Overrides implementation of . Counts - /// the number of bytes written. - /// - /// - public override void Write(char value) - { - try - { - base.Write(value); - - // get the number of bytes needed to represent the - // char using the supplied encoding. - this.m_countBytes += this.Encoding.GetByteCount(new char[] { value }); - } - catch (Exception e) - { - this.ErrorHandler.Error("Failed to write [" + value + "].", e, ErrorCode.WriteFailure); - } - } - - /// - /// Writes a buffer to the underlying writer and counts the number of bytes written. - /// - /// the buffer to write. - /// the start index to write from. - /// the number of characters to write. - /// - /// - /// Overrides implementation of . Counts - /// the number of bytes written. - /// - /// - public override void Write(char[] buffer, int index, int count) - { - if (count > 0) - { - try - { - base.Write(buffer, index, count); - - // get the number of bytes needed to represent the - // char array using the supplied encoding. - this.m_countBytes += this.Encoding.GetByteCount(buffer, index, count); - } - catch (Exception e) - { - this.ErrorHandler.Error("Failed to write buffer.", e, ErrorCode.WriteFailure); - } - } - } - - /// - /// Writes a string to the output and counts the number of bytes written. - /// - /// The string data to write to the output. - /// - /// - /// Overrides implementation of . Counts - /// the number of bytes written. - /// - /// - public override void Write(string str) - { - if (str != null && str.Length > 0) - { - try - { - base.Write(str); - - // get the number of bytes needed to represent the - // string using the supplied encoding. - this.m_countBytes += this.Encoding.GetByteCount(str); - } - catch (Exception e) - { - this.ErrorHandler.Error("Failed to write [" + str + "].", e, ErrorCode.WriteFailure); - } - } + /// + /// Writes a character to the underlying writer and counts the number of bytes written. + /// + /// the char to write + /// + /// + /// Overrides implementation of . Counts + /// the number of bytes written. + /// + /// + public override void Write(char value) + { + try + { + base.Write(value); + + // get the number of bytes needed to represent the + // char using the supplied encoding. + this.m_countBytes += this.Encoding.GetByteCount(new char[] { value }); + } + catch(Exception e) + { + this.ErrorHandler.Error("Failed to write [" + value + "].", e, ErrorCode.WriteFailure); + } } + + /// + /// Writes a buffer to the underlying writer and counts the number of bytes written. + /// + /// the buffer to write + /// the start index to write from + /// the number of characters to write + /// + /// + /// Overrides implementation of . Counts + /// the number of bytes written. + /// + /// + public override void Write(char[] buffer, int index, int count) + { + if (count > 0) + { + try + { + base.Write(buffer, index, count); - /// - /// Gets or sets the total number of bytes written. - /// - /// - /// The total number of bytes written. - /// - /// - /// - /// Gets or sets the total number of bytes written. - /// - /// - public long Count - { - get { return this.m_countBytes; } - set { this.m_countBytes = value; } + // get the number of bytes needed to represent the + // char array using the supplied encoding. + this.m_countBytes += this.Encoding.GetByteCount(buffer, index, count); + } + catch(Exception e) + { + this.ErrorHandler.Error("Failed to write buffer.", e, ErrorCode.WriteFailure); + } + } } - /// - /// Total number of bytes written. - /// + /// + /// Writes a string to the output and counts the number of bytes written. + /// + /// The string data to write to the output. + /// + /// + /// Overrides implementation of . Counts + /// the number of bytes written. + /// + /// + public override void Write(string str) + { + if (str != null && str.Length > 0) + { + try + { + base.Write(str); + + // get the number of bytes needed to represent the + // string using the supplied encoding. + this.m_countBytes += this.Encoding.GetByteCount(str); + } + catch(Exception e) + { + this.ErrorHandler.Error("Failed to write [" + str + "].", e, ErrorCode.WriteFailure); + } + } + } + + /// + /// Gets or sets the total number of bytes written. + /// + /// + /// The total number of bytes written. + /// + /// + /// + /// Gets or sets the total number of bytes written. + /// + /// + public long Count + { + get { return this.m_countBytes; } + set { this.m_countBytes = value; } + } + + /// + /// Total number of bytes written. + /// private long m_countBytes; - } -} + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/CyclicBuffer.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/CyclicBuffer.cs index 7d523893cff..b17c29664df 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/CyclicBuffer.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/CyclicBuffer.cs @@ -1,342 +1,340 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.Util -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; +using System; - using log4net.Core; +using log4net.Core; - /// - /// A fixed size rolling buffer of logging events. - /// - /// - /// - /// An array backed fixed size leaky bucket. - /// - /// - /// Nicko Cadell. - /// Gert Driesen. - public class CyclicBuffer +namespace log4net.Util +{ + /// + /// A fixed size rolling buffer of logging events. + /// + /// + /// + /// An array backed fixed size leaky bucket. + /// + /// + /// Nicko Cadell + /// Gert Driesen + public class CyclicBuffer { /// - /// Initializes a new instance of the class. - /// Constructor. - /// - /// The maximum number of logging events in the buffer. - /// - /// - /// Initializes a new instance of the class with - /// the specified maximum number of buffered logging events. - /// - /// - /// The argument is not a positive integer. - public CyclicBuffer(int maxSize) - { - if (maxSize < 1) - { - throw SystemInfo.CreateArgumentOutOfRangeException("maxSize", (object)maxSize, "Parameter: maxSize, Value: [" + maxSize + "] out of range. Non zero positive integer required"); - } - - this.m_maxSize = maxSize; - this.m_events = new LoggingEvent[maxSize]; - this.m_first = 0; - this.m_last = 0; - this.m_numElems = 0; + /// Constructor + /// + /// The maximum number of logging events in the buffer. + /// + /// + /// Initializes a new instance of the class with + /// the specified maximum number of buffered logging events. + /// + /// + /// The argument is not a positive integer. + public CyclicBuffer(int maxSize) + { + if (maxSize < 1) + { + throw SystemInfo.CreateArgumentOutOfRangeException("maxSize", (object)maxSize, "Parameter: maxSize, Value: [" + maxSize + "] out of range. Non zero positive integer required"); + } + + this.m_maxSize = maxSize; + this.m_events = new LoggingEvent[maxSize]; + this.m_first = 0; + this.m_last = 0; + this.m_numElems = 0; + } + + /// + /// Appends a to the buffer. + /// + /// The event to append to the buffer. + /// The event discarded from the buffer, if the buffer is full, otherwise null. + /// + /// + /// Append an event to the buffer. If the buffer still contains free space then + /// null is returned. If the buffer is full then an event will be dropped + /// to make space for the new event, the event dropped is returned. + /// + /// + public LoggingEvent Append(LoggingEvent loggingEvent) + { + if (loggingEvent == null) + { + throw new ArgumentNullException("loggingEvent"); + } + + lock(this) + { + // save the discarded event + LoggingEvent discardedLoggingEvent = this.m_events[this.m_last]; + + // overwrite the last event position + this.m_events[this.m_last] = loggingEvent; + if (++this.m_last == this.m_maxSize) + { + this.m_last = 0; + } + + if (this.m_numElems < this.m_maxSize) + { + this.m_numElems++; + } + else if (++this.m_first == this.m_maxSize) + { + this.m_first = 0; + } + + if (this.m_numElems < this.m_maxSize) + { + // Space remaining + return null; + } + else + { + // Buffer is full and discarding an event + return discardedLoggingEvent; + } + } + } + + /// + /// Get and remove the oldest event in the buffer. + /// + /// The oldest logging event in the buffer + /// + /// + /// Gets the oldest (first) logging event in the buffer and removes it + /// from the buffer. + /// + /// + public LoggingEvent PopOldest() + { + lock(this) + { + LoggingEvent ret = null; + if (this.m_numElems > 0) + { + this.m_numElems--; + ret = this.m_events[this.m_first]; + this.m_events[this.m_first] = null; + if (++this.m_first == this.m_maxSize) + { + this.m_first = 0; + } + } + return ret; + } + } + + /// + /// Pops all the logging events from the buffer into an array. + /// + /// An array of all the logging events in the buffer. + /// + /// + /// Get all the events in the buffer and clear the buffer. + /// + /// + public LoggingEvent[] PopAll() + { + lock(this) + { + LoggingEvent[] ret = new LoggingEvent[this.m_numElems]; + + if (this.m_numElems > 0) + { + if (this.m_first < this.m_last) + { + Array.Copy(this.m_events, this.m_first, ret, 0, this.m_numElems); + } + else + { + Array.Copy(this.m_events, this.m_first, ret, 0, this.m_maxSize - this.m_first); + Array.Copy(this.m_events, 0, ret, this.m_maxSize - this.m_first, this.m_last); + } + } + + this.Clear(); + + return ret; + } + } + + /// + /// Clear the buffer + /// + /// + /// + /// Clear the buffer of all events. The events in the buffer are lost. + /// + /// + public void Clear() + { + lock(this) + { + // Set all the elements to null + Array.Clear(this.m_events, 0, this.m_events.Length); + + this.m_first = 0; + this.m_last = 0; + this.m_numElems = 0; + } + } + +#if RESIZABLE_CYCLIC_BUFFER + /// + /// Resizes the cyclic buffer to . + /// + /// The new size of the buffer. + /// + /// + /// Resize the cyclic buffer. Events in the buffer are copied into + /// the newly sized buffer. If the buffer is shrunk and there are + /// more events currently in the buffer than the new size of the + /// buffer then the newest events will be dropped from the buffer. + /// + /// + /// The argument is not a positive integer. + public void Resize(int newSize) + { + lock(this) + { + if (newSize < 0) + { + throw log4net.Util.SystemInfo.CreateArgumentOutOfRangeException("newSize", (object)newSize, "Parameter: newSize, Value: [" + newSize + "] out of range. Non zero positive integer required"); + } + if (newSize == m_numElems) + { + return; // nothing to do + } + + LoggingEvent[] temp = new LoggingEvent[newSize]; + + int loopLen = (newSize < m_numElems) ? newSize : m_numElems; + + for(int i = 0; i < loopLen; i++) + { + temp[i] = m_events[m_first]; + m_events[m_first] = null; + + if (++m_first == m_numElems) + { + m_first = 0; + } + } + + m_events = temp; + m_first = 0; + m_numElems = loopLen; + m_maxSize = newSize; + + if (loopLen == newSize) + { + m_last = 0; + } + else + { + m_last = loopLen; + } + } } +#endif - /// - /// Appends a to the buffer. - /// - /// The event to append to the buffer. - /// The event discarded from the buffer, if the buffer is full, otherwise null. - /// - /// - /// Append an event to the buffer. If the buffer still contains free space then - /// null is returned. If the buffer is full then an event will be dropped - /// to make space for the new event, the event dropped is returned. - /// - /// - public LoggingEvent Append(LoggingEvent loggingEvent) - { - if (loggingEvent == null) - { - throw new ArgumentNullException("loggingEvent"); - } - - lock (this) - { - // save the discarded event - LoggingEvent discardedLoggingEvent = this.m_events[this.m_last]; - - // overwrite the last event position - this.m_events[this.m_last] = loggingEvent; - if (++this.m_last == this.m_maxSize) - { - this.m_last = 0; - } - - if (this.m_numElems < this.m_maxSize) - { - this.m_numElems++; - } - else if (++this.m_first == this.m_maxSize) - { - this.m_first = 0; - } - - if (this.m_numElems < this.m_maxSize) - { - // Space remaining - return null; - } - else - { - // Buffer is full and discarding an event - return discardedLoggingEvent; - } - } - } - - /// - /// Get and remove the oldest event in the buffer. - /// - /// The oldest logging event in the buffer. - /// - /// - /// Gets the oldest (first) logging event in the buffer and removes it - /// from the buffer. - /// - /// - public LoggingEvent PopOldest() - { - lock (this) - { - LoggingEvent ret = null; - if (this.m_numElems > 0) - { - this.m_numElems--; - ret = this.m_events[this.m_first]; - this.m_events[this.m_first] = null; - if (++this.m_first == this.m_maxSize) - { - this.m_first = 0; - } - } + /// + /// Gets the th oldest event currently in the buffer. + /// + /// The th oldest event currently in the buffer. + /// + /// + /// If is outside the range 0 to the number of events + /// currently in the buffer, then null is returned. + /// + /// + public LoggingEvent this[int i] + { + get + { + lock(this) + { + if (i < 0 || i >= this.m_numElems) + { + return null; + } - return ret; - } - } - - /// - /// Pops all the logging events from the buffer into an array. - /// - /// An array of all the logging events in the buffer. - /// - /// - /// Get all the events in the buffer and clear the buffer. - /// - /// - public LoggingEvent[] PopAll() - { - lock (this) - { - LoggingEvent[] ret = new LoggingEvent[this.m_numElems]; - - if (this.m_numElems > 0) - { - if (this.m_first < this.m_last) - { - Array.Copy(this.m_events, this.m_first, ret, 0, this.m_numElems); - } - else - { - Array.Copy(this.m_events, this.m_first, ret, 0, this.m_maxSize - this.m_first); - Array.Copy(this.m_events, 0, ret, this.m_maxSize - this.m_first, this.m_last); - } - } - - this.Clear(); - - return ret; - } - } - - /// - /// Clear the buffer. - /// - /// - /// - /// Clear the buffer of all events. The events in the buffer are lost. - /// - /// - public void Clear() - { - lock (this) - { - // Set all the elements to null - Array.Clear(this.m_events, 0, this.m_events.Length); - - this.m_first = 0; - this.m_last = 0; - this.m_numElems = 0; - } + return this.m_events[(this.m_first + i) % this.m_maxSize]; + } + } } -#if RESIZABLE_CYCLIC_BUFFER - /// - /// Resizes the cyclic buffer to . - /// - /// The new size of the buffer. - /// - /// - /// Resize the cyclic buffer. Events in the buffer are copied into - /// the newly sized buffer. If the buffer is shrunk and there are - /// more events currently in the buffer than the new size of the - /// buffer then the newest events will be dropped from the buffer. - /// - /// - /// The argument is not a positive integer. - public void Resize(int newSize) - { - lock(this) - { - if (newSize < 0) - { - throw log4net.Util.SystemInfo.CreateArgumentOutOfRangeException("newSize", (object)newSize, "Parameter: newSize, Value: [" + newSize + "] out of range. Non zero positive integer required"); - } - if (newSize == m_numElems) - { - return; // nothing to do - } - - LoggingEvent[] temp = new LoggingEvent[newSize]; - - int loopLen = (newSize < m_numElems) ? newSize : m_numElems; - - for(int i = 0; i < loopLen; i++) - { - temp[i] = m_events[m_first]; - m_events[m_first] = null; - - if (++m_first == m_numElems) - { - m_first = 0; - } - } - - m_events = temp; - m_first = 0; - m_numElems = loopLen; - m_maxSize = newSize; - - if (loopLen == newSize) - { - m_last = 0; - } - else - { - m_last = loopLen; - } - } - } -#endif + /// + /// Gets the maximum size of the buffer. + /// + /// The maximum size of the buffer. + /// + /// + /// Gets the maximum size of the buffer + /// + /// + public int MaxSize + { + get + { + lock(this) + { + return this.m_maxSize; + } + } +#if RESIZABLE_CYCLIC_BUFFER + set + { + /// Setting the MaxSize will cause the buffer to resize. + Resize(value); + } +#endif + } - /// - /// Gets the th oldest event currently in the buffer. - /// - /// The th oldest event currently in the buffer. - /// - /// - /// If is outside the range 0 to the number of events - /// currently in the buffer, then null is returned. - /// - /// - public LoggingEvent this[int i] - { - get - { - lock (this) - { - if (i < 0 || i >= this.m_numElems) - { - return null; - } - - return this.m_events[(this.m_first + i) % this.m_maxSize]; - } - } - } - - /// - /// Gets the maximum size of the buffer. - /// - /// The maximum size of the buffer. - /// - /// - /// Gets the maximum size of the buffer. - /// - /// - public int MaxSize - { - get - { - lock (this) - { - return this.m_maxSize; - } - } -#if RESIZABLE_CYCLIC_BUFFER - set - { - /// Setting the MaxSize will cause the buffer to resize. - Resize(value); - } -#endif - } - - /// - /// Gets the number of logging events in the buffer. - /// - /// The number of logging events in the buffer. - /// - /// - /// This number is guaranteed to be in the range 0 to - /// (inclusive). - /// - /// - public int Length - { - get - { - lock (this) - { - return this.m_numElems; - } - } + /// + /// Gets the number of logging events in the buffer. + /// + /// The number of logging events in the buffer. + /// + /// + /// This number is guaranteed to be in the range 0 to + /// (inclusive). + /// + /// + public int Length + { + get + { + lock(this) + { + return this.m_numElems; + } + } } - private LoggingEvent[] m_events; - private int m_first; - private int m_last; - private int m_numElems; + private LoggingEvent[] m_events; + private int m_first; + private int m_last; + private int m_numElems; private int m_maxSize; - } -} + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/EmptyCollection.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/EmptyCollection.cs index 46ce13f4fe9..3642a15739b 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/EmptyCollection.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/EmptyCollection.cs @@ -1,159 +1,159 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.Util -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; - using System.Collections; +using System; +using System.Collections; - /// - /// An always empty . - /// - /// - /// - /// A singleton implementation of the - /// interface that always represents an empty collection. - /// - /// - /// Nicko Cadell. - /// Gert Driesen. -#if !NETCF - [Serializable] -#endif - public sealed class EmptyCollection : ICollection +namespace log4net.Util +{ + /// + /// An always empty . + /// + /// + /// + /// A singleton implementation of the + /// interface that always represents an empty collection. + /// + /// + /// Nicko Cadell + /// Gert Driesen +#if !NETCF + [Serializable] +#endif + public sealed class EmptyCollection : ICollection { - /// - /// Initializes a new instance of the class. - /// - /// - /// - /// Uses a private access modifier to enforce the singleton pattern. - /// - /// - private EmptyCollection() - { + /// + /// Initializes a new instance of the class. + /// + /// + /// + /// Uses a private access modifier to enforce the singleton pattern. + /// + /// + private EmptyCollection() + { } - /// - /// Gets the singleton instance of the empty collection. - /// - /// The singleton instance of the empty collection. - /// - /// - /// Gets the singleton instance of the empty collection. - /// - /// - public static EmptyCollection Instance - { - get { return s_instance; } + /// + /// Gets the singleton instance of the empty collection. + /// + /// The singleton instance of the empty collection. + /// + /// + /// Gets the singleton instance of the empty collection. + /// + /// + public static EmptyCollection Instance + { + get { return s_instance; } } - /// - /// Copies the elements of the to an - /// , starting at a particular Array index. - /// - /// The one-dimensional - /// that is the destination of the elements copied from - /// . The Array must have zero-based - /// indexing. - /// The zero-based index in array at which - /// copying begins. - /// - /// - /// As the collection is empty no values are copied into the array. - /// - /// - public void CopyTo(System.Array array, int index) - { - // copy nothing - } - - /// - /// Gets a value indicating whether gets a value indicating if access to the is synchronized (thread-safe). - /// - /// - /// true if access to the is synchronized (thread-safe); otherwise, false. - /// - /// - /// - /// For the this property is always true. - /// - /// - public bool IsSynchronized - { - get { return true; } - } - - /// - /// Gets the number of elements contained in the . - /// - /// - /// The number of elements contained in the . - /// - /// - /// - /// As the collection is empty the is always 0. - /// - /// - public int Count - { - get { return 0; } - } - - /// - /// Gets an object that can be used to synchronize access to the . - /// - /// - /// An object that can be used to synchronize access to the . - /// - /// - /// - /// As the collection is empty and thread safe and synchronized this instance is also - /// the object. - /// - /// - public object SyncRoot - { - get { return this; } + /// + /// Copies the elements of the to an + /// , starting at a particular Array index. + /// + /// The one-dimensional + /// that is the destination of the elements copied from + /// . The Array must have zero-based + /// indexing. + /// The zero-based index in array at which + /// copying begins. + /// + /// + /// As the collection is empty no values are copied into the array. + /// + /// + public void CopyTo(Array array, int index) + { + // copy nothing } - /// - /// Returns an enumerator that can iterate through a collection. - /// - /// - /// An that can be used to - /// iterate through the collection. - /// - /// - /// - /// As the collection is empty a is returned. - /// - /// - public IEnumerator GetEnumerator() - { - return NullEnumerator.Instance; + /// + /// Gets a value indicating if access to the is synchronized (thread-safe). + /// + /// + /// true if access to the is synchronized (thread-safe); otherwise, false. + /// + /// + /// + /// For the this property is always true. + /// + /// + public bool IsSynchronized + { + get { return true; } } - /// - /// The singleton instance of the empty collection. - /// + /// + /// Gets the number of elements contained in the . + /// + /// + /// The number of elements contained in the . + /// + /// + /// + /// As the collection is empty the is always 0. + /// + /// + public int Count + { + get { return 0; } + } + + /// + /// Gets an object that can be used to synchronize access to the . + /// + /// + /// An object that can be used to synchronize access to the . + /// + /// + /// + /// As the collection is empty and thread safe and synchronized this instance is also + /// the object. + /// + /// + public object SyncRoot + { + get { return this; } + } + + /// + /// Returns an enumerator that can iterate through a collection. + /// + /// + /// An that can be used to + /// iterate through the collection. + /// + /// + /// + /// As the collection is empty a is returned. + /// + /// + public IEnumerator GetEnumerator() + { + return NullEnumerator.Instance; + } + + /// + /// The singleton instance of the empty collection. + /// private static readonly EmptyCollection s_instance = new EmptyCollection(); - } -} + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/EmptyDictionary.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/EmptyDictionary.cs index 50b34bf626d..73f865d71f8 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/EmptyDictionary.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/EmptyDictionary.cs @@ -1,316 +1,316 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.Util -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; - using System.Collections; +using System; +using System.Collections; - /// - /// An always empty . - /// - /// - /// - /// A singleton implementation of the - /// interface that always represents an empty collection. - /// - /// - /// Nicko Cadell. - /// Gert Driesen. -#if !NETCF - [Serializable] -#endif - public sealed class EmptyDictionary : IDictionary +namespace log4net.Util +{ + /// + /// An always empty . + /// + /// + /// + /// A singleton implementation of the + /// interface that always represents an empty collection. + /// + /// + /// Nicko Cadell + /// Gert Driesen +#if !NETCF + [Serializable] +#endif + public sealed class EmptyDictionary : IDictionary { - /// - /// Initializes a new instance of the class. - /// - /// - /// - /// Uses a private access modifier to enforce the singleton pattern. - /// - /// - private EmptyDictionary() - { + /// + /// Initializes a new instance of the class. + /// + /// + /// + /// Uses a private access modifier to enforce the singleton pattern. + /// + /// + private EmptyDictionary() + { } - /// - /// Gets the singleton instance of the . - /// - /// The singleton instance of the . - /// - /// - /// Gets the singleton instance of the . - /// - /// - public static EmptyDictionary Instance - { - get { return s_instance; } + /// + /// Gets the singleton instance of the . + /// + /// The singleton instance of the . + /// + /// + /// Gets the singleton instance of the . + /// + /// + public static EmptyDictionary Instance + { + get { return s_instance; } } - /// - /// Copies the elements of the to an - /// , starting at a particular Array index. - /// - /// The one-dimensional - /// that is the destination of the elements copied from - /// . The Array must have zero-based - /// indexing. - /// The zero-based index in array at which - /// copying begins. - /// - /// - /// As the collection is empty no values are copied into the array. - /// - /// - public void CopyTo(System.Array array, int index) - { - // copy nothing - } - - /// - /// Gets a value indicating whether gets a value indicating if access to the is synchronized (thread-safe). - /// - /// - /// true if access to the is synchronized (thread-safe); otherwise, false. - /// - /// - /// - /// For the this property is always true. - /// - /// - public bool IsSynchronized - { - get { return true; } - } - - /// - /// Gets the number of elements contained in the . - /// - /// - /// The number of elements contained in the . - /// - /// - /// - /// As the collection is empty the is always 0. - /// - /// - public int Count - { - get { return 0; } - } - - /// - /// Gets an object that can be used to synchronize access to the . - /// - /// - /// An object that can be used to synchronize access to the . - /// - /// - /// - /// As the collection is empty and thread safe and synchronized this instance is also - /// the object. - /// - /// - public object SyncRoot - { - get { return this; } + /// + /// Copies the elements of the to an + /// , starting at a particular Array index. + /// + /// The one-dimensional + /// that is the destination of the elements copied from + /// . The Array must have zero-based + /// indexing. + /// The zero-based index in array at which + /// copying begins. + /// + /// + /// As the collection is empty no values are copied into the array. + /// + /// + public void CopyTo(Array array, int index) + { + // copy nothing } - /// - /// Returns an enumerator that can iterate through a collection. - /// - /// - /// An that can be used to - /// iterate through the collection. - /// - /// - /// - /// As the collection is empty a is returned. - /// - /// - IEnumerator IEnumerable.GetEnumerator() - { - return NullEnumerator.Instance; + /// + /// Gets a value indicating if access to the is synchronized (thread-safe). + /// + /// + /// true if access to the is synchronized (thread-safe); otherwise, false. + /// + /// + /// + /// For the this property is always true. + /// + /// + public bool IsSynchronized + { + get { return true; } } - /// - /// Adds an element with the provided key and value to the - /// . - /// - /// The to use as the key of the element to add. - /// The to use as the value of the element to add. - /// - /// - /// As the collection is empty no new values can be added. A - /// is thrown if this method is called. - /// - /// - /// This dictionary is always empty and cannot be modified. - public void Add(object key, object value) - { - throw new InvalidOperationException(); - } - - /// - /// Removes all elements from the . - /// - /// - /// - /// As the collection is empty no values can be removed. A - /// is thrown if this method is called. - /// - /// - /// This dictionary is always empty and cannot be modified. - public void Clear() - { - throw new InvalidOperationException(); - } - - /// - /// Determines whether the contains an element - /// with the specified key. - /// - /// The key to locate in the . - /// false. - /// - /// - /// As the collection is empty the method always returns false. - /// - /// - public bool Contains(object key) - { - return false; - } - - /// - /// Returns an enumerator that can iterate through a collection. - /// - /// - /// An that can be used to - /// iterate through the collection. - /// - /// - /// - /// As the collection is empty a is returned. - /// - /// - public IDictionaryEnumerator GetEnumerator() - { - return NullDictionaryEnumerator.Instance; - } - - /// - /// Removes the element with the specified key from the . - /// - /// The key of the element to remove. - /// - /// - /// As the collection is empty no values can be removed. A - /// is thrown if this method is called. - /// - /// - /// This dictionary is always empty and cannot be modified. - public void Remove(object key) - { - throw new InvalidOperationException(); - } - - /// - /// Gets a value indicating whether the has a fixed size. - /// - /// true. - /// - /// - /// As the collection is empty always returns true. - /// - /// - public bool IsFixedSize - { - get { return true; } - } - - /// - /// Gets a value indicating whether the is read-only. - /// - /// true. - /// - /// - /// As the collection is empty always returns true. - /// - /// - public bool IsReadOnly - { - get { return true; } - } - - /// - /// Gets an containing the keys of the . - /// - /// An containing the keys of the . - /// - /// - /// As the collection is empty a is returned. - /// - /// - public System.Collections.ICollection Keys - { - get { return EmptyCollection.Instance; } - } - - /// - /// Gets an containing the values of the . - /// - /// An containing the values of the . - /// - /// - /// As the collection is empty a is returned. - /// - /// - public System.Collections.ICollection Values - { - get { return EmptyCollection.Instance; } - } - - /// - /// Gets or sets the element with the specified key. - /// - /// The key of the element to get or set. - /// null. - /// - /// - /// As the collection is empty no values can be looked up or stored. - /// If the index getter is called then null is returned. - /// A is thrown if the setter is called. - /// - /// - /// This dictionary is always empty and cannot be modified. - public object this[object key] - { - get { return null; } - set { throw new InvalidOperationException(); } + /// + /// Gets the number of elements contained in the + /// + /// + /// The number of elements contained in the . + /// + /// + /// + /// As the collection is empty the is always 0. + /// + /// + public int Count + { + get { return 0; } } - /// - /// The singleton instance of the empty dictionary. - /// + /// + /// Gets an object that can be used to synchronize access to the . + /// + /// + /// An object that can be used to synchronize access to the . + /// + /// + /// + /// As the collection is empty and thread safe and synchronized this instance is also + /// the object. + /// + /// + public object SyncRoot + { + get { return this; } + } + + /// + /// Returns an enumerator that can iterate through a collection. + /// + /// + /// An that can be used to + /// iterate through the collection. + /// + /// + /// + /// As the collection is empty a is returned. + /// + /// + IEnumerator IEnumerable.GetEnumerator() + { + return NullEnumerator.Instance; + } + + /// + /// Adds an element with the provided key and value to the + /// . + /// + /// The to use as the key of the element to add. + /// The to use as the value of the element to add. + /// + /// + /// As the collection is empty no new values can be added. A + /// is thrown if this method is called. + /// + /// + /// This dictionary is always empty and cannot be modified. + public void Add(object key, object value) + { + throw new InvalidOperationException(); + } + + /// + /// Removes all elements from the . + /// + /// + /// + /// As the collection is empty no values can be removed. A + /// is thrown if this method is called. + /// + /// + /// This dictionary is always empty and cannot be modified. + public void Clear() + { + throw new InvalidOperationException(); + } + + /// + /// Determines whether the contains an element + /// with the specified key. + /// + /// The key to locate in the . + /// false + /// + /// + /// As the collection is empty the method always returns false. + /// + /// + public bool Contains(object key) + { + return false; + } + + /// + /// Returns an enumerator that can iterate through a collection. + /// + /// + /// An that can be used to + /// iterate through the collection. + /// + /// + /// + /// As the collection is empty a is returned. + /// + /// + public IDictionaryEnumerator GetEnumerator() + { + return NullDictionaryEnumerator.Instance; + } + + /// + /// Removes the element with the specified key from the . + /// + /// The key of the element to remove. + /// + /// + /// As the collection is empty no values can be removed. A + /// is thrown if this method is called. + /// + /// + /// This dictionary is always empty and cannot be modified. + public void Remove(object key) + { + throw new InvalidOperationException(); + } + + /// + /// Gets a value indicating whether the has a fixed size. + /// + /// true + /// + /// + /// As the collection is empty always returns true. + /// + /// + public bool IsFixedSize + { + get { return true; } + } + + /// + /// Gets a value indicating whether the is read-only. + /// + /// true + /// + /// + /// As the collection is empty always returns true. + /// + /// + public bool IsReadOnly + { + get { return true; } + } + + /// + /// Gets an containing the keys of the . + /// + /// An containing the keys of the . + /// + /// + /// As the collection is empty a is returned. + /// + /// + public ICollection Keys + { + get { return EmptyCollection.Instance; } + } + + /// + /// Gets an containing the values of the . + /// + /// An containing the values of the . + /// + /// + /// As the collection is empty a is returned. + /// + /// + public ICollection Values + { + get { return EmptyCollection.Instance; } + } + + /// + /// Gets or sets the element with the specified key. + /// + /// The key of the element to get or set. + /// null + /// + /// + /// As the collection is empty no values can be looked up or stored. + /// If the index getter is called then null is returned. + /// A is thrown if the setter is called. + /// + /// + /// This dictionary is always empty and cannot be modified. + public object this[object key] + { + get { return null; } + set { throw new InvalidOperationException(); } + } + + /// + /// The singleton instance of the empty dictionary. + /// private static readonly EmptyDictionary s_instance = new EmptyDictionary(); - } -} + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/FormattingInfo.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/FormattingInfo.cs index 3eb6aa38a86..8b4b893c2d3 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/FormattingInfo.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/FormattingInfo.cs @@ -1,128 +1,125 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.Util -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; +using System; +using log4net.Util; - using log4net.Util; - - /// - /// Contain the information obtained when parsing formatting modifiers - /// in conversion modifiers. - /// - /// - /// - /// Holds the formatting information extracted from the format string by - /// the . This is used by the - /// objects when rendering the output. - /// - /// - /// Nicko Cadell. - /// Gert Driesen. - public class FormattingInfo +namespace log4net.Util +{ + /// + /// Contain the information obtained when parsing formatting modifiers + /// in conversion modifiers. + /// + /// + /// + /// Holds the formatting information extracted from the format string by + /// the . This is used by the + /// objects when rendering the output. + /// + /// + /// Nicko Cadell + /// Gert Driesen + public class FormattingInfo { /// - /// Initializes a new instance of the class. - /// Defaut Constructor. - /// - /// - /// - /// Initializes a new instance of the class. - /// - /// - public FormattingInfo() - { + /// Defaut Constructor + /// + /// + /// + /// Initializes a new instance of the class. + /// + /// + public FormattingInfo() + { + } + + /// + /// Constructor + /// + /// + /// + /// Initializes a new instance of the class + /// with the specified parameters. + /// + /// + public FormattingInfo(int min, int max, bool leftAlign) + { + this.m_min = min; + this.m_max = max; + this.m_leftAlign = leftAlign; } /// - /// Initializes a new instance of the class. - /// Constructor. - /// - /// - /// - /// Initializes a new instance of the class - /// with the specified parameters. - /// - /// - public FormattingInfo(int min, int max, bool leftAlign) - { - this.m_min = min; - this.m_max = max; - this.m_leftAlign = leftAlign; + /// Gets or sets the minimum value. + /// + /// + /// The minimum value. + /// + /// + /// + /// Gets or sets the minimum value. + /// + /// + public int Min + { + get { return this.m_min; } + set { this.m_min = value; } } - /// - /// Gets or sets the minimum value. - /// - /// - /// The minimum value. - /// - /// - /// - /// Gets or sets the minimum value. - /// - /// - public int Min - { - get { return this.m_min; } - set { this.m_min = value; } - } - - /// - /// Gets or sets the maximum value. - /// - /// - /// The maximum value. - /// - /// - /// - /// Gets or sets the maximum value. - /// - /// - public int Max - { - get { return this.m_max; } - set { this.m_max = value; } - } - - /// - /// Gets or sets a value indicating whether gets or sets a flag indicating whether left align is enabled - /// or not. - /// - /// - /// A flag indicating whether left align is enabled or not. - /// - /// - /// - /// Gets or sets a flag indicating whether left align is enabled or not. - /// - /// - public bool LeftAlign - { - get { return this.m_leftAlign; } - set { this.m_leftAlign = value; } + /// + /// Gets or sets the maximum value. + /// + /// + /// The maximum value. + /// + /// + /// + /// Gets or sets the maximum value. + /// + /// + public int Max + { + get { return this.m_max; } + set { this.m_max = value; } + } + + /// + /// Gets or sets a flag indicating whether left align is enabled + /// or not. + /// + /// + /// A flag indicating whether left align is enabled or not. + /// + /// + /// + /// Gets or sets a flag indicating whether left align is enabled or not. + /// + /// + public bool LeftAlign + { + get { return this.m_leftAlign; } + set { this.m_leftAlign = value; } } - private int m_min = -1; - private int m_max = int.MaxValue; + private int m_min = -1; + private int m_max = int.MaxValue; private bool m_leftAlign = false; - } -} + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/GlobalContextProperties.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/GlobalContextProperties.cs index 7da9da0dd3a..b293803d245 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/GlobalContextProperties.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/GlobalContextProperties.cs @@ -1,159 +1,158 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.Util -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; - using System.Collections; +using System; +using System.Collections; - /// - /// Implementation of Properties collection for the . - /// - /// - /// - /// This class implements a properties collection that is thread safe and supports both - /// storing properties and capturing a read only copy of the current propertied. - /// - /// - /// This class is optimized to the scenario where the properties are read frequently - /// and are modified infrequently. - /// - /// - /// Nicko Cadell. - public sealed class GlobalContextProperties : ContextPropertiesBase +namespace log4net.Util +{ + /// + /// Implementation of Properties collection for the + /// + /// + /// + /// This class implements a properties collection that is thread safe and supports both + /// storing properties and capturing a read only copy of the current propertied. + /// + /// + /// This class is optimized to the scenario where the properties are read frequently + /// and are modified infrequently. + /// + /// + /// Nicko Cadell + public sealed class GlobalContextProperties : ContextPropertiesBase { - /// - /// The read only copy of the properties. - /// - /// - /// - /// This variable is declared volatile to prevent the compiler and JIT from - /// reordering reads and writes of this thread performed on different threads. - /// - /// -#if NETCF - private ReadOnlyPropertiesDictionary m_readOnlyProperties = new ReadOnlyPropertiesDictionary(); -#else - private volatile ReadOnlyPropertiesDictionary m_readOnlyProperties = new ReadOnlyPropertiesDictionary(); -#endif - - /// - /// Lock object used to synchronize updates within this instance. - /// + /// + /// The read only copy of the properties. + /// + /// + /// + /// This variable is declared volatile to prevent the compiler and JIT from + /// reordering reads and writes of this thread performed on different threads. + /// + /// +#if NETCF + private ReadOnlyPropertiesDictionary m_readOnlyProperties = new ReadOnlyPropertiesDictionary(); +#else + private volatile ReadOnlyPropertiesDictionary m_readOnlyProperties = new ReadOnlyPropertiesDictionary(); +#endif + + /// + /// Lock object used to synchronize updates within this instance + /// private readonly object m_syncRoot = new object(); /// - /// Initializes a new instance of the class. - /// Constructor. - /// - /// - /// - /// Initializes a new instance of the class. - /// - /// - internal GlobalContextProperties() - { + /// Constructor + /// + /// + /// + /// Initializes a new instance of the class. + /// + /// + internal GlobalContextProperties() + { } - /// - /// Gets or sets the value of a property. - /// - /// - /// The value for the property with the specified key. - /// - /// - /// - /// Reading the value for a key is faster than setting the value. - /// When the value is written a new read only copy of - /// the properties is created. - /// - /// - public override object this[string key] - { - get - { - return this.m_readOnlyProperties[key]; - } + /// + /// Gets or sets the value of a property + /// + /// + /// The value for the property with the specified key + /// + /// + /// + /// Reading the value for a key is faster than setting the value. + /// When the value is written a new read only copy of + /// the properties is created. + /// + /// + public override object this[string key] + { + get + { + return this.m_readOnlyProperties[key]; + } + set + { + lock(this.m_syncRoot) + { + PropertiesDictionary mutableProps = new PropertiesDictionary(this.m_readOnlyProperties); - set - { - lock (this.m_syncRoot) - { - PropertiesDictionary mutableProps = new PropertiesDictionary(this.m_readOnlyProperties); - - mutableProps[key] = value; - - this.m_readOnlyProperties = new ReadOnlyPropertiesDictionary(mutableProps); - } - } + mutableProps[key] = value; + + this.m_readOnlyProperties = new ReadOnlyPropertiesDictionary(mutableProps); + } + } } - /// - /// Remove a property from the global context. - /// - /// the key for the entry to remove. - /// - /// - /// Removing an entry from the global context properties is relatively expensive compared - /// with reading a value. - /// - /// - public void Remove(string key) - { - lock (this.m_syncRoot) - { - if (this.m_readOnlyProperties.Contains(key)) - { - PropertiesDictionary mutableProps = new PropertiesDictionary(this.m_readOnlyProperties); - - mutableProps.Remove(key); - - this.m_readOnlyProperties = new ReadOnlyPropertiesDictionary(mutableProps); - } - } - } - - /// - /// Clear the global context properties. - /// - public void Clear() - { - lock (this.m_syncRoot) - { - this.m_readOnlyProperties = new ReadOnlyPropertiesDictionary(); - } + /// + /// Remove a property from the global context + /// + /// the key for the entry to remove + /// + /// + /// Removing an entry from the global context properties is relatively expensive compared + /// with reading a value. + /// + /// + public void Remove(string key) + { + lock(this.m_syncRoot) + { + if (this.m_readOnlyProperties.Contains(key)) + { + PropertiesDictionary mutableProps = new PropertiesDictionary(this.m_readOnlyProperties); + + mutableProps.Remove(key); + + this.m_readOnlyProperties = new ReadOnlyPropertiesDictionary(mutableProps); + } + } + } + + /// + /// Clear the global context properties + /// + public void Clear() + { + lock(this.m_syncRoot) + { + this.m_readOnlyProperties = new ReadOnlyPropertiesDictionary(); + } } - /// - /// Get a readonly immutable copy of the properties. - /// - /// the current global context properties. - /// - /// - /// This implementation is fast because the GlobalContextProperties class - /// stores a readonly copy of the properties. - /// - /// - internal ReadOnlyPropertiesDictionary GetReadOnlyProperties() - { - return this.m_readOnlyProperties; + /// + /// Get a readonly immutable copy of the properties + /// + /// the current global context properties + /// + /// + /// This implementation is fast because the GlobalContextProperties class + /// stores a readonly copy of the properties. + /// + /// + internal ReadOnlyPropertiesDictionary GetReadOnlyProperties() + { + return this.m_readOnlyProperties; } - } + } } + diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/ILogExtensions.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/ILogExtensions.cs index b748a823931..4da4f8f137b 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/ILogExtensions.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/ILogExtensions.cs @@ -1,1748 +1,1748 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#if NET_3_5 || NET_4_0 || MONO_3_5 || MONO_4_0 || NETSTANDARD1_3 - -using System; - -using log4net.Core; - -namespace log4net.Util -{ - /// - /// The static class ILogExtensions contains a set of widely used - /// methods that ease the interaction with the ILog interface implementations. - /// - /// - /// - /// This class contains methods for logging at different levels and checks the - /// properties for determining if those logging levels are enabled in the current - /// configuration. - /// - /// - /// Simple example of logging messages. - /// - /// using log4net.Util; - /// - /// ILog log = LogManager.GetLogger("application-log"); - /// - /// log.InfoExt("Application Start"); - /// log.DebugExt("This is a debug message"); - /// - /// - public static class ILogExtensions +#if NET_3_5 || NET_4_0 || MONO_3_5 || MONO_4_0 || NETSTANDARD + +using System; + +using log4net.Core; + +namespace log4net.Util +{ + /// + /// The static class ILogExtensions contains a set of widely used + /// methods that ease the interaction with the ILog interface implementations. + /// + /// + /// + /// This class contains methods for logging at different levels and checks the + /// properties for determining if those logging levels are enabled in the current + /// configuration. + /// + /// + /// Simple example of logging messages + /// + /// using log4net.Util; + /// + /// ILog log = LogManager.GetLogger("application-log"); + /// + /// log.InfoExt("Application Start"); + /// log.DebugExt("This is a debug message"); + /// + /// + public static class ILogExtensions { - /// - /// The fully qualified type of the Logger class. - /// + /// + /// The fully qualified type of the Logger class. + /// private static readonly Type declaringType = typeof(ILogExtensions); - /// - /// Log a message object with the level. - /// - /// The logger on which the message is logged. - /// The lambda expression that gets the object to log. - /// - /// - /// This method first checks if this logger is INFO - /// enabled by reading the value property. - /// This check happens always and does not depend on the - /// implementation. If this logger is INFO enabled, then it converts - /// the message object (retrieved by invocation of the provided callback) to a - /// string by invoking the appropriate . - /// It then proceeds to call all the registered appenders in this logger - /// and also higher in the hierarchy depending on the value of - /// the additivity flag. - /// - /// WARNING Note that passing an - /// to this method will print the name of the - /// but no stack trace. To print a stack trace use the - /// form instead. - /// - /// - /// - /// - public static void DebugExt(this ILog logger, Func callback) - { - try - { + /// + /// Log a message object with the level. + /// + /// The logger on which the message is logged. + /// The lambda expression that gets the object to log. + /// + /// + /// This method first checks if this logger is INFO + /// enabled by reading the value property. + /// This check happens always and does not depend on the + /// implementation. If this logger is INFO enabled, then it converts + /// the message object (retrieved by invocation of the provided callback) to a + /// string by invoking the appropriate . + /// It then proceeds to call all the registered appenders in this logger + /// and also higher in the hierarchy depending on the value of + /// the additivity flag. + /// + /// WARNING Note that passing an + /// to this method will print the name of the + /// but no stack trace. To print a stack trace use the + /// form instead. + /// + /// + /// + /// + public static void DebugExt(this ILog logger, Func callback) + { + try + { if (!logger.IsDebugEnabled) { return; } - logger.Debug(callback()); - } - catch (Exception ex) - { - log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); - } - } - - /// - /// Log a message object with the level including - /// the stack trace of the passed - /// as a parameter. - /// - /// The logger on which the message is logged. - /// The lambda expression that gets the object to log. - /// The exception to log, including its stack trace. - /// - /// - /// See the form for more detailed information. - /// - /// - /// - /// - public static void DebugExt(this ILog logger, Func callback, Exception exception) - { - try - { + logger.Debug(callback()); + } + catch (Exception ex) + { + LogLog.Error(declaringType, "Exception while logging", ex); + } + } + + /// + /// Log a message object with the level including + /// the stack trace of the passed + /// as a parameter. + /// + /// The logger on which the message is logged. + /// The lambda expression that gets the object to log. + /// The exception to log, including its stack trace. + /// + /// + /// See the form for more detailed information. + /// + /// + /// + /// + public static void DebugExt(this ILog logger, Func callback, Exception exception) + { + try + { if (!logger.IsDebugEnabled) { return; } - logger.Debug(callback(), exception); - } - catch (Exception ex) - { - log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); - } + logger.Debug(callback(), exception); + } + catch (Exception ex) + { + LogLog.Error(declaringType, "Exception while logging", ex); + } } - /// Log a message object with the level. //TODO - /// - /// Log a message object with the level. - /// - /// The logger on which the message is logged. - /// The message object to log. - /// - /// - /// This method first checks if this logger is INFO - /// enabled by reading the value property. - /// This check happens always and does not depend on the - /// implementation. If this logger is INFO enabled, then it converts - /// the message object (passed as parameter) to a string by invoking the appropriate - /// . It then - /// proceeds to call all the registered appenders in this logger - /// and also higher in the hierarchy depending on the value of - /// the additivity flag. - /// - /// WARNING Note that passing an - /// to this method will print the name of the - /// but no stack trace. To print a stack trace use the - /// form instead. - /// - /// - /// - /// - public static void DebugExt(this ILog logger, object message) - { - try - { + /// Log a message object with the level. //TODO + /// + /// Log a message object with the level. + /// + /// The logger on which the message is logged. + /// The message object to log. + /// + /// + /// This method first checks if this logger is INFO + /// enabled by reading the value property. + /// This check happens always and does not depend on the + /// implementation. If this logger is INFO enabled, then it converts + /// the message object (passed as parameter) to a string by invoking the appropriate + /// . It then + /// proceeds to call all the registered appenders in this logger + /// and also higher in the hierarchy depending on the value of + /// the additivity flag. + /// + /// WARNING Note that passing an + /// to this method will print the name of the + /// but no stack trace. To print a stack trace use the + /// form instead. + /// + /// + /// + /// + public static void DebugExt(this ILog logger, object message) + { + try + { if (!logger.IsDebugEnabled) { return; } - logger.Debug(message); - } - catch (Exception ex) - { - log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); - } - } - - /// - /// Log a message object with the level including - /// the stack trace of the passed - /// as a parameter. - /// - /// The logger on which the message is logged. - /// The message object to log. - /// The exception to log, including its stack trace. - /// - /// - /// See the form for more detailed information. - /// - /// - /// - /// - public static void DebugExt(this ILog logger, object message, Exception exception) - { - try - { + logger.Debug(message); + } + catch (Exception ex) + { + LogLog.Error(declaringType, "Exception while logging", ex); + } + } + + /// + /// Log a message object with the level including + /// the stack trace of the passed + /// as a parameter. + /// + /// The logger on which the message is logged. + /// The message object to log. + /// The exception to log, including its stack trace. + /// + /// + /// See the form for more detailed information. + /// + /// + /// + /// + public static void DebugExt(this ILog logger, object message, Exception exception) + { + try + { if (!logger.IsDebugEnabled) { return; } - logger.Debug(message, exception); - } - catch (Exception ex) - { - log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); - } + logger.Debug(message, exception); + } + catch (Exception ex) + { + LogLog.Error(declaringType, "Exception while logging", ex); + } } - /// - /// Logs a formatted message string with the level. - /// - /// The logger on which the message is logged. - /// A String containing zero or more format items. - /// An Object to format. - /// - /// - /// The message is formatted using the String.Format method. See - /// for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - /// - /// - public static void DebugFormatExt(this ILog logger, string format, object arg0) - { - try - { + /// + /// Logs a formatted message string with the level. + /// + /// The logger on which the message is logged. + /// A String containing zero or more format items + /// An Object to format + /// + /// + /// The message is formatted using the String.Format method. See + /// for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + /// + /// + public static void DebugFormatExt(this ILog logger, string format, object arg0) + { + try + { if (!logger.IsDebugEnabled) { return; } - logger.DebugFormat(format, arg0); - } - catch (Exception ex) - { - log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); - } - } - - /// - /// Logs a formatted message string with the level. - /// - /// The logger on which the message is logged. - /// A String containing zero or more format items. - /// An Object array containing zero or more objects to format. - /// - /// - /// The message is formatted using the String.Format method. See - /// for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - /// - /// - public static void DebugFormatExt(this ILog logger, string format, params object[] args) - { - try - { + logger.DebugFormat(format, arg0); + } + catch (Exception ex) + { + LogLog.Error(declaringType, "Exception while logging", ex); + } + } + + /// + /// Logs a formatted message string with the level. + /// + /// The logger on which the message is logged. + /// A String containing zero or more format items + /// An Object array containing zero or more objects to format + /// + /// + /// The message is formatted using the String.Format method. See + /// for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + /// + /// + public static void DebugFormatExt(this ILog logger, string format, params object[] args) + { + try + { if (!logger.IsDebugEnabled) { return; } - logger.DebugFormat(format, args); - } - catch (Exception ex) - { - log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); - } - } - - /// - /// Logs a formatted message string with the level. - /// - /// An that supplies culture-specific formatting information. - /// The logger on which the message is logged. - /// A String containing zero or more format items. - /// An Object array containing zero or more objects to format. - /// - /// - /// The message is formatted using the String.Format method. See - /// for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - /// - /// - public static void DebugFormatExt(this ILog logger, IFormatProvider provider, string format, params object[] args) - { - try - { + logger.DebugFormat(format, args); + } + catch (Exception ex) + { + LogLog.Error(declaringType, "Exception while logging", ex); + } + } + + /// + /// Logs a formatted message string with the level. + /// + /// An that supplies culture-specific formatting information + /// The logger on which the message is logged. + /// A String containing zero or more format items + /// An Object array containing zero or more objects to format + /// + /// + /// The message is formatted using the String.Format method. See + /// for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + /// + /// + public static void DebugFormatExt(this ILog logger, IFormatProvider provider, string format, params object[] args) + { + try + { if (!logger.IsDebugEnabled) { return; } - logger.DebugFormat(provider, format, args); - } - catch (Exception ex) - { - log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); - } - } - - /// - /// Logs a formatted message string with the level. - /// - /// The logger on which the message is logged. - /// A String containing zero or more format items. - /// An Object to format. - /// An Object to format. - /// - /// - /// The message is formatted using the String.Format method. See - /// for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - /// - /// - public static void DebugFormatExt(this ILog logger, string format, object arg0, object arg1) - { - try - { + logger.DebugFormat(provider, format, args); + } + catch (Exception ex) + { + LogLog.Error(declaringType, "Exception while logging", ex); + } + } + + /// + /// Logs a formatted message string with the level. + /// + /// The logger on which the message is logged. + /// A String containing zero or more format items + /// An Object to format + /// An Object to format + /// + /// + /// The message is formatted using the String.Format method. See + /// for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + /// + /// + public static void DebugFormatExt(this ILog logger, string format, object arg0, object arg1) + { + try + { if (!logger.IsDebugEnabled) { return; } - logger.DebugFormat(format, arg0, arg1); - } - catch (Exception ex) - { - log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); - } - } - - /// - /// Logs a formatted message string with the level. - /// - /// The logger on which the message is logged. - /// A String containing zero or more format items. - /// An Object to format. - /// An Object to format. - /// An Object to format. - /// - /// - /// The message is formatted using the String.Format method. See - /// for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - /// - /// - public static void DebugFormatExt(this ILog logger, string format, object arg0, object arg1, object arg2) - { - try - { + logger.DebugFormat(format, arg0, arg1); + } + catch (Exception ex) + { + LogLog.Error(declaringType, "Exception while logging", ex); + } + } + + /// + /// Logs a formatted message string with the level. + /// + /// The logger on which the message is logged. + /// A String containing zero or more format items + /// An Object to format + /// An Object to format + /// An Object to format + /// + /// + /// The message is formatted using the String.Format method. See + /// for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + /// + /// + public static void DebugFormatExt(this ILog logger, string format, object arg0, object arg1, object arg2) + { + try + { if (!logger.IsDebugEnabled) { return; } - logger.DebugFormat(format, arg0, arg1, arg2); - } - catch (Exception ex) - { - log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); - } + logger.DebugFormat(format, arg0, arg1, arg2); + } + catch (Exception ex) + { + LogLog.Error(declaringType, "Exception while logging", ex); + } } - /// - /// Log a message object with the level. - /// - /// The logger on which the message is logged. - /// The lambda expression that gets the object to log. - /// - /// - /// This method first checks if this logger is INFO - /// enabled by reading the value property. - /// This check happens always and does not depend on the - /// implementation. If this logger is INFO enabled, then it converts - /// the message object (retrieved by invocation of the provided callback) to a - /// string by invoking the appropriate . - /// It then proceeds to call all the registered appenders in this logger - /// and also higher in the hierarchy depending on the value of - /// the additivity flag. - /// - /// WARNING Note that passing an - /// to this method will print the name of the - /// but no stack trace. To print a stack trace use the - /// form instead. - /// - /// - /// - /// - public static void InfoExt(this ILog logger, Func callback) - { - try - { + /// + /// Log a message object with the level. + /// + /// The logger on which the message is logged. + /// The lambda expression that gets the object to log. + /// + /// + /// This method first checks if this logger is INFO + /// enabled by reading the value property. + /// This check happens always and does not depend on the + /// implementation. If this logger is INFO enabled, then it converts + /// the message object (retrieved by invocation of the provided callback) to a + /// string by invoking the appropriate . + /// It then proceeds to call all the registered appenders in this logger + /// and also higher in the hierarchy depending on the value of + /// the additivity flag. + /// + /// WARNING Note that passing an + /// to this method will print the name of the + /// but no stack trace. To print a stack trace use the + /// form instead. + /// + /// + /// + /// + public static void InfoExt(this ILog logger, Func callback) + { + try + { if (!logger.IsInfoEnabled) { return; } - logger.Info(callback()); - } - catch (Exception ex) - { - log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); - } - } - - /// - /// Log a message object with the level including - /// the stack trace of the passed - /// as a parameter. - /// - /// The logger on which the message is logged. - /// The lambda expression that gets the object to log. - /// The exception to log, including its stack trace. - /// - /// - /// See the form for more detailed information. - /// - /// - /// - /// - public static void InfoExt(this ILog logger, Func callback, Exception exception) - { - try - { + logger.Info(callback()); + } + catch (Exception ex) + { + LogLog.Error(declaringType, "Exception while logging", ex); + } + } + + /// + /// Log a message object with the level including + /// the stack trace of the passed + /// as a parameter. + /// + /// The logger on which the message is logged. + /// The lambda expression that gets the object to log. + /// The exception to log, including its stack trace. + /// + /// + /// See the form for more detailed information. + /// + /// + /// + /// + public static void InfoExt(this ILog logger, Func callback, Exception exception) + { + try + { if (!logger.IsInfoEnabled) { return; } - logger.Info(callback(), exception); - } - catch (Exception ex) - { - log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); - } + logger.Info(callback(), exception); + } + catch (Exception ex) + { + LogLog.Error(declaringType, "Exception while logging", ex); + } } - /// Log a message object with the level. //TODO - /// - /// Log a message object with the level. - /// - /// The logger on which the message is logged. - /// The message object to log. - /// - /// - /// This method first checks if this logger is INFO - /// enabled by reading the value property. - /// This check happens always and does not depend on the - /// implementation. If this logger is INFO enabled, then it converts - /// the message object (passed as parameter) to a string by invoking the appropriate - /// . It then - /// proceeds to call all the registered appenders in this logger - /// and also higher in the hierarchy depending on the value of - /// the additivity flag. - /// - /// WARNING Note that passing an - /// to this method will print the name of the - /// but no stack trace. To print a stack trace use the - /// form instead. - /// - /// - /// - /// - public static void InfoExt(this ILog logger, object message) - { - try - { + /// Log a message object with the level. //TODO + /// + /// Log a message object with the level. + /// + /// The logger on which the message is logged. + /// The message object to log. + /// + /// + /// This method first checks if this logger is INFO + /// enabled by reading the value property. + /// This check happens always and does not depend on the + /// implementation. If this logger is INFO enabled, then it converts + /// the message object (passed as parameter) to a string by invoking the appropriate + /// . It then + /// proceeds to call all the registered appenders in this logger + /// and also higher in the hierarchy depending on the value of + /// the additivity flag. + /// + /// WARNING Note that passing an + /// to this method will print the name of the + /// but no stack trace. To print a stack trace use the + /// form instead. + /// + /// + /// + /// + public static void InfoExt(this ILog logger, object message) + { + try + { if (!logger.IsInfoEnabled) { return; } - logger.Info(message); - } - catch (Exception ex) - { - log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); - } - } - - /// - /// Log a message object with the level including - /// the stack trace of the passed - /// as a parameter. - /// - /// The logger on which the message is logged. - /// The message object to log. - /// The exception to log, including its stack trace. - /// - /// - /// See the form for more detailed information. - /// - /// - /// - /// - public static void InfoExt(this ILog logger, object message, Exception exception) - { - try - { + logger.Info(message); + } + catch (Exception ex) + { + LogLog.Error(declaringType, "Exception while logging", ex); + } + } + + /// + /// Log a message object with the level including + /// the stack trace of the passed + /// as a parameter. + /// + /// The logger on which the message is logged. + /// The message object to log. + /// The exception to log, including its stack trace. + /// + /// + /// See the form for more detailed information. + /// + /// + /// + /// + public static void InfoExt(this ILog logger, object message, Exception exception) + { + try + { if (!logger.IsInfoEnabled) { return; } - logger.Info(message, exception); - } - catch (Exception ex) - { - log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); - } + logger.Info(message, exception); + } + catch (Exception ex) + { + LogLog.Error(declaringType, "Exception while logging", ex); + } } - /// - /// Logs a formatted message string with the level. - /// - /// The logger on which the message is logged. - /// A String containing zero or more format items. - /// An Object to format. - /// - /// - /// The message is formatted using the String.Format method. See - /// for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - /// - /// - public static void InfoFormatExt(this ILog logger, string format, object arg0) - { - try - { + /// + /// Logs a formatted message string with the level. + /// + /// The logger on which the message is logged. + /// A String containing zero or more format items + /// An Object to format + /// + /// + /// The message is formatted using the String.Format method. See + /// for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + /// + /// + public static void InfoFormatExt(this ILog logger, string format, object arg0) + { + try + { if (!logger.IsInfoEnabled) { return; } - logger.InfoFormat(format, arg0); - } - catch (Exception ex) - { - log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); - } - } - - /// - /// Logs a formatted message string with the level. - /// - /// The logger on which the message is logged. - /// A String containing zero or more format items. - /// An Object array containing zero or more objects to format. - /// - /// - /// The message is formatted using the String.Format method. See - /// for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - /// - /// - public static void InfoFormatExt(this ILog logger, string format, params object[] args) - { - try - { + logger.InfoFormat(format, arg0); + } + catch (Exception ex) + { + LogLog.Error(declaringType, "Exception while logging", ex); + } + } + + /// + /// Logs a formatted message string with the level. + /// + /// The logger on which the message is logged. + /// A String containing zero or more format items + /// An Object array containing zero or more objects to format + /// + /// + /// The message is formatted using the String.Format method. See + /// for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + /// + /// + public static void InfoFormatExt(this ILog logger, string format, params object[] args) + { + try + { if (!logger.IsInfoEnabled) { return; } - logger.InfoFormat(format, args); - } - catch (Exception ex) - { - log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); - } - } - - /// - /// Logs a formatted message string with the level. - /// - /// An that supplies culture-specific formatting information. - /// The logger on which the message is logged. - /// A String containing zero or more format items. - /// An Object array containing zero or more objects to format. - /// - /// - /// The message is formatted using the String.Format method. See - /// for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - /// - /// - public static void InfoFormatExt(this ILog logger, IFormatProvider provider, string format, params object[] args) - { - try - { + logger.InfoFormat(format, args); + } + catch (Exception ex) + { + LogLog.Error(declaringType, "Exception while logging", ex); + } + } + + /// + /// Logs a formatted message string with the level. + /// + /// An that supplies culture-specific formatting information + /// The logger on which the message is logged. + /// A String containing zero or more format items + /// An Object array containing zero or more objects to format + /// + /// + /// The message is formatted using the String.Format method. See + /// for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + /// + /// + public static void InfoFormatExt(this ILog logger, IFormatProvider provider, string format, params object[] args) + { + try + { if (!logger.IsInfoEnabled) { return; } - logger.InfoFormat(provider, format, args); - } - catch (Exception ex) - { - log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); - } - } - - /// - /// Logs a formatted message string with the level. - /// - /// The logger on which the message is logged. - /// A String containing zero or more format items. - /// An Object to format. - /// An Object to format. - /// - /// - /// The message is formatted using the String.Format method. See - /// for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - /// - /// - public static void InfoFormatExt(this ILog logger, string format, object arg0, object arg1) - { - try - { + logger.InfoFormat(provider, format, args); + } + catch (Exception ex) + { + LogLog.Error(declaringType, "Exception while logging", ex); + } + } + + /// + /// Logs a formatted message string with the level. + /// + /// The logger on which the message is logged. + /// A String containing zero or more format items + /// An Object to format + /// An Object to format + /// + /// + /// The message is formatted using the String.Format method. See + /// for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + /// + /// + public static void InfoFormatExt(this ILog logger, string format, object arg0, object arg1) + { + try + { if (!logger.IsInfoEnabled) { return; } - logger.InfoFormat(format, arg0, arg1); - } - catch (Exception ex) - { - log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); - } - } - - /// - /// Logs a formatted message string with the level. - /// - /// The logger on which the message is logged. - /// A String containing zero or more format items. - /// An Object to format. - /// An Object to format. - /// An Object to format. - /// - /// - /// The message is formatted using the String.Format method. See - /// for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - /// - /// - public static void InfoFormatExt(this ILog logger, string format, object arg0, object arg1, object arg2) - { - try - { + logger.InfoFormat(format, arg0, arg1); + } + catch (Exception ex) + { + LogLog.Error(declaringType, "Exception while logging", ex); + } + } + + /// + /// Logs a formatted message string with the level. + /// + /// The logger on which the message is logged. + /// A String containing zero or more format items + /// An Object to format + /// An Object to format + /// An Object to format + /// + /// + /// The message is formatted using the String.Format method. See + /// for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + /// + /// + public static void InfoFormatExt(this ILog logger, string format, object arg0, object arg1, object arg2) + { + try + { if (!logger.IsInfoEnabled) { return; } - logger.InfoFormat(format, arg0, arg1, arg2); - } - catch (Exception ex) - { - log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); - } + logger.InfoFormat(format, arg0, arg1, arg2); + } + catch (Exception ex) + { + LogLog.Error(declaringType, "Exception while logging", ex); + } } - /// - /// Log a message object with the level. - /// - /// The logger on which the message is logged. - /// The lambda expression that gets the object to log. - /// - /// - /// This method first checks if this logger is WARN - /// enabled by reading the value property. - /// This check happens always and does not depend on the - /// implementation. If this logger is WARN enabled, then it converts - /// the message object (retrieved by invocation of the provided callback) to a - /// string by invoking the appropriate . - /// It then proceeds to call all the registered appenders in this logger - /// and also higher in the hierarchy depending on the value of - /// the additivity flag. - /// - /// WARNING Note that passing an - /// to this method will print the name of the - /// but no stack trace. To print a stack trace use the - /// form instead. - /// - /// - /// - /// - public static void WarnExt(this ILog logger, Func callback) - { - try - { + /// + /// Log a message object with the level. + /// + /// The logger on which the message is logged. + /// The lambda expression that gets the object to log. + /// + /// + /// This method first checks if this logger is WARN + /// enabled by reading the value property. + /// This check happens always and does not depend on the + /// implementation. If this logger is WARN enabled, then it converts + /// the message object (retrieved by invocation of the provided callback) to a + /// string by invoking the appropriate . + /// It then proceeds to call all the registered appenders in this logger + /// and also higher in the hierarchy depending on the value of + /// the additivity flag. + /// + /// WARNING Note that passing an + /// to this method will print the name of the + /// but no stack trace. To print a stack trace use the + /// form instead. + /// + /// + /// + /// + public static void WarnExt(this ILog logger, Func callback) + { + try + { if (!logger.IsWarnEnabled) { return; } - logger.Warn(callback()); - } - catch (Exception ex) - { - log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); - } - } - - /// - /// Log a message object with the level including - /// the stack trace of the passed - /// as a parameter. - /// - /// The logger on which the message is logged. - /// The lambda expression that gets the object to log. - /// The exception to log, including its stack trace. - /// - /// - /// See the form for more detailed information. - /// - /// - /// - /// - public static void WarnExt(this ILog logger, Func callback, Exception exception) - { - try - { + logger.Warn(callback()); + } + catch (Exception ex) + { + LogLog.Error(declaringType, "Exception while logging", ex); + } + } + + /// + /// Log a message object with the level including + /// the stack trace of the passed + /// as a parameter. + /// + /// The logger on which the message is logged. + /// The lambda expression that gets the object to log. + /// The exception to log, including its stack trace. + /// + /// + /// See the form for more detailed information. + /// + /// + /// + /// + public static void WarnExt(this ILog logger, Func callback, Exception exception) + { + try + { if (!logger.IsWarnEnabled) { return; } - logger.Warn(callback(), exception); - } - catch (Exception ex) - { - log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); - } + logger.Warn(callback(), exception); + } + catch (Exception ex) + { + LogLog.Error(declaringType, "Exception while logging", ex); + } } - /// Log a message object with the level. //TODO - /// - /// Log a message object with the level. - /// - /// The logger on which the message is logged. - /// The message object to log. - /// - /// - /// This method first checks if this logger is WARN - /// enabled by reading the value property. - /// This check happens always and does not depend on the - /// implementation. If this logger is WARN enabled, then it converts - /// the message object (passed as parameter) to a string by invoking the appropriate - /// . It then - /// proceeds to call all the registered appenders in this logger - /// and also higher in the hierarchy depending on the value of - /// the additivity flag. - /// - /// WARNING Note that passing an - /// to this method will print the name of the - /// but no stack trace. To print a stack trace use the - /// form instead. - /// - /// - /// - /// - public static void WarnExt(this ILog logger, object message) - { - try - { + /// Log a message object with the level. //TODO + /// + /// Log a message object with the level. + /// + /// The logger on which the message is logged. + /// The message object to log. + /// + /// + /// This method first checks if this logger is WARN + /// enabled by reading the value property. + /// This check happens always and does not depend on the + /// implementation. If this logger is WARN enabled, then it converts + /// the message object (passed as parameter) to a string by invoking the appropriate + /// . It then + /// proceeds to call all the registered appenders in this logger + /// and also higher in the hierarchy depending on the value of + /// the additivity flag. + /// + /// WARNING Note that passing an + /// to this method will print the name of the + /// but no stack trace. To print a stack trace use the + /// form instead. + /// + /// + /// + /// + public static void WarnExt(this ILog logger, object message) + { + try + { if (!logger.IsWarnEnabled) { return; } - logger.Warn(message); - } - catch (Exception ex) - { - log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); - } - } - - /// - /// Log a message object with the level including - /// the stack trace of the passed - /// as a parameter. - /// - /// The logger on which the message is logged. - /// The message object to log. - /// The exception to log, including its stack trace. - /// - /// - /// See the form for more detailed information. - /// - /// - /// - /// - public static void WarnExt(this ILog logger, object message, Exception exception) - { - try - { + logger.Warn(message); + } + catch (Exception ex) + { + LogLog.Error(declaringType, "Exception while logging", ex); + } + } + + /// + /// Log a message object with the level including + /// the stack trace of the passed + /// as a parameter. + /// + /// The logger on which the message is logged. + /// The message object to log. + /// The exception to log, including its stack trace. + /// + /// + /// See the form for more detailed information. + /// + /// + /// + /// + public static void WarnExt(this ILog logger, object message, Exception exception) + { + try + { if (!logger.IsWarnEnabled) { return; } - logger.Warn(message, exception); - } - catch (Exception ex) - { - log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); - } + logger.Warn(message, exception); + } + catch (Exception ex) + { + LogLog.Error(declaringType, "Exception while logging", ex); + } } - /// - /// Logs a formatted message string with the level. - /// - /// The logger on which the message is logged. - /// A String containing zero or more format items. - /// An Object to format. - /// - /// - /// The message is formatted using the String.Format method. See - /// for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - /// - /// - public static void WarnFormatExt(this ILog logger, string format, object arg0) - { - try - { + /// + /// Logs a formatted message string with the level. + /// + /// The logger on which the message is logged. + /// A String containing zero or more format items + /// An Object to format + /// + /// + /// The message is formatted using the String.Format method. See + /// for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + /// + /// + public static void WarnFormatExt(this ILog logger, string format, object arg0) + { + try + { if (!logger.IsWarnEnabled) { return; } - logger.WarnFormat(format, arg0); - } - catch (Exception ex) - { - log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); - } - } - - /// - /// Logs a formatted message string with the level. - /// - /// The logger on which the message is logged. - /// A String containing zero or more format items. - /// An Object array containing zero or more objects to format. - /// - /// - /// The message is formatted using the String.Format method. See - /// for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - /// - /// - public static void WarnFormatExt(this ILog logger, string format, params object[] args) - { - try - { + logger.WarnFormat(format, arg0); + } + catch (Exception ex) + { + LogLog.Error(declaringType, "Exception while logging", ex); + } + } + + /// + /// Logs a formatted message string with the level. + /// + /// The logger on which the message is logged. + /// A String containing zero or more format items + /// An Object array containing zero or more objects to format + /// + /// + /// The message is formatted using the String.Format method. See + /// for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + /// + /// + public static void WarnFormatExt(this ILog logger, string format, params object[] args) + { + try + { if (!logger.IsWarnEnabled) { return; } - logger.WarnFormat(format, args); - } - catch (Exception ex) - { - log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); - } - } - - /// - /// Logs a formatted message string with the level. - /// - /// An that supplies culture-specific formatting information. - /// The logger on which the message is logged. - /// A String containing zero or more format items. - /// An Object array containing zero or more objects to format. - /// - /// - /// The message is formatted using the String.Format method. See - /// for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - /// - /// - public static void WarnFormatExt(this ILog logger, IFormatProvider provider, string format, params object[] args) - { - try - { + logger.WarnFormat(format, args); + } + catch (Exception ex) + { + LogLog.Error(declaringType, "Exception while logging", ex); + } + } + + /// + /// Logs a formatted message string with the level. + /// + /// An that supplies culture-specific formatting information + /// The logger on which the message is logged. + /// A String containing zero or more format items + /// An Object array containing zero or more objects to format + /// + /// + /// The message is formatted using the String.Format method. See + /// for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + /// + /// + public static void WarnFormatExt(this ILog logger, IFormatProvider provider, string format, params object[] args) + { + try + { if (!logger.IsWarnEnabled) { return; } - logger.WarnFormat(provider, format, args); - } - catch (Exception ex) - { - log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); - } - } - - /// - /// Logs a formatted message string with the level. - /// - /// The logger on which the message is logged. - /// A String containing zero or more format items. - /// An Object to format. - /// An Object to format. - /// - /// - /// The message is formatted using the String.Format method. See - /// for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - /// - /// - public static void WarnFormatExt(this ILog logger, string format, object arg0, object arg1) - { - try - { + logger.WarnFormat(provider, format, args); + } + catch (Exception ex) + { + LogLog.Error(declaringType, "Exception while logging", ex); + } + } + + /// + /// Logs a formatted message string with the level. + /// + /// The logger on which the message is logged. + /// A String containing zero or more format items + /// An Object to format + /// An Object to format + /// + /// + /// The message is formatted using the String.Format method. See + /// for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + /// + /// + public static void WarnFormatExt(this ILog logger, string format, object arg0, object arg1) + { + try + { if (!logger.IsWarnEnabled) { return; } - logger.WarnFormat(format, arg0, arg1); - } - catch (Exception ex) - { - log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); - } - } - - /// - /// Logs a formatted message string with the level. - /// - /// The logger on which the message is logged. - /// A String containing zero or more format items. - /// An Object to format. - /// An Object to format. - /// An Object to format. - /// - /// - /// The message is formatted using the String.Format method. See - /// for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - /// - /// - public static void WarnFormatExt(this ILog logger, string format, object arg0, object arg1, object arg2) - { - try - { + logger.WarnFormat(format, arg0, arg1); + } + catch (Exception ex) + { + LogLog.Error(declaringType, "Exception while logging", ex); + } + } + + /// + /// Logs a formatted message string with the level. + /// + /// The logger on which the message is logged. + /// A String containing zero or more format items + /// An Object to format + /// An Object to format + /// An Object to format + /// + /// + /// The message is formatted using the String.Format method. See + /// for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + /// + /// + public static void WarnFormatExt(this ILog logger, string format, object arg0, object arg1, object arg2) + { + try + { if (!logger.IsWarnEnabled) { return; } - logger.WarnFormat(format, arg0, arg1, arg2); - } - catch (Exception ex) - { - log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); - } + logger.WarnFormat(format, arg0, arg1, arg2); + } + catch (Exception ex) + { + LogLog.Error(declaringType, "Exception while logging", ex); + } } - /// - /// Log a message object with the level. - /// - /// The logger on which the message is logged. - /// The lambda expression that gets the object to log. - /// - /// - /// This method first checks if this logger is ERROR - /// enabled by reading the value property. - /// This check happens always and does not depend on the - /// implementation. If this logger is ERROR enabled, then it converts - /// the message object (retrieved by invocation of the provided callback) to a - /// string by invoking the appropriate . - /// It then proceeds to call all the registered appenders in this logger - /// and also higher in the hierarchy depending on the value of - /// the additivity flag. - /// - /// WARNING Note that passing an - /// to this method will print the name of the - /// but no stack trace. To print a stack trace use the - /// form instead. - /// - /// - /// - /// - public static void ErrorExt(this ILog logger, Func callback) - { - try - { + /// + /// Log a message object with the level. + /// + /// The logger on which the message is logged. + /// The lambda expression that gets the object to log. + /// + /// + /// This method first checks if this logger is ERROR + /// enabled by reading the value property. + /// This check happens always and does not depend on the + /// implementation. If this logger is ERROR enabled, then it converts + /// the message object (retrieved by invocation of the provided callback) to a + /// string by invoking the appropriate . + /// It then proceeds to call all the registered appenders in this logger + /// and also higher in the hierarchy depending on the value of + /// the additivity flag. + /// + /// WARNING Note that passing an + /// to this method will print the name of the + /// but no stack trace. To print a stack trace use the + /// form instead. + /// + /// + /// + /// + public static void ErrorExt(this ILog logger, Func callback) + { + try + { if (!logger.IsErrorEnabled) { return; } - logger.Error(callback()); - } - catch (Exception ex) - { - log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); - } - } - - /// - /// Log a message object with the level including - /// the stack trace of the passed - /// as a parameter. - /// - /// The logger on which the message is logged. - /// The lambda expression that gets the object to log. - /// The exception to log, including its stack trace. - /// - /// - /// See the form for more detailed information. - /// - /// - /// - /// - public static void ErrorExt(this ILog logger, Func callback, Exception exception) - { - try - { + logger.Error(callback()); + } + catch (Exception ex) + { + LogLog.Error(declaringType, "Exception while logging", ex); + } + } + + /// + /// Log a message object with the level including + /// the stack trace of the passed + /// as a parameter. + /// + /// The logger on which the message is logged. + /// The lambda expression that gets the object to log. + /// The exception to log, including its stack trace. + /// + /// + /// See the form for more detailed information. + /// + /// + /// + /// + public static void ErrorExt(this ILog logger, Func callback, Exception exception) + { + try + { if (!logger.IsErrorEnabled) { return; } - logger.Error(callback(), exception); - } - catch (Exception ex) - { - log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); - } + logger.Error(callback(), exception); + } + catch (Exception ex) + { + LogLog.Error(declaringType, "Exception while logging", ex); + } } - /// Log a message object with the level. //TODO - /// - /// Log a message object with the level. - /// - /// The logger on which the message is logged. - /// The message object to log. - /// - /// - /// This method first checks if this logger is ERROR - /// enabled by reading the value property. - /// This check happens always and does not depend on the - /// implementation. If this logger is ERROR enabled, then it converts - /// the message object (passed as parameter) to a string by invoking the appropriate - /// . It then - /// proceeds to call all the registered appenders in this logger - /// and also higher in the hierarchy depending on the value of - /// the additivity flag. - /// - /// WARNING Note that passing an - /// to this method will print the name of the - /// but no stack trace. To print a stack trace use the - /// form instead. - /// - /// - /// - /// - public static void ErrorExt(this ILog logger, object message) - { - try - { + /// Log a message object with the level. //TODO + /// + /// Log a message object with the level. + /// + /// The logger on which the message is logged. + /// The message object to log. + /// + /// + /// This method first checks if this logger is ERROR + /// enabled by reading the value property. + /// This check happens always and does not depend on the + /// implementation. If this logger is ERROR enabled, then it converts + /// the message object (passed as parameter) to a string by invoking the appropriate + /// . It then + /// proceeds to call all the registered appenders in this logger + /// and also higher in the hierarchy depending on the value of + /// the additivity flag. + /// + /// WARNING Note that passing an + /// to this method will print the name of the + /// but no stack trace. To print a stack trace use the + /// form instead. + /// + /// + /// + /// + public static void ErrorExt(this ILog logger, object message) + { + try + { if (!logger.IsErrorEnabled) { return; } - logger.Error(message); - } - catch (Exception ex) - { - log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); - } - } - - /// - /// Log a message object with the level including - /// the stack trace of the passed - /// as a parameter. - /// - /// The logger on which the message is logged. - /// The message object to log. - /// The exception to log, including its stack trace. - /// - /// - /// See the form for more detailed information. - /// - /// - /// - /// - public static void ErrorExt(this ILog logger, object message, Exception exception) - { - try - { + logger.Error(message); + } + catch (Exception ex) + { + LogLog.Error(declaringType, "Exception while logging", ex); + } + } + + /// + /// Log a message object with the level including + /// the stack trace of the passed + /// as a parameter. + /// + /// The logger on which the message is logged. + /// The message object to log. + /// The exception to log, including its stack trace. + /// + /// + /// See the form for more detailed information. + /// + /// + /// + /// + public static void ErrorExt(this ILog logger, object message, Exception exception) + { + try + { if (!logger.IsErrorEnabled) { return; } - logger.Error(message, exception); - } - catch (Exception ex) - { - log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); - } + logger.Error(message, exception); + } + catch (Exception ex) + { + LogLog.Error(declaringType, "Exception while logging", ex); + } } - /// - /// Logs a formatted message string with the level. - /// - /// The logger on which the message is logged. - /// A String containing zero or more format items. - /// An Object to format. - /// - /// - /// The message is formatted using the String.Format method. See - /// for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - /// - /// - public static void ErrorFormatExt(this ILog logger, string format, object arg0) - { - try - { + /// + /// Logs a formatted message string with the level. + /// + /// The logger on which the message is logged. + /// A String containing zero or more format items + /// An Object to format + /// + /// + /// The message is formatted using the String.Format method. See + /// for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + /// + /// + public static void ErrorFormatExt(this ILog logger, string format, object arg0) + { + try + { if (!logger.IsErrorEnabled) { return; } - logger.ErrorFormat(format, arg0); - } - catch (Exception ex) - { - log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); - } - } - - /// - /// Logs a formatted message string with the level. - /// - /// The logger on which the message is logged. - /// A String containing zero or more format items. - /// An Object array containing zero or more objects to format. - /// - /// - /// The message is formatted using the String.Format method. See - /// for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - /// - /// - public static void ErrorFormatExt(this ILog logger, string format, params object[] args) - { - try - { + logger.ErrorFormat(format, arg0); + } + catch (Exception ex) + { + LogLog.Error(declaringType, "Exception while logging", ex); + } + } + + /// + /// Logs a formatted message string with the level. + /// + /// The logger on which the message is logged. + /// A String containing zero or more format items + /// An Object array containing zero or more objects to format + /// + /// + /// The message is formatted using the String.Format method. See + /// for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + /// + /// + public static void ErrorFormatExt(this ILog logger, string format, params object[] args) + { + try + { if (!logger.IsErrorEnabled) { return; } - logger.ErrorFormat(format, args); - } - catch (Exception ex) - { - log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); - } - } - - /// - /// Logs a formatted message string with the level. - /// - /// An that supplies culture-specific formatting information. - /// The logger on which the message is logged. - /// A String containing zero or more format items. - /// An Object array containing zero or more objects to format. - /// - /// - /// The message is formatted using the String.Format method. See - /// for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - /// - /// - public static void ErrorFormatExt(this ILog logger, IFormatProvider provider, string format, params object[] args) - { - try - { + logger.ErrorFormat(format, args); + } + catch (Exception ex) + { + LogLog.Error(declaringType, "Exception while logging", ex); + } + } + + /// + /// Logs a formatted message string with the level. + /// + /// An that supplies culture-specific formatting information + /// The logger on which the message is logged. + /// A String containing zero or more format items + /// An Object array containing zero or more objects to format + /// + /// + /// The message is formatted using the String.Format method. See + /// for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + /// + /// + public static void ErrorFormatExt(this ILog logger, IFormatProvider provider, string format, params object[] args) + { + try + { if (!logger.IsErrorEnabled) { return; } - logger.ErrorFormat(provider, format, args); - } - catch (Exception ex) - { - log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); - } - } - - /// - /// Logs a formatted message string with the level. - /// - /// The logger on which the message is logged. - /// A String containing zero or more format items. - /// An Object to format. - /// An Object to format. - /// - /// - /// The message is formatted using the String.Format method. See - /// for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - /// - /// - public static void ErrorFormatExt(this ILog logger, string format, object arg0, object arg1) - { - try - { + logger.ErrorFormat(provider, format, args); + } + catch (Exception ex) + { + LogLog.Error(declaringType, "Exception while logging", ex); + } + } + + /// + /// Logs a formatted message string with the level. + /// + /// The logger on which the message is logged. + /// A String containing zero or more format items + /// An Object to format + /// An Object to format + /// + /// + /// The message is formatted using the String.Format method. See + /// for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + /// + /// + public static void ErrorFormatExt(this ILog logger, string format, object arg0, object arg1) + { + try + { if (!logger.IsErrorEnabled) { return; } - logger.ErrorFormat(format, arg0, arg1); - } - catch (Exception ex) - { - log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); - } - } - - /// - /// Logs a formatted message string with the level. - /// - /// The logger on which the message is logged. - /// A String containing zero or more format items. - /// An Object to format. - /// An Object to format. - /// An Object to format. - /// - /// - /// The message is formatted using the String.Format method. See - /// for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - /// - /// - public static void ErrorFormatExt(this ILog logger, string format, object arg0, object arg1, object arg2) - { - try - { + logger.ErrorFormat(format, arg0, arg1); + } + catch (Exception ex) + { + LogLog.Error(declaringType, "Exception while logging", ex); + } + } + + /// + /// Logs a formatted message string with the level. + /// + /// The logger on which the message is logged. + /// A String containing zero or more format items + /// An Object to format + /// An Object to format + /// An Object to format + /// + /// + /// The message is formatted using the String.Format method. See + /// for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + /// + /// + public static void ErrorFormatExt(this ILog logger, string format, object arg0, object arg1, object arg2) + { + try + { if (!logger.IsErrorEnabled) { return; } - logger.ErrorFormat(format, arg0, arg1, arg2); - } - catch (Exception ex) - { - log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); - } + logger.ErrorFormat(format, arg0, arg1, arg2); + } + catch (Exception ex) + { + LogLog.Error(declaringType, "Exception while logging", ex); + } } - /// - /// Log a message object with the level. - /// - /// The logger on which the message is logged. - /// The lambda expression that gets the object to log. - /// - /// - /// This method first checks if this logger is FATAL - /// enabled by reading the value property. - /// This check happens always and does not depend on the - /// implementation. If this logger is FATAL enabled, then it converts - /// the message object (retrieved by invocation of the provided callback) to a - /// string by invoking the appropriate . - /// It then proceeds to call all the registered appenders in this logger - /// and also higher in the hierarchy depending on the value of - /// the additivity flag. - /// - /// WARNING Note that passing an - /// to this method will print the name of the - /// but no stack trace. To print a stack trace use the - /// form instead. - /// - /// - /// - /// - public static void FatalExt(this ILog logger, Func callback) - { - try - { + /// + /// Log a message object with the level. + /// + /// The logger on which the message is logged. + /// The lambda expression that gets the object to log. + /// + /// + /// This method first checks if this logger is FATAL + /// enabled by reading the value property. + /// This check happens always and does not depend on the + /// implementation. If this logger is FATAL enabled, then it converts + /// the message object (retrieved by invocation of the provided callback) to a + /// string by invoking the appropriate . + /// It then proceeds to call all the registered appenders in this logger + /// and also higher in the hierarchy depending on the value of + /// the additivity flag. + /// + /// WARNING Note that passing an + /// to this method will print the name of the + /// but no stack trace. To print a stack trace use the + /// form instead. + /// + /// + /// + /// + public static void FatalExt(this ILog logger, Func callback) + { + try + { if (!logger.IsFatalEnabled) { return; } - logger.Fatal(callback()); - } - catch (Exception ex) - { - log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); - } - } - - /// - /// Log a message object with the level including - /// the stack trace of the passed - /// as a parameter. - /// - /// The logger on which the message is logged. - /// The lambda expression that gets the object to log. - /// The exception to log, including its stack trace. - /// - /// - /// See the form for more detailed information. - /// - /// - /// - /// - public static void FatalExt(this ILog logger, Func callback, Exception exception) - { - try - { + logger.Fatal(callback()); + } + catch (Exception ex) + { + LogLog.Error(declaringType, "Exception while logging", ex); + } + } + + /// + /// Log a message object with the level including + /// the stack trace of the passed + /// as a parameter. + /// + /// The logger on which the message is logged. + /// The lambda expression that gets the object to log. + /// The exception to log, including its stack trace. + /// + /// + /// See the form for more detailed information. + /// + /// + /// + /// + public static void FatalExt(this ILog logger, Func callback, Exception exception) + { + try + { if (!logger.IsFatalEnabled) { return; } - logger.Fatal(callback(), exception); - } - catch (Exception ex) - { - log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); - } + logger.Fatal(callback(), exception); + } + catch (Exception ex) + { + LogLog.Error(declaringType, "Exception while logging", ex); + } } - /// Log a message object with the level. //TODO - /// - /// Log a message object with the level. - /// - /// The logger on which the message is logged. - /// The message object to log. - /// - /// - /// This method first checks if this logger is FATAL - /// enabled by reading the value property. - /// This check happens always and does not depend on the - /// implementation. If this logger is FATAL enabled, then it converts - /// the message object (passed as parameter) to a string by invoking the appropriate - /// . It then - /// proceeds to call all the registered appenders in this logger - /// and also higher in the hierarchy depending on the value of - /// the additivity flag. - /// - /// WARNING Note that passing an - /// to this method will print the name of the - /// but no stack trace. To print a stack trace use the - /// form instead. - /// - /// - /// - /// - public static void FatalExt(this ILog logger, object message) - { - try - { + /// Log a message object with the level. //TODO + /// + /// Log a message object with the level. + /// + /// The logger on which the message is logged. + /// The message object to log. + /// + /// + /// This method first checks if this logger is FATAL + /// enabled by reading the value property. + /// This check happens always and does not depend on the + /// implementation. If this logger is FATAL enabled, then it converts + /// the message object (passed as parameter) to a string by invoking the appropriate + /// . It then + /// proceeds to call all the registered appenders in this logger + /// and also higher in the hierarchy depending on the value of + /// the additivity flag. + /// + /// WARNING Note that passing an + /// to this method will print the name of the + /// but no stack trace. To print a stack trace use the + /// form instead. + /// + /// + /// + /// + public static void FatalExt(this ILog logger, object message) + { + try + { if (!logger.IsFatalEnabled) { return; } - logger.Fatal(message); - } - catch (Exception ex) - { - log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); - } - } - - /// - /// Log a message object with the level including - /// the stack trace of the passed - /// as a parameter. - /// - /// The logger on which the message is logged. - /// The message object to log. - /// The exception to log, including its stack trace. - /// - /// - /// See the form for more detailed information. - /// - /// - /// - /// - public static void FatalExt(this ILog logger, object message, Exception exception) - { - try - { + logger.Fatal(message); + } + catch (Exception ex) + { + LogLog.Error(declaringType, "Exception while logging", ex); + } + } + + /// + /// Log a message object with the level including + /// the stack trace of the passed + /// as a parameter. + /// + /// The logger on which the message is logged. + /// The message object to log. + /// The exception to log, including its stack trace. + /// + /// + /// See the form for more detailed information. + /// + /// + /// + /// + public static void FatalExt(this ILog logger, object message, Exception exception) + { + try + { if (!logger.IsFatalEnabled) { return; } - logger.Fatal(message, exception); - } - catch (Exception ex) - { - log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); - } + logger.Fatal(message, exception); + } + catch (Exception ex) + { + LogLog.Error(declaringType, "Exception while logging", ex); + } } - /// - /// Logs a formatted message string with the level. - /// - /// The logger on which the message is logged. - /// A String containing zero or more format items. - /// An Object to format. - /// - /// - /// The message is formatted using the String.Format method. See - /// for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - /// - /// - public static void FatalFormatExt(this ILog logger, string format, object arg0) - { - try - { + /// + /// Logs a formatted message string with the level. + /// + /// The logger on which the message is logged. + /// A String containing zero or more format items + /// An Object to format + /// + /// + /// The message is formatted using the String.Format method. See + /// for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + /// + /// + public static void FatalFormatExt(this ILog logger, string format, object arg0) + { + try + { if (!logger.IsFatalEnabled) { return; } - logger.FatalFormat(format, arg0); - } - catch (Exception ex) - { - log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); - } - } - - /// - /// Logs a formatted message string with the level. - /// - /// The logger on which the message is logged. - /// A String containing zero or more format items. - /// An Object array containing zero or more objects to format. - /// - /// - /// The message is formatted using the String.Format method. See - /// for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - /// - /// - public static void FatalFormatExt(this ILog logger, string format, params object[] args) - { - try - { + logger.FatalFormat(format, arg0); + } + catch (Exception ex) + { + LogLog.Error(declaringType, "Exception while logging", ex); + } + } + + /// + /// Logs a formatted message string with the level. + /// + /// The logger on which the message is logged. + /// A String containing zero or more format items + /// An Object array containing zero or more objects to format + /// + /// + /// The message is formatted using the String.Format method. See + /// for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + /// + /// + public static void FatalFormatExt(this ILog logger, string format, params object[] args) + { + try + { if (!logger.IsFatalEnabled) { return; } - logger.FatalFormat(format, args); - } - catch (Exception ex) - { - log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); - } - } - - /// - /// Logs a formatted message string with the level. - /// - /// An that supplies culture-specific formatting information. - /// The logger on which the message is logged. - /// A String containing zero or more format items. - /// An Object array containing zero or more objects to format. - /// - /// - /// The message is formatted using the String.Format method. See - /// for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - /// - /// - public static void FatalFormatExt(this ILog logger, IFormatProvider provider, string format, params object[] args) - { - try - { + logger.FatalFormat(format, args); + } + catch (Exception ex) + { + LogLog.Error(declaringType, "Exception while logging", ex); + } + } + + /// + /// Logs a formatted message string with the level. + /// + /// An that supplies culture-specific formatting information + /// The logger on which the message is logged. + /// A String containing zero or more format items + /// An Object array containing zero or more objects to format + /// + /// + /// The message is formatted using the String.Format method. See + /// for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + /// + /// + public static void FatalFormatExt(this ILog logger, IFormatProvider provider, string format, params object[] args) + { + try + { if (!logger.IsFatalEnabled) { return; } - logger.FatalFormat(provider, format, args); - } - catch (Exception ex) - { - log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); - } - } - - /// - /// Logs a formatted message string with the level. - /// - /// The logger on which the message is logged. - /// A String containing zero or more format items. - /// An Object to format. - /// An Object to format. - /// - /// - /// The message is formatted using the String.Format method. See - /// for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - /// - /// - public static void FatalFormatExt(this ILog logger, string format, object arg0, object arg1) - { - try - { + logger.FatalFormat(provider, format, args); + } + catch (Exception ex) + { + LogLog.Error(declaringType, "Exception while logging", ex); + } + } + + /// + /// Logs a formatted message string with the level. + /// + /// The logger on which the message is logged. + /// A String containing zero or more format items + /// An Object to format + /// An Object to format + /// + /// + /// The message is formatted using the String.Format method. See + /// for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + /// + /// + public static void FatalFormatExt(this ILog logger, string format, object arg0, object arg1) + { + try + { if (!logger.IsFatalEnabled) { return; } - logger.FatalFormat(format, arg0, arg1); - } - catch (Exception ex) - { - log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); - } - } - - /// - /// Logs a formatted message string with the level. - /// - /// The logger on which the message is logged. - /// A String containing zero or more format items. - /// An Object to format. - /// An Object to format. - /// An Object to format. - /// - /// - /// The message is formatted using the String.Format method. See - /// for details of the syntax of the format string and the behavior - /// of the formatting. - /// - /// - /// This method does not take an object to include in the - /// log event. To pass an use one of the - /// methods instead. - /// - /// - /// - /// - public static void FatalFormatExt(this ILog logger, string format, object arg0, object arg1, object arg2) - { - try - { + logger.FatalFormat(format, arg0, arg1); + } + catch (Exception ex) + { + LogLog.Error(declaringType, "Exception while logging", ex); + } + } + + /// + /// Logs a formatted message string with the level. + /// + /// The logger on which the message is logged. + /// A String containing zero or more format items + /// An Object to format + /// An Object to format + /// An Object to format + /// + /// + /// The message is formatted using the String.Format method. See + /// for details of the syntax of the format string and the behavior + /// of the formatting. + /// + /// + /// This method does not take an object to include in the + /// log event. To pass an use one of the + /// methods instead. + /// + /// + /// + /// + public static void FatalFormatExt(this ILog logger, string format, object arg0, object arg1, object arg2) + { + try + { if (!logger.IsFatalEnabled) { return; } - logger.FatalFormat(format, arg0, arg1, arg2); - } - catch (Exception ex) - { - log4net.Util.LogLog.Error(declaringType, "Exception while logging", ex); - } + logger.FatalFormat(format, arg0, arg1, arg2); + } + catch (Exception ex) + { + LogLog.Error(declaringType, "Exception while logging", ex); + } } - } -} -#endif + } +} +#endif diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/LevelMapping.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/LevelMapping.cs index fafd53c36f4..f424894430f 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/LevelMapping.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/LevelMapping.cs @@ -1,138 +1,136 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.Util -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; - using System.Collections; +using System; +using System.Collections; - using log4net.Core; +using log4net.Core; - /// - /// Manages a mapping from levels to . - /// - /// - /// - /// Manages an ordered mapping from instances - /// to subclasses. - /// - /// - /// Nicko Cadell. - public sealed class LevelMapping : IOptionHandler +namespace log4net.Util +{ + /// + /// Manages a mapping from levels to + /// + /// + /// + /// Manages an ordered mapping from instances + /// to subclasses. + /// + /// + /// Nicko Cadell + public sealed class LevelMapping : IOptionHandler { /// - /// Initializes a new instance of the class. - /// Default constructor. - /// - /// - /// - /// Initialise a new instance of . - /// - /// - public LevelMapping() - { + /// Default constructor + /// + /// + /// + /// Initialise a new instance of . + /// + /// + public LevelMapping() + { } - /// - /// Add a to this mapping. - /// - /// the entry to add. - /// - /// - /// If a has previously been added - /// for the same then that entry will be - /// overwritten. - /// - /// - public void Add(LevelMappingEntry entry) - { - if (this.m_entriesMap.ContainsKey(entry.Level)) - { - this.m_entriesMap.Remove(entry.Level); - } + /// + /// Add a to this mapping + /// + /// the entry to add + /// + /// + /// If a has previously been added + /// for the same then that entry will be + /// overwritten. + /// + /// + public void Add(LevelMappingEntry entry) + { + if (this.m_entriesMap.ContainsKey(entry.Level)) + { + this.m_entriesMap.Remove(entry.Level); + } - this.m_entriesMap.Add(entry.Level, entry); - } - - /// - /// Lookup the mapping for the specified level. - /// - /// the level to lookup. - /// the for the level or null if no mapping found. - /// - /// - /// Lookup the value for the specified level. Finds the nearest - /// mapping value for the level that is equal to or less than the - /// specified. - /// - /// - /// If no mapping could be found then null is returned. - /// - /// - public LevelMappingEntry Lookup(Level level) - { - if (this.m_entries != null) - { - foreach (LevelMappingEntry entry in this.m_entries) - { - if (level >= entry.Level) - { - return entry; - } - } - } + this.m_entriesMap.Add(entry.Level, entry); + } - return null; + /// + /// Lookup the mapping for the specified level + /// + /// the level to lookup + /// the for the level or null if no mapping found + /// + /// + /// Lookup the value for the specified level. Finds the nearest + /// mapping value for the level that is equal to or less than the + /// specified. + /// + /// + /// If no mapping could be found then null is returned. + /// + /// + public LevelMappingEntry Lookup(Level level) + { + if (this.m_entries != null) + { + foreach(LevelMappingEntry entry in this.m_entries) + { + if (level >= entry.Level) + { + return entry; + } + } + } + return null; } - /// - /// Initialize options. - /// - /// - /// - /// Caches the sorted list of in an array. - /// - /// - public void ActivateOptions() - { - Level[] sortKeys = new Level[this.m_entriesMap.Count]; - LevelMappingEntry[] sortValues = new LevelMappingEntry[this.m_entriesMap.Count]; - - this.m_entriesMap.Keys.CopyTo(sortKeys, 0); - this.m_entriesMap.Values.CopyTo(sortValues, 0); - - // Sort in level order - Array.Sort(sortKeys, sortValues, 0, sortKeys.Length, null); - - // Reverse list so that highest level is first - Array.Reverse(sortValues, 0, sortValues.Length); - - foreach (LevelMappingEntry entry in sortValues) - { - entry.ActivateOptions(); - } - - this.m_entries = sortValues; + /// + /// Initialize options + /// + /// + /// + /// Caches the sorted list of in an array + /// + /// + public void ActivateOptions() + { + Level[] sortKeys = new Level[this.m_entriesMap.Count]; + LevelMappingEntry[] sortValues = new LevelMappingEntry[this.m_entriesMap.Count]; + + this.m_entriesMap.Keys.CopyTo(sortKeys, 0); + this.m_entriesMap.Values.CopyTo(sortValues, 0); + + // Sort in level order + Array.Sort(sortKeys, sortValues, 0, sortKeys.Length, null); + + // Reverse list so that highest level is first + Array.Reverse(sortValues, 0, sortValues.Length); + + foreach(LevelMappingEntry entry in sortValues) + { + entry.ActivateOptions(); + } + + this.m_entries = sortValues; } - private Hashtable m_entriesMap = new Hashtable(); + private Hashtable m_entriesMap = new Hashtable(); private LevelMappingEntry[] m_entries = null; - } -} + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/LevelMappingEntry.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/LevelMappingEntry.cs index 2e08dec9d00..f54c1565015 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/LevelMappingEntry.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/LevelMappingEntry.cs @@ -1,86 +1,85 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.Util -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; - using System.Collections; +using System; +using System.Collections; - using log4net.Core; +using log4net.Core; - /// - /// An entry in the . - /// - /// - /// - /// This is an abstract base class for types that are stored in the - /// object. - /// - /// - /// Nicko Cadell. - public abstract class LevelMappingEntry : IOptionHandler +namespace log4net.Util +{ + /// + /// An entry in the + /// + /// + /// + /// This is an abstract base class for types that are stored in the + /// object. + /// + /// + /// Nicko Cadell + public abstract class LevelMappingEntry : IOptionHandler { /// - /// Initializes a new instance of the class. - /// Default protected constructor. - /// - /// - /// - /// Default protected constructor. - /// - /// - protected LevelMappingEntry() - { + /// Default protected constructor + /// + /// + /// + /// Default protected constructor + /// + /// + protected LevelMappingEntry() + { } - /// - /// Gets or sets the level that is the key for this mapping. - /// - /// - /// The that is the key for this mapping. - /// - /// - /// - /// Get or set the that is the key for this - /// mapping subclass. - /// - /// - public Level Level - { - get { return this.m_level; } - set { this.m_level = value; } + /// + /// The level that is the key for this mapping + /// + /// + /// The that is the key for this mapping + /// + /// + /// + /// Get or set the that is the key for this + /// mapping subclass. + /// + /// + public Level Level + { + get { return this.m_level; } + set { this.m_level = value; } } - /// - /// Initialize any options defined on this entry. - /// - /// - /// - /// Should be overridden by any classes that need to initialise based on their options. - /// - /// - public virtual void ActivateOptions() - { - // default implementation is to do nothing + /// + /// Initialize any options defined on this entry + /// + /// + /// + /// Should be overridden by any classes that need to initialise based on their options + /// + /// + public virtual void ActivateOptions() + { + // default implementation is to do nothing } private Level m_level; - } -} + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/LogLog.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/LogLog.cs index 934659e380a..be0d4b269f8 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/LogLog.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/LogLog.cs @@ -1,662 +1,656 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -#if !NETSTANDARD1_3 -using System.Configuration; - -#endif -using System.Diagnostics; - -namespace log4net.Util -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; - using System.Collections; - - /// - /// - /// - /// - /// - public delegate void LogReceivedEventHandler(object source, LogReceivedEventArgs e); - - /// - /// Outputs log statements from within the log4net assembly. - /// - /// - /// - /// Log4net components cannot make log4net logging calls. However, it is - /// sometimes useful for the user to learn about what log4net is - /// doing. - /// - /// - /// All log4net internal debug calls go to the standard output stream - /// whereas internal error messages are sent to the standard error output - /// stream. - /// - /// - /// Nicko Cadell. - /// Gert Driesen. - public sealed class LogLog - { - /// - /// The event raised when an internal message has been received. - /// - public static event LogReceivedEventHandler LogReceived; - - private readonly Type source; - private readonly DateTime timeStampUtc; - private readonly string prefix; - private readonly string message; - private readonly Exception exception; - - /// - /// Gets the Type that generated the internal message. - /// - public Type Source - { - get { return this.source; } - } - - /// - /// Gets the DateTime stamp of when the internal message was received. - /// - public DateTime TimeStamp - { - get { return this.timeStampUtc.ToLocalTime(); } - } - - /// - /// Gets the UTC DateTime stamp of when the internal message was received. - /// - public DateTime TimeStampUtc - { - get { return this.timeStampUtc; } - } - - /// - /// Gets a string indicating the severity of the internal message. - /// - /// - /// "log4net: ", - /// "log4net:ERROR ", - /// "log4net:WARN ". - /// - public string Prefix - { - get { return this.prefix; } - } - - /// - /// Gets the internal log message. - /// - public string Message - { - get { return this.message; } - } - - /// - /// Gets the Exception related to the message. - /// - /// - /// Optional. Will be null if no Exception was passed. - /// - public Exception Exception - { - get { return this.exception; } - } - - /// - /// Formats Prefix, Source, and Message in the same format as the value - /// sent to Console.Out and Trace.Write. - /// - /// - public override string ToString() - { - return this.Prefix + this.Source.Name + ": " + this.Message; +using System; +using System.Collections; +using System.Diagnostics; + +namespace log4net.Util +{ + /// + /// + /// + /// + /// + public delegate void LogReceivedEventHandler(object source, LogReceivedEventArgs e); + + /// + /// Outputs log statements from within the log4net assembly. + /// + /// + /// + /// Log4net components cannot make log4net logging calls. However, it is + /// sometimes useful for the user to learn about what log4net is + /// doing. + /// + /// + /// All log4net internal debug calls go to the standard output stream + /// whereas internal error messages are sent to the standard error output + /// stream. + /// + /// + /// Nicko Cadell + /// Gert Driesen + public sealed class LogLog + { + /// + /// The event raised when an internal message has been received. + /// + public static event LogReceivedEventHandler LogReceived; + + private readonly Type source; + private readonly DateTime timeStampUtc; + private readonly string prefix; + private readonly string message; + private readonly Exception exception; + + /// + /// The Type that generated the internal message. + /// + public Type Source + { + get { return this.source; } + } + + /// + /// The DateTime stamp of when the internal message was received. + /// + public DateTime TimeStamp + { + get { return this.timeStampUtc.ToLocalTime(); } + } + + /// + /// The UTC DateTime stamp of when the internal message was received. + /// + public DateTime TimeStampUtc + { + get { return this.timeStampUtc; } + } + + /// + /// A string indicating the severity of the internal message. + /// + /// + /// "log4net: ", + /// "log4net:ERROR ", + /// "log4net:WARN " + /// + public string Prefix + { + get { return this.prefix; } + } + + /// + /// The internal log message. + /// + public string Message + { + get { return this.message; } + } + + /// + /// The Exception related to the message. + /// + /// + /// Optional. Will be null if no Exception was passed. + /// + public Exception Exception + { + get { return this.exception; } + } + + /// + /// Formats Prefix, Source, and Message in the same format as the value + /// sent to Console.Out and Trace.Write. + /// + /// + public override string ToString() + { + return this.Prefix + this.Source.Name + ": " + this.Message; + } + + /// + /// Initializes a new instance of the class. + /// + /// + /// + /// + /// + public LogLog(Type source, string prefix, string message, Exception exception) + { + this.timeStampUtc = DateTime.UtcNow; + + this.source = source; + this.prefix = prefix; + this.message = message; + this.exception = exception; + } + + /// + /// Static constructor that initializes logging by reading + /// settings from the application configuration file. + /// + /// + /// + /// The log4net.Internal.Debug application setting + /// controls internal debugging. This setting should be set + /// to true to enable debugging. + /// + /// + /// The log4net.Internal.Quiet application setting + /// suppresses all internal logging including error messages. + /// This setting should be set to true to enable message + /// suppression. + /// + /// + static LogLog() + { +#if !NETCF + try + { + InternalDebugging = OptionConverter.ToBoolean(SystemInfo.GetAppSetting("log4net.Internal.Debug"), false); + QuietMode = OptionConverter.ToBoolean(SystemInfo.GetAppSetting("log4net.Internal.Quiet"), false); + EmitInternalMessages = OptionConverter.ToBoolean(SystemInfo.GetAppSetting("log4net.Internal.Emit"), true); + } + catch(Exception ex) + { + // If an exception is thrown here then it looks like the config file does not + // parse correctly. + // + // We will leave debug OFF and print an Error message + Error(typeof(LogLog), "Exception while reading ConfigurationSettings. Check your .config file is well formed XML.", ex); + } +#endif + } + + /// + /// Gets or sets a value indicating whether log4net internal logging + /// is enabled or disabled. + /// + /// + /// true if log4net internal logging is enabled, otherwise + /// false. + /// + /// + /// + /// When set to true, internal debug level logging will be + /// displayed. + /// + /// + /// This value can be set by setting the application setting + /// log4net.Internal.Debug in the application configuration + /// file. + /// + /// + /// The default value is false, i.e. debugging is + /// disabled. + /// + /// + /// + /// + /// The following example enables internal debugging using the + /// application configuration file : + /// + /// + /// + /// + /// + /// + /// + /// + /// + public static bool InternalDebugging + { + get { return s_debugEnabled; } + set { s_debugEnabled = value; } + } + + /// + /// Gets or sets a value indicating whether log4net should generate no output + /// from internal logging, not even for errors. + /// + /// + /// true if log4net should generate no output at all from internal + /// logging, otherwise false. + /// + /// + /// + /// When set to true will cause internal logging at all levels to be + /// suppressed. This means that no warning or error reports will be logged. + /// This option overrides the setting and + /// disables all debug also. + /// + /// This value can be set by setting the application setting + /// log4net.Internal.Quiet in the application configuration file. + /// + /// + /// The default value is false, i.e. internal logging is not + /// disabled. + /// + /// + /// + /// The following example disables internal logging using the + /// application configuration file : + /// + /// + /// + /// + /// + /// + /// + /// + public static bool QuietMode + { + get { return s_quietMode; } + set { s_quietMode = value; } + } + + /// + /// + /// + public static bool EmitInternalMessages + { + get { return s_emitInternalMessages; } + set { s_emitInternalMessages = value; } + } + + /// + /// Raises the LogReceived event when an internal messages is received. + /// + /// + /// + /// + /// + public static void OnLogReceived(Type source, string prefix, string message, Exception exception) + { + if (LogReceived != null) + { + LogReceived(null, new LogReceivedEventArgs(new LogLog(source, prefix, message, exception))); + } + } + + /// + /// Test if LogLog.Debug is enabled for output. + /// + /// + /// true if Debug is enabled + /// + /// + /// + /// Test if LogLog.Debug is enabled for output. + /// + /// + public static bool IsDebugEnabled + { + get { return s_debugEnabled && !s_quietMode; } } - /// - /// Initializes a new instance of the class. - /// - /// - /// - /// - /// - public LogLog(Type source, string prefix, string message, Exception exception) - { - this.timeStampUtc = DateTime.UtcNow; - - this.source = source; - this.prefix = prefix; - this.message = message; - this.exception = exception; + /// + /// Writes log4net internal debug messages to the + /// standard output stream. + /// + /// + /// The message to log. + /// + /// + /// All internal debug messages are prepended with + /// the string "log4net: ". + /// + /// + public static void Debug(Type source, string message) + { + if (IsDebugEnabled) + { + if (EmitInternalMessages) + { + EmitOutLine(PREFIX + message); + } + + OnLogReceived(source, PREFIX, message, null); + } } /// - /// Initializes static members of the class. - /// Static constructor that initializes logging by reading - /// settings from the application configuration file. - /// - /// - /// - /// The log4net.Internal.Debug application setting - /// controls internal debugging. This setting should be set - /// to true to enable debugging. - /// - /// - /// The log4net.Internal.Quiet application setting - /// suppresses all internal logging including error messages. - /// This setting should be set to true to enable message - /// suppression. - /// - /// - static LogLog() - { -#if !NETCF - try - { - InternalDebugging = OptionConverter.ToBoolean(SystemInfo.GetAppSetting("log4net.Internal.Debug"), false); - QuietMode = OptionConverter.ToBoolean(SystemInfo.GetAppSetting("log4net.Internal.Quiet"), false); - EmitInternalMessages = OptionConverter.ToBoolean(SystemInfo.GetAppSetting("log4net.Internal.Emit"), true); - } - catch (Exception ex) - { - // If an exception is thrown here then it looks like the config file does not - // parse correctly. - // - // We will leave debug OFF and print an Error message - Error(typeof(LogLog), "Exception while reading ConfigurationSettings. Check your .config file is well formed XML.", ex); - } -#endif + /// Writes log4net internal debug messages to the + /// standard output stream. + /// + /// The Type that generated this message. + /// The message to log. + /// An exception to log. + /// + /// + /// All internal debug messages are prepended with + /// the string "log4net: ". + /// + /// + public static void Debug(Type source, string message, Exception exception) + { + if (IsDebugEnabled) + { + if (EmitInternalMessages) + { + EmitOutLine(PREFIX + message); + if (exception != null) + { + EmitOutLine(exception.ToString()); + } + } + + OnLogReceived(source, PREFIX, message, exception); + } } + + /// + /// Test if LogLog.Warn is enabled for output. + /// + /// + /// true if Warn is enabled + /// + /// + /// + /// Test if LogLog.Warn is enabled for output. + /// + /// + public static bool IsWarnEnabled + { + get { return !s_quietMode; } + } + + /// + /// Writes log4net internal warning messages to the + /// standard error stream. + /// + /// The Type that generated this message. + /// The message to log. + /// + /// + /// All internal warning messages are prepended with + /// the string "log4net:WARN ". + /// + /// + public static void Warn(Type source, string message) + { + if (IsWarnEnabled) + { + if (EmitInternalMessages) + { + EmitErrorLine(WARN_PREFIX + message); + } + + OnLogReceived(source, WARN_PREFIX, message, null); + } + } + + /// + /// Writes log4net internal warning messages to the + /// standard error stream. + /// + /// The Type that generated this message. + /// The message to log. + /// An exception to log. + /// + /// + /// All internal warning messages are prepended with + /// the string "log4net:WARN ". + /// + /// + public static void Warn(Type source, string message, Exception exception) + { + if (IsWarnEnabled) + { + if (EmitInternalMessages) + { + EmitErrorLine(WARN_PREFIX + message); + if (exception != null) + { + EmitErrorLine(exception.ToString()); + } + } + + OnLogReceived(source, WARN_PREFIX, message, exception); + } + } - /// - /// Gets or sets a value indicating whether log4net internal logging - /// is enabled or disabled. - /// - /// - /// true if log4net internal logging is enabled, otherwise - /// false. - /// - /// - /// - /// When set to true, internal debug level logging will be - /// displayed. - /// - /// - /// This value can be set by setting the application setting - /// log4net.Internal.Debug in the application configuration - /// file. - /// - /// - /// The default value is false, i.e. debugging is - /// disabled. - /// - /// - /// - /// - /// The following example enables internal debugging using the - /// application configuration file : - /// - /// - /// - /// - /// - /// - /// - /// - /// - public static bool InternalDebugging - { - get { return s_debugEnabled; } - set { s_debugEnabled = value; } - } - - /// - /// Gets or sets a value indicating whether log4net should generate no output - /// from internal logging, not even for errors. - /// - /// - /// true if log4net should generate no output at all from internal - /// logging, otherwise false. - /// - /// - /// - /// When set to true will cause internal logging at all levels to be - /// suppressed. This means that no warning or error reports will be logged. - /// This option overrides the setting and - /// disables all debug also. - /// - /// This value can be set by setting the application setting - /// log4net.Internal.Quiet in the application configuration file. - /// - /// - /// The default value is false, i.e. internal logging is not - /// disabled. - /// - /// - /// - /// The following example disables internal logging using the - /// application configuration file : - /// - /// - /// - /// - /// - /// - /// - /// - public static bool QuietMode - { - get { return s_quietMode; } - set { s_quietMode = value; } - } - - /// - /// - /// - public static bool EmitInternalMessages - { - get { return s_emitInternalMessages; } - set { s_emitInternalMessages = value; } + /// + /// Test if LogLog.Error is enabled for output. + /// + /// + /// true if Error is enabled + /// + /// + /// + /// Test if LogLog.Error is enabled for output. + /// + /// + public static bool IsErrorEnabled + { + get { return !s_quietMode; } } - /// - /// Raises the LogReceived event when an internal messages is received. - /// - /// - /// - /// - /// - public static void OnLogReceived(Type source, string prefix, string message, Exception exception) - { - if (LogReceived != null) - { - LogReceived(null, new LogReceivedEventArgs(new LogLog(source, prefix, message, exception))); - } - } - - /// - /// Gets a value indicating whether test if LogLog.Debug is enabled for output. - /// - /// - /// true if Debug is enabled. - /// - /// - /// - /// Test if LogLog.Debug is enabled for output. - /// - /// - public static bool IsDebugEnabled - { - get { return s_debugEnabled && !s_quietMode; } - } - - /// - /// Writes log4net internal debug messages to the - /// standard output stream. - /// - /// - /// The message to log. - /// - /// - /// All internal debug messages are prepended with - /// the string "log4net: ". - /// - /// - public static void Debug(Type source, string message) - { - if (IsDebugEnabled) - { - if (EmitInternalMessages) - { - EmitOutLine(PREFIX + message); - } - - OnLogReceived(source, PREFIX, message, null); - } - } - - /// - /// Writes log4net internal debug messages to the - /// standard output stream. - /// - /// The Type that generated this message. - /// The message to log. - /// An exception to log. - /// - /// - /// All internal debug messages are prepended with - /// the string "log4net: ". - /// - /// - public static void Debug(Type source, string message, Exception exception) - { - if (IsDebugEnabled) - { - if (EmitInternalMessages) - { - EmitOutLine(PREFIX + message); - if (exception != null) - { - EmitOutLine(exception.ToString()); - } - } - - OnLogReceived(source, PREFIX, message, exception); - } - } - - /// - /// Gets a value indicating whether test if LogLog.Warn is enabled for output. - /// - /// - /// true if Warn is enabled. - /// - /// - /// - /// Test if LogLog.Warn is enabled for output. - /// - /// - public static bool IsWarnEnabled - { - get { return !s_quietMode; } - } - - /// - /// Writes log4net internal warning messages to the - /// standard error stream. - /// - /// The Type that generated this message. - /// The message to log. - /// - /// - /// All internal warning messages are prepended with - /// the string "log4net:WARN ". - /// - /// - public static void Warn(Type source, string message) - { - if (IsWarnEnabled) - { - if (EmitInternalMessages) - { - EmitErrorLine(WARN_PREFIX + message); - } - - OnLogReceived(source, WARN_PREFIX, message, null); - } - } - - /// - /// Writes log4net internal warning messages to the - /// standard error stream. - /// - /// The Type that generated this message. - /// The message to log. - /// An exception to log. - /// - /// - /// All internal warning messages are prepended with - /// the string "log4net:WARN ". - /// - /// - public static void Warn(Type source, string message, Exception exception) - { - if (IsWarnEnabled) - { - if (EmitInternalMessages) - { - EmitErrorLine(WARN_PREFIX + message); - if (exception != null) - { - EmitErrorLine(exception.ToString()); - } - } - - OnLogReceived(source, WARN_PREFIX, message, exception); - } - } - - /// - /// Gets a value indicating whether test if LogLog.Error is enabled for output. - /// - /// - /// true if Error is enabled. - /// - /// - /// - /// Test if LogLog.Error is enabled for output. - /// - /// - public static bool IsErrorEnabled - { - get { return !s_quietMode; } - } - - /// - /// Writes log4net internal error messages to the - /// standard error stream. - /// - /// The Type that generated this message. - /// The message to log. - /// - /// - /// All internal error messages are prepended with - /// the string "log4net:ERROR ". - /// - /// - public static void Error(Type source, string message) - { - if (IsErrorEnabled) - { - if (EmitInternalMessages) - { - EmitErrorLine(ERR_PREFIX + message); - } - - OnLogReceived(source, ERR_PREFIX, message, null); - } - } - - /// - /// Writes log4net internal error messages to the - /// standard error stream. - /// - /// The Type that generated this message. - /// The message to log. - /// An exception to log. - /// - /// - /// All internal debug messages are prepended with - /// the string "log4net:ERROR ". - /// - /// - public static void Error(Type source, string message, Exception exception) - { - if (IsErrorEnabled) - { - if (EmitInternalMessages) - { - EmitErrorLine(ERR_PREFIX + message); - if (exception != null) - { - EmitErrorLine(exception.ToString()); - } - } - - OnLogReceived(source, ERR_PREFIX, message, exception); - } + /// + /// Writes log4net internal error messages to the + /// standard error stream. + /// + /// The Type that generated this message. + /// The message to log. + /// + /// + /// All internal error messages are prepended with + /// the string "log4net:ERROR ". + /// + /// + public static void Error(Type source, string message) + { + if (IsErrorEnabled) + { + if (EmitInternalMessages) + { + EmitErrorLine(ERR_PREFIX + message); + } + + OnLogReceived(source, ERR_PREFIX, message, null); + } + } + + /// + /// Writes log4net internal error messages to the + /// standard error stream. + /// + /// The Type that generated this message. + /// The message to log. + /// An exception to log. + /// + /// + /// All internal debug messages are prepended with + /// the string "log4net:ERROR ". + /// + /// + public static void Error(Type source, string message, Exception exception) + { + if (IsErrorEnabled) + { + if (EmitInternalMessages) + { + EmitErrorLine(ERR_PREFIX + message); + if (exception != null) + { + EmitErrorLine(exception.ToString()); + } + } + + OnLogReceived(source, ERR_PREFIX, message, exception); + } } - /// - /// Writes output to the standard output stream. - /// - /// The message to log. - /// - /// - /// Writes to both Console.Out and System.Diagnostics.Trace. - /// Note that the System.Diagnostics.Trace is not supported - /// on the Compact Framework. - /// - /// - /// If the AppDomain is not configured with a config file then - /// the call to System.Diagnostics.Trace may fail. This is only - /// an issue if you are programmatically creating your own AppDomains. - /// - /// - private static void EmitOutLine(string message) - { - try - { -#if NETCF - Console.WriteLine(message); - //System.Diagnostics.Debug.WriteLine(message); -#else - Console.Out.WriteLine(message); - Trace.WriteLine(message); -#endif - } - catch - { - // Ignore exception, what else can we do? Not really a good idea to propagate back to the caller - } - } - - /// - /// Writes output to the standard error stream. - /// - /// The message to log. - /// - /// - /// Writes to both Console.Error and System.Diagnostics.Trace. - /// Note that the System.Diagnostics.Trace is not supported - /// on the Compact Framework. - /// - /// - /// If the AppDomain is not configured with a config file then - /// the call to System.Diagnostics.Trace may fail. This is only - /// an issue if you are programmatically creating your own AppDomains. - /// - /// - private static void EmitErrorLine(string message) - { - try - { -#if NETCF - Console.WriteLine(message); - //System.Diagnostics.Debug.WriteLine(message); -#else - Console.Error.WriteLine(message); - Trace.WriteLine(message); -#endif - } - catch - { - // Ignore exception, what else can we do? Not really a good idea to propagate back to the caller - } + /// + /// Writes output to the standard output stream. + /// + /// The message to log. + /// + /// + /// Writes to both Console.Out and System.Diagnostics.Trace. + /// Note that the System.Diagnostics.Trace is not supported + /// on the Compact Framework. + /// + /// + /// If the AppDomain is not configured with a config file then + /// the call to System.Diagnostics.Trace may fail. This is only + /// an issue if you are programmatically creating your own AppDomains. + /// + /// + private static void EmitOutLine(string message) + { + try + { +#if NETCF + Console.WriteLine(message); + //System.Diagnostics.Debug.WriteLine(message); +#else + Console.Out.WriteLine(message); + Trace.WriteLine(message); +#endif + } + catch + { + // Ignore exception, what else can we do? Not really a good idea to propagate back to the caller + } } - /// - /// Default debug level. - /// - private static bool s_debugEnabled = false; - - /// - /// In quietMode not even errors generate any output. - /// - private static bool s_quietMode = false; - - private static bool s_emitInternalMessages = true; - - private const string PREFIX = "log4net: "; - private const string ERR_PREFIX = "log4net:ERROR "; - private const string WARN_PREFIX = "log4net:WARN "; - - /// - /// Subscribes to the LogLog.LogReceived event and stores messages - /// to the supplied IList instance. - /// - public class LogReceivedAdapter : IDisposable - { - private readonly IList items; + /// + /// Writes output to the standard error stream. + /// + /// The message to log. + /// + /// + /// Writes to both Console.Error and System.Diagnostics.Trace. + /// Note that the System.Diagnostics.Trace is not supported + /// on the Compact Framework. + /// + /// + /// If the AppDomain is not configured with a config file then + /// the call to System.Diagnostics.Trace may fail. This is only + /// an issue if you are programmatically creating your own AppDomains. + /// + /// + private static void EmitErrorLine(string message) + { + try + { +#if NETCF + Console.WriteLine(message); + //System.Diagnostics.Debug.WriteLine(message); +#else + Console.Error.WriteLine(message); + Trace.WriteLine(message); +#endif + } + catch + { + // Ignore exception, what else can we do? Not really a good idea to propagate back to the caller + } + } + + /// + /// Default debug level + /// + private static bool s_debugEnabled = false; + + /// + /// In quietMode not even errors generate any output. + /// + private static bool s_quietMode = false; + + private static bool s_emitInternalMessages = true; + + private const string PREFIX = "log4net: "; + private const string ERR_PREFIX = "log4net:ERROR "; + private const string WARN_PREFIX = "log4net:WARN "; + + /// + /// Subscribes to the LogLog.LogReceived event and stores messages + /// to the supplied IList instance. + /// + public class LogReceivedAdapter : IDisposable + { + private readonly IList items; private readonly LogReceivedEventHandler handler; /// - /// Initializes a new instance of the class. - /// - /// - public LogReceivedAdapter(IList items) - { - this.items = items; - - this.handler = new LogReceivedEventHandler(this.LogLog_LogReceived); - - LogReceived += this.handler; - } - - private void LogLog_LogReceived(object source, LogReceivedEventArgs e) - { - this.items.Add(e.LogLog); - } - - /// - /// - /// - public IList Items - { - get { return this.items; } - } - - /// - /// - /// - public void Dispose() - { - LogReceived -= this.handler; - } - } - } - - /// - /// - /// - public class LogReceivedEventArgs : EventArgs - { + /// + /// + /// + public LogReceivedAdapter(IList items) + { + this.items = items; + + this.handler = new LogReceivedEventHandler(this.LogLog_LogReceived); + + LogReceived += this.handler; + } + + void LogLog_LogReceived(object source, LogReceivedEventArgs e) + { + this.items.Add(e.LogLog); + } + + /// + /// + /// + public IList Items + { + get { return this.items; } + } + + /// + /// + /// + public void Dispose() + { + LogReceived -= this.handler; + } + } + } + + /// + /// + /// + public class LogReceivedEventArgs : EventArgs + { private readonly LogLog loglog; /// - /// Initializes a new instance of the class. - /// - /// - public LogReceivedEventArgs(LogLog loglog) - { - this.loglog = loglog; - } - - /// - /// - /// - public LogLog LogLog - { - get { return this.loglog; } - } - } -} + /// + /// + /// + public LogReceivedEventArgs(LogLog loglog) + { + this.loglog = loglog; + } + + /// + /// + /// + public LogLog LogLog + { + get { return this.loglog; } + } + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/LogicalThreadContextProperties.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/LogicalThreadContextProperties.cs index 6d873d142a2..7f42b960001 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/LogicalThreadContextProperties.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/LogicalThreadContextProperties.cs @@ -1,248 +1,259 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -// .NET Compact Framework 1.0 has no support for System.Runtime.Remoting.Messaging.CallContext -#if !NETCF - -using System; -using System.Runtime.Remoting.Messaging; -using System.Security; - -namespace log4net.Util -{ - /// - /// Implementation of Properties collection for the . - /// - /// - /// - /// Class implements a collection of properties that is specific to each thread. - /// The class is not synchronized as each thread has its own . - /// - /// - /// This class stores its properties in a slot on the named - /// log4net.Util.LogicalThreadContextProperties. - /// - /// - /// The requires a link time - /// for the - /// . - /// If the calling code does not have this permission then this context will be disabled. - /// It will not store any property values set on it. - /// - /// - /// Nicko Cadell. - public sealed class LogicalThreadContextProperties : ContextPropertiesBase - { - private const string c_SlotName = "log4net.Util.LogicalThreadContextProperties"; - - /// - /// Flag used to disable this context if we don't have permission to access the CallContext. - /// +// .NET Compact Framework 1.0 has no support for System.Runtime.Remoting.Messaging.CallContext +#if !NETCF + +using System; +#if !NETSTANDARD +using System.Runtime.Remoting.Messaging; +#endif +using System.Security; +#if NETSTANDARD +using System.Threading; +#endif + +namespace log4net.Util +{ + /// + /// Implementation of Properties collection for the + /// + /// + /// + /// Class implements a collection of properties that is specific to each thread. + /// The class is not synchronized as each thread has its own . + /// + /// + /// This class stores its properties in a slot on the named + /// log4net.Util.LogicalThreadContextProperties. + /// + /// + /// For .NET Standard 1.3 this class uses + /// System.Threading.AsyncLocal rather than . + /// + /// + /// The requires a link time + /// for the + /// . + /// If the calling code does not have this permission then this context will be disabled. + /// It will not store any property values set on it. + /// + /// + /// Nicko Cadell + public sealed class LogicalThreadContextProperties : ContextPropertiesBase + { +#if NETSTANDARD + private static readonly AsyncLocal AsyncLocalDictionary = new AsyncLocal(); +#else + private const string c_SlotName = "log4net.Util.LogicalThreadContextProperties"; +#endif + + /// + /// Flag used to disable this context if we don't have permission to access the CallContext. + /// private bool m_disabled = false; /// - /// Initializes a new instance of the class. - /// Constructor. - /// - /// - /// - /// Initializes a new instance of the class. - /// - /// - internal LogicalThreadContextProperties() - { + /// Constructor + /// + /// + /// + /// Initializes a new instance of the class. + /// + /// + internal LogicalThreadContextProperties() + { } - /// - /// Gets or sets the value of a property. - /// - /// - /// The value for the property with the specified key. - /// - /// - /// - /// Get or set the property value for the specified. - /// - /// - public override object this[string key] - { - get - { - // Don't create the dictionary if it does not already exist - PropertiesDictionary dictionary = this.GetProperties(false); - if (dictionary != null) - { - return dictionary[key]; - } - - return null; - } - - set - { - // Force the dictionary to be created - PropertiesDictionary props = this.GetProperties(true); - - // Reason for cloning the dictionary below: object instances set on the CallContext - // need to be immutable to correctly flow through async/await - PropertiesDictionary immutableProps = new PropertiesDictionary(props); - immutableProps[key] = value; - SetCallContextData(immutableProps); - } + /// + /// Gets or sets the value of a property + /// + /// + /// The value for the property with the specified key + /// + /// + /// + /// Get or set the property value for the specified. + /// + /// + public override object this[string key] + { + get + { + // Don't create the dictionary if it does not already exist + PropertiesDictionary dictionary = this.GetProperties(false); + if (dictionary != null) + { + return dictionary[key]; + } + return null; + } + set + { + // Force the dictionary to be created + PropertiesDictionary props = this.GetProperties(true); + // Reason for cloning the dictionary below: object instances set on the CallContext + // need to be immutable to correctly flow through async/await + PropertiesDictionary immutableProps = new PropertiesDictionary(props); + immutableProps[key] = value; + SetLogicalProperties(immutableProps); + } } - /// - /// Remove a property. - /// - /// the key for the entry to remove. - /// - /// - /// Remove the value for the specified from the context. - /// - /// - public void Remove(string key) - { - PropertiesDictionary dictionary = this.GetProperties(false); - if (dictionary != null) - { - PropertiesDictionary immutableProps = new PropertiesDictionary(dictionary); - immutableProps.Remove(key); - SetCallContextData(immutableProps); - } - } - - /// - /// Clear all the context properties. - /// - /// - /// - /// Clear all the context properties. - /// - /// - public void Clear() - { - PropertiesDictionary dictionary = this.GetProperties(false); - if (dictionary != null) - { - PropertiesDictionary immutableProps = new PropertiesDictionary(); - SetCallContextData(immutableProps); - } + /// + /// Remove a property + /// + /// the key for the entry to remove + /// + /// + /// Remove the value for the specified from the context. + /// + /// + public void Remove(string key) + { + PropertiesDictionary dictionary = this.GetProperties(false); + if (dictionary != null) + { + PropertiesDictionary immutableProps = new PropertiesDictionary(dictionary); + immutableProps.Remove(key); + SetLogicalProperties(immutableProps); + } } - /// - /// Get the PropertiesDictionary stored in the LocalDataStoreSlot for this thread. - /// - /// create the dictionary if it does not exist, otherwise return null if is does not exist. - /// the properties for this thread. - /// - /// - /// The collection returned is only to be used on the calling thread. If the - /// caller needs to share the collection between different threads then the - /// caller must clone the collection before doings so. - /// - /// - internal PropertiesDictionary GetProperties(bool create) - { - if (!this.m_disabled) - { - try - { - PropertiesDictionary properties = GetCallContextData(); - if (properties == null && create) - { - properties = new PropertiesDictionary(); - SetCallContextData(properties); - } - - return properties; - } - catch (SecurityException secEx) - { - this.m_disabled = true; - - // Thrown if we don't have permission to read or write the CallContext - LogLog.Warn(declaringType, "SecurityException while accessing CallContext. Disabling LogicalThreadContextProperties", secEx); - } - } - - // Only get here is we are disabled because of a security exception - if (create) - { - return new PropertiesDictionary(); - } + /// + /// Clear all the context properties + /// + /// + /// + /// Clear all the context properties + /// + /// + public void Clear() + { + PropertiesDictionary dictionary = this.GetProperties(false); + if (dictionary != null) + { + PropertiesDictionary immutableProps = new PropertiesDictionary(); + SetLogicalProperties(immutableProps); + } + } - return null; + /// + /// Get the PropertiesDictionary stored in the LocalDataStoreSlot for this thread. + /// + /// create the dictionary if it does not exist, otherwise return null if is does not exist + /// the properties for this thread + /// + /// + /// The collection returned is only to be used on the calling thread. If the + /// caller needs to share the collection between different threads then the + /// caller must clone the collection before doings so. + /// + /// + internal PropertiesDictionary GetProperties(bool create) + { + if (!this.m_disabled) + { + try + { + PropertiesDictionary properties = GetLogicalProperties(); + if (properties == null && create) + { + properties = new PropertiesDictionary(); + SetLogicalProperties(properties); + } + return properties; + } + catch (SecurityException secEx) + { + this.m_disabled = true; + + // Thrown if we don't have permission to read or write the CallContext + LogLog.Warn(declaringType, "SecurityException while accessing CallContext. Disabling LogicalThreadContextProperties", secEx); + } + } + + // Only get here is we are disabled because of a security exception + if (create) + { + return new PropertiesDictionary(); + } + return null; } - /// - /// Gets the call context get data. - /// - /// The peroperties dictionary stored in the call context. - /// - /// The method has a - /// security link demand, therfore we must put the method call in a seperate method - /// that we can wrap in an exception handler. - /// -#if NET_4_0 || MONO_4_0 - [System.Security.SecuritySafeCritical] -#endif - private static PropertiesDictionary GetCallContextData() - { -#if NET_2_0 || MONO_2_0 || MONO_3_5 || MONO_4_0 - return CallContext.LogicalGetData(c_SlotName) as PropertiesDictionary; -#else - return CallContext.GetData(c_SlotName) as PropertiesDictionary; -#endif + /// + /// Gets the call context get data. + /// + /// The peroperties dictionary stored in the call context + /// + /// The method has a + /// security link demand, therfore we must put the method call in a seperate method + /// that we can wrap in an exception handler. + /// +#if NET_4_0 || MONO_4_0 || NETSTANDARD + [SecuritySafeCritical] +#endif + private static PropertiesDictionary GetLogicalProperties() + { +#if NETSTANDARD + return AsyncLocalDictionary.Value; +#elif NET_2_0 || MONO_2_0 || MONO_3_5 || MONO_4_0 + return CallContext.LogicalGetData(c_SlotName) as PropertiesDictionary; +#else + return CallContext.GetData(c_SlotName) as PropertiesDictionary; +#endif } - /// - /// Sets the call context data. - /// - /// The properties. - /// - /// The method has a - /// security link demand, therfore we must put the method call in a seperate method - /// that we can wrap in an exception handler. - /// -#if NET_4_0 || MONO_4_0 - [System.Security.SecuritySafeCritical] -#endif - private static void SetCallContextData(PropertiesDictionary properties) - { -#if NET_2_0 || MONO_2_0 || MONO_3_5 || MONO_4_0 - CallContext.LogicalSetData(c_SlotName, properties); -#else - CallContext.SetData(c_SlotName, properties); -#endif + /// + /// Sets the call context data. + /// + /// The properties. + /// + /// The method has a + /// security link demand, therfore we must put the method call in a seperate method + /// that we can wrap in an exception handler. + /// +#if NET_4_0 || MONO_4_0 || NETSTANDARD + [SecuritySafeCritical] +#endif + private static void SetLogicalProperties(PropertiesDictionary properties) + { +#if NETSTANDARD + AsyncLocalDictionary.Value = properties; +#elif NET_2_0 || MONO_2_0 || MONO_3_5 || MONO_4_0 + CallContext.LogicalSetData(c_SlotName, properties); +#else + CallContext.SetData(c_SlotName, properties); +#endif } - /// - /// The fully qualified type of the LogicalThreadContextProperties class. - /// - /// - /// Used by the internal logger to record the Type of the - /// log message. - /// + /// + /// The fully qualified type of the LogicalThreadContextProperties class. + /// + /// + /// Used by the internal logger to record the Type of the + /// log message. + /// private static readonly Type declaringType = typeof(LogicalThreadContextProperties); - } -} - -#endif + } +} + +#endif diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/LogicalThreadContextStack.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/LogicalThreadContextStack.cs index 2c9870c8388..a7e55f9939b 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/LogicalThreadContextStack.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/LogicalThreadContextStack.cs @@ -1,392 +1,386 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#if !NETCF -using System; -using System.Collections; +#if !NETCF +using System; +using System.Collections; -using log4net.Core; - -namespace log4net.Util +using log4net.Core; + +namespace log4net.Util { - /// - /// Delegate type used for LogicalThreadContextStack's callbacks. - /// -#if NET_2_0 || MONO_2_0 + + /// + /// Delegate type used for LogicalThreadContextStack's callbacks. + /// + #if NET_2_0 || MONO_2_0 || NETSTANDARD public delegate void TwoArgAction(T1 t1, T2 t2); -#else - public delegate void TwoArgAction(string t1, LogicalThreadContextStack t2); -#endif + #else + public delegate void TwoArgAction(string t1, LogicalThreadContextStack t2); + #endif - /// - /// Implementation of Stack for the . - /// - /// - /// - /// Implementation of Stack for the . - /// - /// - /// Nicko Cadell. - public sealed class LogicalThreadContextStack : IFixingRequired + /// + /// Implementation of Stack for the + /// + /// + /// + /// Implementation of Stack for the + /// + /// + /// Nicko Cadell + public sealed class LogicalThreadContextStack : IFixingRequired { - /// - /// The stack store. - /// - private Stack m_stack = new Stack(); - - /// - /// The name of this within the - /// . - /// + /// + /// The stack store. + /// + private Stack m_stack = new Stack(); + + /// + /// The name of this within the + /// . + /// private string m_propertyKey; - /// - /// The callback used to let the register a - /// new instance of a . - /// -#if NET_2_0 || MONO_2_0 + /// + /// The callback used to let the register a + /// new instance of a . + /// + #if NET_2_0 || MONO_2_0 || NETSTANDARD private TwoArgAction m_registerNew; -#else - private TwoArgAction m_registerNew; -#endif + #else + private TwoArgAction m_registerNew; + #endif /// - /// Initializes a new instance of the class. - /// Internal constructor. - /// - /// - /// - /// Initializes a new instance of the class. - /// - /// -#if NET_2_0 || MONO_2_0 + /// Internal constructor + /// + /// + /// + /// Initializes a new instance of the class. + /// + /// + #if NET_2_0 || MONO_2_0 || NETSTANDARD internal LogicalThreadContextStack(string propertyKey, TwoArgAction registerNew) -#else - internal LogicalThreadContextStack(string propertyKey, TwoArgAction registerNew) -#endif - { - this.m_propertyKey = propertyKey; - this.m_registerNew = registerNew; + #else + internal LogicalThreadContextStack(string propertyKey, TwoArgAction registerNew) + #endif + { + this.m_propertyKey = propertyKey; + this.m_registerNew = registerNew; } - /// - /// Gets the number of messages in the stack. - /// - /// - /// The current number of messages in the stack. - /// - /// - /// - /// The current number of messages in the stack. That is - /// the number of times has been called - /// minus the number of times has been called. - /// - /// - public int Count - { - get { return this.m_stack.Count; } + /// + /// The number of messages in the stack + /// + /// + /// The current number of messages in the stack + /// + /// + /// + /// The current number of messages in the stack. That is + /// the number of times has been called + /// minus the number of times has been called. + /// + /// + public int Count + { + get { return this.m_stack.Count; } } - /// - /// Clears all the contextual information held in this stack. - /// - /// - /// - /// Clears all the contextual information held in this stack. - /// Only call this if you think that this thread is being reused after - /// a previous call execution which may not have completed correctly. - /// You do not need to use this method if you always guarantee to call - /// the method of the - /// returned from even in exceptional circumstances, - /// for example by using the using(log4net.LogicalThreadContext.Stacks["NDC"].Push("Stack_Message")) - /// syntax. - /// - /// - public void Clear() - { - this.m_registerNew(this.m_propertyKey, new LogicalThreadContextStack(this.m_propertyKey, this.m_registerNew)); - } - - /// - /// Removes the top context from this stack. - /// - /// The message in the context that was removed from the top of this stack. - /// - /// - /// Remove the top context from this stack, and return - /// it to the caller. If this stack is empty then an - /// empty string (not ) is returned. - /// - /// - public string Pop() - { - // copy current stack - Stack stack = new Stack(new Stack(this.m_stack)); - string result = string.Empty; - if (stack.Count > 0) - { - result = ((StackFrame)stack.Pop()).Message; - } + /// + /// Clears all the contextual information held in this stack. + /// + /// + /// + /// Clears all the contextual information held in this stack. + /// Only call this if you think that this thread is being reused after + /// a previous call execution which may not have completed correctly. + /// You do not need to use this method if you always guarantee to call + /// the method of the + /// returned from even in exceptional circumstances, + /// for example by using the using(log4net.LogicalThreadContext.Stacks["NDC"].Push("Stack_Message")) + /// syntax. + /// + /// + public void Clear() + { + this.m_registerNew(this.m_propertyKey, new LogicalThreadContextStack(this.m_propertyKey, this.m_registerNew)); + } + + /// + /// Removes the top context from this stack. + /// + /// The message in the context that was removed from the top of this stack. + /// + /// + /// Remove the top context from this stack, and return + /// it to the caller. If this stack is empty then an + /// empty string (not ) is returned. + /// + /// + public string Pop() + { + // copy current stack + Stack stack = new Stack(new Stack(this.m_stack)); + string result = string.Empty; + if (stack.Count > 0) + { + result = ((StackFrame)(stack.Pop())).Message; + } + LogicalThreadContextStack ltcs = new LogicalThreadContextStack(this.m_propertyKey, this.m_registerNew); + ltcs.m_stack = stack; + this.m_registerNew(this.m_propertyKey, ltcs); + return result; + } + + /// + /// Pushes a new context message into this stack. + /// + /// The new context message. + /// + /// An that can be used to clean up the context stack. + /// + /// + /// + /// Pushes a new context onto this stack. An + /// is returned that can be used to clean up this stack. This + /// can be easily combined with the using keyword to scope the + /// context. + /// + /// + /// Simple example of using the Push method with the using keyword. + /// + /// using(log4net.LogicalThreadContext.Stacks["NDC"].Push("Stack_Message")) + /// { + /// log.Warn("This should have an ThreadContext Stack message"); + /// } + /// + /// + public IDisposable Push(string message) + { + // do modifications on a copy + Stack stack = new Stack(new Stack(this.m_stack)); + stack.Push(new StackFrame(message, (stack.Count > 0) ? (StackFrame)stack.Peek() : null)); + + LogicalThreadContextStack contextStack = new LogicalThreadContextStack(this.m_propertyKey, this.m_registerNew); + contextStack.m_stack = stack; + this.m_registerNew(this.m_propertyKey, contextStack); + return new AutoPopStackFrame(contextStack, stack.Count - 1); + } + + /// + /// Gets the current context information for this stack. + /// + /// The current context information. + internal string GetFullMessage() + { + Stack stack = this.m_stack; + if (stack.Count > 0) + { + return ((StackFrame)(stack.Peek())).FullMessage; + } + return null; + } - LogicalThreadContextStack ltcs = new LogicalThreadContextStack(this.m_propertyKey, this.m_registerNew); - ltcs.m_stack = stack; - this.m_registerNew(this.m_propertyKey, ltcs); - return result; - } - - /// - /// Pushes a new context message into this stack. - /// - /// The new context message. - /// - /// An that can be used to clean up the context stack. - /// - /// - /// - /// Pushes a new context onto this stack. An - /// is returned that can be used to clean up this stack. This - /// can be easily combined with the using keyword to scope the - /// context. - /// - /// - /// Simple example of using the Push method with the using keyword. - /// - /// using(log4net.LogicalThreadContext.Stacks["NDC"].Push("Stack_Message")) - /// { - /// log.Warn("This should have an ThreadContext Stack message"); - /// } - /// - /// - public IDisposable Push(string message) - { - // do modifications on a copy - Stack stack = new Stack(new Stack(this.m_stack)); - stack.Push(new StackFrame(message, (stack.Count > 0) ? (StackFrame)stack.Peek() : null)); - - LogicalThreadContextStack contextStack = new LogicalThreadContextStack(this.m_propertyKey, this.m_registerNew); - contextStack.m_stack = stack; - this.m_registerNew(this.m_propertyKey, contextStack); - return new AutoPopStackFrame(contextStack, stack.Count - 1); + /// + /// Gets and sets the internal stack used by this + /// + /// The internal storage stack + /// + /// + /// This property is provided only to support backward compatability + /// of the . Tytpically the internal stack should not + /// be modified. + /// + /// + internal Stack InternalStack + { + get { return this.m_stack; } + set { this.m_stack = value; } } - /// - /// Gets the current context information for this stack. - /// - /// The current context information. - internal string GetFullMessage() - { - Stack stack = this.m_stack; - if (stack.Count > 0) - { - return ((StackFrame)stack.Peek()).FullMessage; - } + /// + /// Gets the current context information for this stack. + /// + /// Gets the current context information + /// + /// + /// Gets the current context information for this stack. + /// + /// + public override string ToString() + { + return this.GetFullMessage(); + } - return null; - } - - /// - /// Gets or sets and sets the internal stack used by this . - /// - /// The internal storage stack. - /// - /// - /// This property is provided only to support backward compatability - /// of the . Tytpically the internal stack should not - /// be modified. - /// - /// - internal Stack InternalStack - { - get { return this.m_stack; } - set { this.m_stack = value; } + /// + /// Get a portable version of this object + /// + /// the portable instance of this object + /// + /// + /// Get a cross thread portable version of this object + /// + /// + object IFixingRequired.GetFixedObject() + { + return this.GetFullMessage(); } - /// - /// Gets the current context information for this stack. - /// - /// Gets the current context information. - /// - /// - /// Gets the current context information for this stack. - /// - /// - public override string ToString() - { - return this.GetFullMessage(); - } - - /// - /// Get a portable version of this object. - /// - /// the portable instance of this object. - /// - /// - /// Get a cross thread portable version of this object. - /// - /// - object IFixingRequired.GetFixedObject() - { - return this.GetFullMessage(); - } - - /// - /// Inner class used to represent a single context frame in the stack. - /// - /// - /// - /// Inner class used to represent a single context frame in the stack. - /// - /// - private sealed class StackFrame + /// + /// Inner class used to represent a single context frame in the stack. + /// + /// + /// + /// Inner class used to represent a single context frame in the stack. + /// + /// + private sealed class StackFrame { - private readonly string m_message; - private readonly StackFrame m_parent; + private readonly string m_message; + private readonly StackFrame m_parent; private string m_fullMessage = null; /// - /// Initializes a new instance of the class. - /// Constructor. - /// - /// The message for this context. - /// The parent context in the chain. - /// - /// - /// Initializes a new instance of the class - /// with the specified message and parent context. - /// - /// - internal StackFrame(string message, StackFrame parent) - { - this.m_message = message; - this.m_parent = parent; - - if (parent == null) - { - this.m_fullMessage = message; - } + /// Constructor + /// + /// The message for this context. + /// The parent context in the chain. + /// + /// + /// Initializes a new instance of the class + /// with the specified message and parent context. + /// + /// + internal StackFrame(string message, StackFrame parent) + { + this.m_message = message; + this.m_parent = parent; + + if (parent == null) + { + this.m_fullMessage = message; + } } - /// - /// Gets get the message. - /// - /// The message. - /// - /// - /// Get the message. - /// - /// - internal string Message - { - get { return this.m_message; } - } - - /// - /// Gets the full text of the context down to the root level. - /// - /// - /// The full text of the context down to the root level. - /// - /// - /// - /// Gets the full text of the context down to the root level. - /// - /// - internal string FullMessage - { - get - { - if (this.m_fullMessage == null && this.m_parent != null) - { - this.m_fullMessage = string.Concat(this.m_parent.FullMessage, " ", this.m_message); - } + /// + /// Get the message. + /// + /// The message. + /// + /// + /// Get the message. + /// + /// + internal string Message + { + get { return this.m_message; } + } - return this.m_fullMessage; - } + /// + /// Gets the full text of the context down to the root level. + /// + /// + /// The full text of the context down to the root level. + /// + /// + /// + /// Gets the full text of the context down to the root level. + /// + /// + internal string FullMessage + { + get + { + if (this.m_fullMessage == null && this.m_parent != null) + { + this.m_fullMessage = string.Concat(this.m_parent.FullMessage, " ", this.m_message); + } + return this.m_fullMessage; + } } - } - - /// - /// Struct returned from the method. - /// - /// - /// - /// This struct implements the and is designed to be used - /// with the pattern to remove the stack frame at the end of the scope. - /// - /// - private struct AutoPopStackFrame : IDisposable + } + + /// + /// Struct returned from the method. + /// + /// + /// + /// This struct implements the and is designed to be used + /// with the pattern to remove the stack frame at the end of the scope. + /// + /// + private struct AutoPopStackFrame : IDisposable { - /// - /// The depth to trim the stack to when this instance is disposed. - /// - private int m_frameDepth; - - /// - /// The outer LogicalThreadContextStack. - /// + /// + /// The depth to trim the stack to when this instance is disposed + /// + private int m_frameDepth; + + /// + /// The outer LogicalThreadContextStack. + /// private LogicalThreadContextStack m_logicalThreadContextStack; /// - /// Initializes a new instance of the struct. - /// Constructor. - /// - /// The internal stack used by the ThreadContextStack. - /// The depth to return the stack to when this object is disposed. - /// - /// - /// Initializes a new instance of the class with - /// the specified stack and return depth. - /// - /// - internal AutoPopStackFrame(LogicalThreadContextStack logicalThreadContextStack, int frameDepth) - { - this.m_frameDepth = frameDepth; - this.m_logicalThreadContextStack = logicalThreadContextStack; + /// Constructor + /// + /// The internal stack used by the ThreadContextStack. + /// The depth to return the stack to when this object is disposed. + /// + /// + /// Initializes a new instance of the class with + /// the specified stack and return depth. + /// + /// + internal AutoPopStackFrame(LogicalThreadContextStack logicalThreadContextStack, int frameDepth) + { + this.m_frameDepth = frameDepth; + this.m_logicalThreadContextStack = logicalThreadContextStack; } - /// - /// Returns the stack to the correct depth. - /// - /// - /// - /// Returns the stack to the correct depth. - /// - /// - public void Dispose() - { - if (this.m_frameDepth >= 0 && this.m_logicalThreadContextStack.m_stack != null) - { - Stack stack = new Stack(new Stack(this.m_logicalThreadContextStack.m_stack)); - while (stack.Count > this.m_frameDepth) - { - stack.Pop(); - } - - LogicalThreadContextStack ltcs = new LogicalThreadContextStack(this.m_logicalThreadContextStack.m_propertyKey, this.m_logicalThreadContextStack.m_registerNew); - ltcs.m_stack = stack; - this.m_logicalThreadContextStack.m_registerNew( - this.m_logicalThreadContextStack.m_propertyKey, - ltcs); - } + /// + /// Returns the stack to the correct depth. + /// + /// + /// + /// Returns the stack to the correct depth. + /// + /// + public void Dispose() + { + if (this.m_frameDepth >= 0 && this.m_logicalThreadContextStack.m_stack != null) + { + Stack stack = new Stack(new Stack(this.m_logicalThreadContextStack.m_stack)); + while (stack.Count > this.m_frameDepth) + { + stack.Pop(); + } + LogicalThreadContextStack ltcs = new LogicalThreadContextStack(this.m_logicalThreadContextStack.m_propertyKey, this.m_logicalThreadContextStack.m_registerNew); + ltcs.m_stack = stack; + this.m_logicalThreadContextStack.m_registerNew(this.m_logicalThreadContextStack.m_propertyKey, + ltcs); + } } - } - } -} -#endif + } + + } +} +#endif diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/LogicalThreadContextStacks.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/LogicalThreadContextStacks.cs index b0083a05eb2..9b10ace080d 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/LogicalThreadContextStacks.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/LogicalThreadContextStacks.cs @@ -1,129 +1,127 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#if !NETCF -using System; -using System.Collections; - -namespace log4net.Util -{ - /// - /// Implementation of Stacks collection for the . - /// - /// - /// - /// Implementation of Stacks collection for the . - /// - /// - /// Nicko Cadell. - public sealed class LogicalThreadContextStacks - { +#if !NETCF +using System; + +namespace log4net.Util +{ + /// + /// Implementation of Stacks collection for the + /// + /// + /// + /// Implementation of Stacks collection for the + /// + /// + /// Nicko Cadell + public sealed class LogicalThreadContextStacks + { private readonly LogicalThreadContextProperties m_properties; /// - /// Initializes a new instance of the class. - /// Internal constructor. - /// - /// - /// - /// Initializes a new instance of the class. - /// - /// - internal LogicalThreadContextStacks(LogicalThreadContextProperties properties) - { - this.m_properties = properties; + /// Internal constructor + /// + /// + /// + /// Initializes a new instance of the class. + /// + /// + internal LogicalThreadContextStacks(LogicalThreadContextProperties properties) + { + this.m_properties = properties; } - /// - /// Gets the named thread context stack. - /// - /// - /// The named stack. - /// - /// - /// - /// Gets the named thread context stack. - /// - /// - public LogicalThreadContextStack this[string key] - { - get - { - LogicalThreadContextStack stack = null; - - object propertyValue = this.m_properties[key]; - if (propertyValue == null) - { - // Stack does not exist, create -#if NET_2_0 || MONO_2_0 - stack = new LogicalThreadContextStack(key, this.registerNew); -#else - stack = new LogicalThreadContextStack(key, new TwoArgAction(registerNew)); -#endif - this.m_properties[key] = stack; - } - else - { - // Look for existing stack - stack = propertyValue as LogicalThreadContextStack; - if (stack == null) - { - // Property is not set to a stack! - string propertyValueString = SystemInfo.NullText; - - try - { - propertyValueString = propertyValue.ToString(); - } - catch - { - } - - LogLog.Error(declaringType, "ThreadContextStacks: Request for stack named [" + key + "] failed because a property with the same name exists which is a [" + propertyValue.GetType().Name + "] with value [" + propertyValueString + "]"); - -#if NET_2_0 || MONO_2_0 - stack = new LogicalThreadContextStack(key, this.registerNew); -#else - stack = new LogicalThreadContextStack(key, new TwoArgAction(registerNew)); -#endif - } - } - - return stack; - } + /// + /// Gets the named thread context stack + /// + /// + /// The named stack + /// + /// + /// + /// Gets the named thread context stack + /// + /// + public LogicalThreadContextStack this[string key] + { + get + { + LogicalThreadContextStack stack = null; + + object propertyValue = this.m_properties[key]; + if (propertyValue == null) + { + // Stack does not exist, create +#if NET_2_0 || MONO_2_0 || NETSTANDARD + stack = new LogicalThreadContextStack(key, this.registerNew); +#else + stack = new LogicalThreadContextStack(key, new TwoArgAction(registerNew)); +#endif + this.m_properties[key] = stack; + } + else + { + // Look for existing stack + stack = propertyValue as LogicalThreadContextStack; + if (stack == null) + { + // Property is not set to a stack! + string propertyValueString = SystemInfo.NullText; + + try + { + propertyValueString = propertyValue.ToString(); + } + catch + { + } + + LogLog.Error(declaringType, "ThreadContextStacks: Request for stack named [" + key + "] failed because a property with the same name exists which is a [" + propertyValue.GetType().Name + "] with value [" + propertyValueString + "]"); + +#if NET_2_0 || MONO_2_0 || NETSTANDARD + stack = new LogicalThreadContextStack(key, this.registerNew); +#else + stack = new LogicalThreadContextStack(key, new TwoArgAction(registerNew)); +#endif + } + } + + return stack; + } } - private void registerNew(string stackName, LogicalThreadContextStack stack) - { - this.m_properties[stackName] = stack; + private void registerNew(string stackName, LogicalThreadContextStack stack) + { + this.m_properties[stackName] = stack; } - /// - /// The fully qualified type of the ThreadContextStacks class. - /// - /// - /// Used by the internal logger to record the Type of the - /// log message. - /// + /// + /// The fully qualified type of the ThreadContextStacks class. + /// + /// + /// Used by the internal logger to record the Type of the + /// log message. + /// private static readonly Type declaringType = typeof(LogicalThreadContextStacks); - } -} - -#endif + } +} + +#endif diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/NativeError.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/NativeError.cs index 2e4c6e1ae57..c7d752da735 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/NativeError.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/NativeError.cs @@ -1,269 +1,269 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -// MONO 1.0 has no support for Win32 Error APIs -#if !MONO -// SSCLI 1.0 has no support for Win32 Error APIs -#if !SSCLI -// We don't want framework or platform specific code in the CLI version of log4net -#if !CLI_1_0 - -using System; -using System.Globalization; -using System.Runtime.InteropServices; - -namespace log4net.Util -{ - /// - /// Represents a native error code and message. - /// - /// - /// - /// Represents a Win32 platform native error. - /// - /// - /// Nicko Cadell. - /// Gert Driesen. - public sealed class NativeError +// MONO 1.0 has no support for Win32 Error APIs +#if !MONO +// SSCLI 1.0 has no support for Win32 Error APIs +#if !SSCLI +// We don't want framework or platform specific code in the CLI version of log4net +#if !CLI_1_0 + +using System; +using System.Globalization; +using System.Runtime.InteropServices; + +namespace log4net.Util +{ + /// + /// Represents a native error code and message. + /// + /// + /// + /// Represents a Win32 platform native error. + /// + /// + /// Nicko Cadell + /// Gert Driesen + public sealed class NativeError { /// - /// Initializes a new instance of the class. - /// Create an instance of the class with the specified - /// error number and message. - /// - /// The number of the native error. - /// The message of the native error. - /// - /// - /// Create an instance of the class with the specified - /// error number and message. - /// - /// - private NativeError(int number, string message) - { - this.m_number = number; - this.m_message = message; + /// Create an instance of the class with the specified + /// error number and message. + /// + /// The number of the native error. + /// The message of the native error. + /// + /// + /// Create an instance of the class with the specified + /// error number and message. + /// + /// + private NativeError(int number, string message) + { + this.m_number = number; + this.m_message = message; + } + + /// + /// Gets the number of the native error. + /// + /// + /// The number of the native error. + /// + /// + /// + /// Gets the number of the native error. + /// + /// + public int Number + { + get { return this.m_number; } } - /// - /// Gets the number of the native error. - /// - /// - /// The number of the native error. - /// - /// - /// - /// Gets the number of the native error. - /// - /// - public int Number - { - get { return this.m_number; } - } - - /// - /// Gets the message of the native error. - /// - /// - /// The message of the native error. - /// - /// - /// - /// - /// Gets the message of the native error. - /// - public string Message - { - get { return this.m_message; } + /// + /// Gets the message of the native error. + /// + /// + /// The message of the native error. + /// + /// + /// + /// + /// Gets the message of the native error. + /// + public string Message + { + get { return this.m_message; } + } + + /// + /// Create a new instance of the class for the last Windows error. + /// + /// + /// An instance of the class for the last windows error. + /// + /// + /// + /// The message for the error number is lookup up using the + /// native Win32 FormatMessage function. + /// + /// +#if NET_4_0 || MONO_4_0 || NETSTANDARD + [System.Security.SecuritySafeCritical] +#endif +#if !NETCF && !NETSTANDARD1_3 + [System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Demand, UnmanagedCode = true)] +#endif + public static NativeError GetLastError() + { + int number = Marshal.GetLastWin32Error(); + return new NativeError(number, GetErrorMessage(number)); } - /// - /// Create a new instance of the class for the last Windows error. - /// - /// - /// An instance of the class for the last windows error. - /// - /// - /// - /// The message for the error number is lookup up using the - /// native Win32 FormatMessage function. - /// - /// -#if NET_4_0 || MONO_4_0 || NETSTANDARD1_3 - [System.Security.SecuritySafeCritical] -#elif !NETCF - [System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Demand, UnmanagedCode=true)] -#endif - public static NativeError GetLastError() - { - int number = Marshal.GetLastWin32Error(); - return new NativeError(number, NativeError.GetErrorMessage(number)); - } - - /// - /// Create a new instance of the class. - /// - /// the error number for the native error. - /// - /// An instance of the class for the specified - /// error number. - /// - /// - /// - /// The message for the specified error number is lookup up using the - /// native Win32 FormatMessage function. - /// - /// - public static NativeError GetError(int number) - { - return new NativeError(number, NativeError.GetErrorMessage(number)); + /// + /// Create a new instance of the class. + /// + /// the error number for the native error + /// + /// An instance of the class for the specified + /// error number. + /// + /// + /// + /// The message for the specified error number is lookup up using the + /// native Win32 FormatMessage function. + /// + /// + public static NativeError GetError(int number) + { + return new NativeError(number, GetErrorMessage(number)); } - /// - /// Retrieves the message corresponding with a Win32 message identifier. - /// - /// Message identifier for the requested message. - /// - /// The message corresponding with the specified message identifier. - /// - /// - /// - /// The message will be searched for in system message-table resource(s) - /// using the native FormatMessage function. - /// - /// -#if NET_4_0 || MONO_4_0 || NETSTANDARD1_3 - [System.Security.SecuritySafeCritical] -#elif !NETCF - [System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Demand, UnmanagedCode = true)] -#endif - public static string GetErrorMessage(int messageId) - { - // Win32 constants - int FORMAT_MESSAGE_ALLOCATE_BUFFER = 0x00000100; // The function should allocates a buffer large enough to hold the formatted message - int FORMAT_MESSAGE_IGNORE_INSERTS = 0x00000200; // Insert sequences in the message definition are to be ignored - int FORMAT_MESSAGE_FROM_SYSTEM = 0x00001000; // The function should search the system message-table resource(s) for the requested message - - string msgBuf = string.Empty; // buffer that will receive the message - IntPtr sourcePtr = IntPtr.Zero; // Location of the message definition, will be ignored - IntPtr argumentsPtr = IntPtr.Zero; // Pointer to array of values to insert, not supported as it requires unsafe code - - if (messageId != 0) - { - // If the function succeeds, the return value is the number of TCHARs stored in the output buffer, excluding the terminating null character - int messageSize = FormatMessage( - FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, - ref sourcePtr, - messageId, - 0, - ref msgBuf, - 255, - argumentsPtr); - - if (messageSize > 0) - { - // Remove trailing null-terminating characters (\r\n) from the message - msgBuf = msgBuf.TrimEnd(new char[] { '\r', '\n' }); - } - else - { - // A message could not be located. - msgBuf = null; - } - } - else - { - msgBuf = null; - } - - return msgBuf; + /// + /// Retrieves the message corresponding with a Win32 message identifier. + /// + /// Message identifier for the requested message. + /// + /// The message corresponding with the specified message identifier. + /// + /// + /// + /// The message will be searched for in system message-table resource(s) + /// using the native FormatMessage function. + /// + /// +#if NET_4_0 || MONO_4_0 || NETSTANDARD + [System.Security.SecuritySafeCritical] +#endif +#if !NETCF && !NETSTANDARD1_3 + [System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Demand, UnmanagedCode = true)] +#endif + public static string GetErrorMessage(int messageId) + { + // Win32 constants + int FORMAT_MESSAGE_ALLOCATE_BUFFER = 0x00000100; // The function should allocates a buffer large enough to hold the formatted message + int FORMAT_MESSAGE_IGNORE_INSERTS = 0x00000200; // Insert sequences in the message definition are to be ignored + int FORMAT_MESSAGE_FROM_SYSTEM = 0x00001000; // The function should search the system message-table resource(s) for the requested message + + string msgBuf = string.Empty; // buffer that will receive the message + IntPtr sourcePtr = IntPtr.Zero; // Location of the message definition, will be ignored + IntPtr argumentsPtr = IntPtr.Zero; // Pointer to array of values to insert, not supported as it requires unsafe code + + if (messageId != 0) + { + // If the function succeeds, the return value is the number of TCHARs stored in the output buffer, excluding the terminating null character + int messageSize = FormatMessage( + FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, + ref sourcePtr, + messageId, + 0, + ref msgBuf, + 255, + argumentsPtr); + + if (messageSize > 0) + { + // Remove trailing null-terminating characters (\r\n) from the message + msgBuf = msgBuf.TrimEnd(new char[] {'\r', '\n'}); + } + else + { + // A message could not be located. + msgBuf = null; + } + } + else + { + msgBuf = null; + } + + return msgBuf; } - /// - /// Return error information string. - /// - /// error information string. - /// - /// - /// Return error information string. - /// - /// - public override string ToString() - { - return string.Format(CultureInfo.InvariantCulture, "0x{0:x8}", this.Number) + (this.Message != null ? ": " + this.Message : string.Empty); + /// + /// Return error information string + /// + /// error information string + /// + /// + /// Return error information string + /// + /// + public override string ToString() + { + return string.Format(CultureInfo.InvariantCulture, "0x{0:x8}", this.Number) + (this.Message != null ? ": " + this.Message : string.Empty); } - /// - /// Formats a message string. - /// - /// Formatting options, and how to interpret the parameter. - /// Location of the message definition. - /// Message identifier for the requested message. - /// Language identifier for the requested message. - /// If includes FORMAT_MESSAGE_ALLOCATE_BUFFER, the function allocates a buffer using the LocalAlloc function, and places the pointer to the buffer at the address specified in . - /// If the FORMAT_MESSAGE_ALLOCATE_BUFFER flag is not set, this parameter specifies the maximum number of TCHARs that can be stored in the output buffer. If FORMAT_MESSAGE_ALLOCATE_BUFFER is set, this parameter specifies the minimum number of TCHARs to allocate for an output buffer. - /// Pointer to an array of values that are used as insert values in the formatted message. - /// - /// - /// The function requires a message definition as input. The message definition can come from a - /// buffer passed into the function. It can come from a message table resource in an - /// already-loaded module. Or the caller can ask the function to search the system's message - /// table resource(s) for the message definition. The function finds the message definition - /// in a message table resource based on a message identifier and a language identifier. - /// The function copies the formatted message text to an output buffer, processing any embedded - /// insert sequences if requested. - /// - /// - /// To prevent the usage of unsafe code, this stub does not support inserting values in the formatted message. - /// - /// - /// - /// - /// If the function succeeds, the return value is the number of TCHARs stored in the output - /// buffer, excluding the terminating null character. - /// - /// - /// If the function fails, the return value is zero. To get extended error information, - /// call . - /// - /// -#if NETCF - [DllImport("CoreDll.dll", SetLastError=true, CharSet=CharSet.Unicode)] -#else - [DllImport("Kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)] -#endif - private static extern int FormatMessage( - int dwFlags, - ref IntPtr lpSource, - int dwMessageId, - int dwLanguageId, - ref string lpBuffer, - int nSize, + /// + /// Formats a message string. + /// + /// Formatting options, and how to interpret the parameter. + /// Location of the message definition. + /// Message identifier for the requested message. + /// Language identifier for the requested message. + /// If includes FORMAT_MESSAGE_ALLOCATE_BUFFER, the function allocates a buffer using the LocalAlloc function, and places the pointer to the buffer at the address specified in . + /// If the FORMAT_MESSAGE_ALLOCATE_BUFFER flag is not set, this parameter specifies the maximum number of TCHARs that can be stored in the output buffer. If FORMAT_MESSAGE_ALLOCATE_BUFFER is set, this parameter specifies the minimum number of TCHARs to allocate for an output buffer. + /// Pointer to an array of values that are used as insert values in the formatted message. + /// + /// + /// The function requires a message definition as input. The message definition can come from a + /// buffer passed into the function. It can come from a message table resource in an + /// already-loaded module. Or the caller can ask the function to search the system's message + /// table resource(s) for the message definition. The function finds the message definition + /// in a message table resource based on a message identifier and a language identifier. + /// The function copies the formatted message text to an output buffer, processing any embedded + /// insert sequences if requested. + /// + /// + /// To prevent the usage of unsafe code, this stub does not support inserting values in the formatted message. + /// + /// + /// + /// + /// If the function succeeds, the return value is the number of TCHARs stored in the output + /// buffer, excluding the terminating null character. + /// + /// + /// If the function fails, the return value is zero. To get extended error information, + /// call . + /// + /// +#if NETCF || NETSTANDARD + [DllImport("CoreDll.dll", SetLastError=true, CharSet=CharSet.Unicode)] +#else + [DllImport("Kernel32.dll", SetLastError=true, CharSet=CharSet.Auto)] +#endif + private static extern int FormatMessage( + int dwFlags, + ref IntPtr lpSource, + int dwMessageId, + int dwLanguageId, + ref String lpBuffer, + int nSize, IntPtr Arguments); - private int m_number; + private int m_number; private string m_message; - } -} - -#endif // !CLI_1_0 -#endif // !SSCLI -#endif // !MONO + } +} + +#endif // !CLI_1_0 +#endif // !SSCLI +#endif // !MONO diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/NullDictionaryEnumerator.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/NullDictionaryEnumerator.cs index 3ba57dc03fe..d135d460c45 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/NullDictionaryEnumerator.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/NullDictionaryEnumerator.cs @@ -1,183 +1,183 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.Util -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; - using System.Collections; +using System; +using System.Collections; - /// - /// An always empty . - /// - /// - /// - /// A singleton implementation of the over a collection - /// that is empty and not modifiable. - /// - /// - /// Nicko Cadell. - /// Gert Driesen. - public sealed class NullDictionaryEnumerator : IDictionaryEnumerator +namespace log4net.Util +{ + /// + /// An always empty . + /// + /// + /// + /// A singleton implementation of the over a collection + /// that is empty and not modifiable. + /// + /// + /// Nicko Cadell + /// Gert Driesen + public sealed class NullDictionaryEnumerator : IDictionaryEnumerator { - /// - /// Initializes a new instance of the class. - /// - /// - /// - /// Uses a private access modifier to enforce the singleton pattern. - /// - /// - private NullDictionaryEnumerator() - { + /// + /// Initializes a new instance of the class. + /// + /// + /// + /// Uses a private access modifier to enforce the singleton pattern. + /// + /// + private NullDictionaryEnumerator() + { } - /// - /// Gets the singleton instance of the . - /// - /// The singleton instance of the . - /// - /// - /// Gets the singleton instance of the . - /// - /// - public static NullDictionaryEnumerator Instance - { - get { return s_instance; } + /// + /// Gets the singleton instance of the . + /// + /// The singleton instance of the . + /// + /// + /// Gets the singleton instance of the . + /// + /// + public static NullDictionaryEnumerator Instance + { + get { return s_instance; } } - /// - /// Gets the current object from the enumerator. - /// - /// - /// Throws an because the - /// never has a current value. - /// - /// - /// - /// As the enumerator is over an empty collection its - /// value cannot be moved over a valid position, therefore - /// will throw an . - /// - /// - /// The collection is empty and - /// cannot be positioned over a valid location. - public object Current - { - get { throw new InvalidOperationException(); } - } - - /// - /// Test if the enumerator can advance, if so advance. - /// - /// false as the cannot advance. - /// - /// - /// As the enumerator is over an empty collection its - /// value cannot be moved over a valid position, therefore - /// will always return false. - /// - /// - public bool MoveNext() - { - return false; - } - - /// - /// Resets the enumerator back to the start. - /// - /// - /// - /// As the enumerator is over an empty collection does nothing. - /// - /// - public void Reset() - { + /// + /// Gets the current object from the enumerator. + /// + /// + /// Throws an because the + /// never has a current value. + /// + /// + /// + /// As the enumerator is over an empty collection its + /// value cannot be moved over a valid position, therefore + /// will throw an . + /// + /// + /// The collection is empty and + /// cannot be positioned over a valid location. + public object Current + { + get { throw new InvalidOperationException(); } + } + + /// + /// Test if the enumerator can advance, if so advance. + /// + /// false as the cannot advance. + /// + /// + /// As the enumerator is over an empty collection its + /// value cannot be moved over a valid position, therefore + /// will always return false. + /// + /// + public bool MoveNext() + { + return false; + } + + /// + /// Resets the enumerator back to the start. + /// + /// + /// + /// As the enumerator is over an empty collection does nothing. + /// + /// + public void Reset() + { + } + + /// + /// Gets the current key from the enumerator. + /// + /// + /// Throws an exception because the + /// never has a current value. + /// + /// + /// + /// As the enumerator is over an empty collection its + /// value cannot be moved over a valid position, therefore + /// will throw an . + /// + /// + /// The collection is empty and + /// cannot be positioned over a valid location. + public object Key + { + get { throw new InvalidOperationException(); } + } + + /// + /// Gets the current value from the enumerator. + /// + /// The current value from the enumerator. + /// + /// Throws an because the + /// never has a current value. + /// + /// + /// + /// As the enumerator is over an empty collection its + /// value cannot be moved over a valid position, therefore + /// will throw an . + /// + /// + /// The collection is empty and + /// cannot be positioned over a valid location. + public object Value + { + get { throw new InvalidOperationException(); } } - /// - /// Gets the current key from the enumerator. - /// - /// - /// Throws an exception because the - /// never has a current value. - /// - /// - /// - /// As the enumerator is over an empty collection its - /// value cannot be moved over a valid position, therefore - /// will throw an . - /// - /// - /// The collection is empty and - /// cannot be positioned over a valid location. - public object Key - { - get { throw new InvalidOperationException(); } - } - - /// - /// Gets the current value from the enumerator. - /// - /// The current value from the enumerator. - /// - /// Throws an because the - /// never has a current value. - /// - /// - /// - /// As the enumerator is over an empty collection its - /// value cannot be moved over a valid position, therefore - /// will throw an . - /// - /// - /// The collection is empty and - /// cannot be positioned over a valid location. - public object Value - { - get { throw new InvalidOperationException(); } - } - - /// - /// Gets the current entry from the enumerator. - /// - /// - /// Throws an because the - /// never has a current entry. - /// - /// - /// - /// As the enumerator is over an empty collection its - /// value cannot be moved over a valid position, therefore - /// will throw an . - /// - /// - /// The collection is empty and - /// cannot be positioned over a valid location. - public DictionaryEntry Entry - { - get { throw new InvalidOperationException(); } + /// + /// Gets the current entry from the enumerator. + /// + /// + /// Throws an because the + /// never has a current entry. + /// + /// + /// + /// As the enumerator is over an empty collection its + /// value cannot be moved over a valid position, therefore + /// will throw an . + /// + /// + /// The collection is empty and + /// cannot be positioned over a valid location. + public DictionaryEntry Entry + { + get { throw new InvalidOperationException(); } } - /// - /// The singleton instance of the . - /// + /// + /// The singleton instance of the . + /// private static readonly NullDictionaryEnumerator s_instance = new NullDictionaryEnumerator(); - } -} + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/NullEnumerator.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/NullEnumerator.cs index 8689e7edaf6..7afb6ce7798 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/NullEnumerator.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/NullEnumerator.cs @@ -1,119 +1,119 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.Util -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; - using System.Collections; +using System; +using System.Collections; - /// - /// An always empty . - /// - /// - /// - /// A singleton implementation of the over a collection - /// that is empty and not modifiable. - /// - /// - /// Nicko Cadell. - /// Gert Driesen. - public sealed class NullEnumerator : IEnumerator +namespace log4net.Util +{ + /// + /// An always empty . + /// + /// + /// + /// A singleton implementation of the over a collection + /// that is empty and not modifiable. + /// + /// + /// Nicko Cadell + /// Gert Driesen + public sealed class NullEnumerator : IEnumerator { - /// - /// Initializes a new instance of the class. - /// - /// - /// - /// Uses a private access modifier to enforce the singleton pattern. - /// - /// - private NullEnumerator() - { + /// + /// Initializes a new instance of the class. + /// + /// + /// + /// Uses a private access modifier to enforce the singleton pattern. + /// + /// + private NullEnumerator() + { } - /// - /// Gets get the singleton instance of the . - /// - /// The singleton instance of the . - /// - /// - /// Gets the singleton instance of the . - /// - /// - public static NullEnumerator Instance - { - get { return s_instance; } + /// + /// Get the singleton instance of the . + /// + /// The singleton instance of the . + /// + /// + /// Gets the singleton instance of the . + /// + /// + public static NullEnumerator Instance + { + get { return s_instance; } } - /// - /// Gets the current object from the enumerator. - /// - /// - /// Throws an because the - /// never has a current value. - /// - /// - /// - /// As the enumerator is over an empty collection its - /// value cannot be moved over a valid position, therefore - /// will throw an . - /// - /// - /// The collection is empty and - /// cannot be positioned over a valid location. - public object Current - { - get { throw new InvalidOperationException(); } - } - - /// - /// Test if the enumerator can advance, if so advance. - /// - /// false as the cannot advance. - /// - /// - /// As the enumerator is over an empty collection its - /// value cannot be moved over a valid position, therefore - /// will always return false. - /// - /// - public bool MoveNext() - { - return false; - } - - /// - /// Resets the enumerator back to the start. - /// - /// - /// - /// As the enumerator is over an empty collection does nothing. - /// - /// - public void Reset() - { + /// + /// Gets the current object from the enumerator. + /// + /// + /// Throws an because the + /// never has a current value. + /// + /// + /// + /// As the enumerator is over an empty collection its + /// value cannot be moved over a valid position, therefore + /// will throw an . + /// + /// + /// The collection is empty and + /// cannot be positioned over a valid location. + public object Current + { + get { throw new InvalidOperationException(); } + } + + /// + /// Test if the enumerator can advance, if so advance + /// + /// false as the cannot advance. + /// + /// + /// As the enumerator is over an empty collection its + /// value cannot be moved over a valid position, therefore + /// will always return false. + /// + /// + public bool MoveNext() + { + return false; + } + + /// + /// Resets the enumerator back to the start. + /// + /// + /// + /// As the enumerator is over an empty collection does nothing. + /// + /// + public void Reset() + { } - /// - /// The singleton instance of the . - /// + /// + /// The singleton instance of the . + /// private static readonly NullEnumerator s_instance = new NullEnumerator(); - } -} + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/NullSecurityContext.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/NullSecurityContext.cs index 847df1c0b57..d6978ed75cd 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/NullSecurityContext.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/NullSecurityContext.cs @@ -1,78 +1,77 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.Util -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; +using System; - using log4net.Core; +using log4net.Core; - /// - /// A SecurityContext used when a SecurityContext is not required. - /// - /// - /// - /// The is a no-op implementation of the - /// base class. It is used where a - /// is required but one has not been provided. - /// - /// - /// Nicko Cadell. - public sealed class NullSecurityContext : SecurityContext - { - /// - /// Singleton instance of . - /// - /// - /// - /// Singleton instance of . - /// - /// +namespace log4net.Util +{ + /// + /// A SecurityContext used when a SecurityContext is not required + /// + /// + /// + /// The is a no-op implementation of the + /// base class. It is used where a + /// is required but one has not been provided. + /// + /// + /// Nicko Cadell + public sealed class NullSecurityContext : SecurityContext + { + /// + /// Singleton instance of + /// + /// + /// + /// Singleton instance of + /// + /// public static readonly NullSecurityContext Instance = new NullSecurityContext(); /// - /// Initializes a new instance of the class. - /// Private constructor. - /// - /// - /// - /// Private constructor for singleton pattern. - /// - /// - private NullSecurityContext() - { - } - - /// - /// Impersonate this SecurityContext. - /// - /// State supplied by the caller. - /// null. - /// - /// - /// No impersonation is done and null is always returned. - /// - /// - public override IDisposable Impersonate(object state) - { - return null; - } - } -} + /// Private constructor + /// + /// + /// + /// Private constructor for singleton pattern. + /// + /// + private NullSecurityContext() + { + } + + /// + /// Impersonate this SecurityContext + /// + /// State supplied by the caller + /// null + /// + /// + /// No impersonation is done and null is always returned. + /// + /// + public override IDisposable Impersonate(object state) + { + return null; + } + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/OnlyOnceErrorHandler.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/OnlyOnceErrorHandler.cs index 440f3dad646..70d15025999 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/OnlyOnceErrorHandler.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/OnlyOnceErrorHandler.cs @@ -1,268 +1,264 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.Util -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; +using System; - using log4net.Core; +using log4net.Core; - /// - /// Implements log4net's default error handling policy which consists - /// of emitting a message for the first error in an appender and - /// ignoring all subsequent errors. - /// - /// - /// - /// The error message is processed using the LogLog sub-system by default. - /// - /// - /// This policy aims at protecting an otherwise working application - /// from being flooded with error messages when logging fails. - /// - /// - /// Nicko Cadell. - /// Gert Driesen. - /// Ron Grabowski. - public class OnlyOnceErrorHandler : IErrorHandler +namespace log4net.Util +{ + /// + /// Implements log4net's default error handling policy which consists + /// of emitting a message for the first error in an appender and + /// ignoring all subsequent errors. + /// + /// + /// + /// The error message is processed using the LogLog sub-system by default. + /// + /// + /// This policy aims at protecting an otherwise working application + /// from being flooded with error messages when logging fails. + /// + /// + /// Nicko Cadell + /// Gert Driesen + /// Ron Grabowski + public class OnlyOnceErrorHandler : IErrorHandler { /// - /// Initializes a new instance of the class. - /// Default Constructor. - /// - /// - /// - /// Initializes a new instance of the class. - /// - /// - public OnlyOnceErrorHandler() - { - this.m_prefix = string.Empty; + /// Default Constructor + /// + /// + /// + /// Initializes a new instance of the class. + /// + /// + public OnlyOnceErrorHandler() + { + this.m_prefix = string.Empty; } /// - /// Initializes a new instance of the class. - /// Constructor. - /// - /// The prefix to use for each message. - /// - /// - /// Initializes a new instance of the class - /// with the specified prefix. - /// - /// - public OnlyOnceErrorHandler(string prefix) - { - this.m_prefix = prefix; + /// Constructor + /// + /// The prefix to use for each message. + /// + /// + /// Initializes a new instance of the class + /// with the specified prefix. + /// + /// + public OnlyOnceErrorHandler(string prefix) + { + this.m_prefix = prefix; } - /// - /// Reset the error handler back to its initial disabled state. - /// - public void Reset() - { - this.m_enabledDateUtc = DateTime.MinValue; - this.m_errorCode = ErrorCode.GenericFailure; - this.m_exception = null; - this.m_message = null; - this.m_firstTime = true; + /// + /// Reset the error handler back to its initial disabled state. + /// + public void Reset() + { + this.m_enabledDateUtc = DateTime.MinValue; + this.m_errorCode = ErrorCode.GenericFailure; + this.m_exception = null; + this.m_message = null; + this.m_firstTime = true; + } + + /// + /// Log an Error + /// + /// The error message. + /// The exception. + /// The internal error code. + /// + /// + /// Invokes if and only if this is the first error or the first error after has been called. + /// + /// + public void Error(string message, Exception e, ErrorCode errorCode) + { + if (this.m_firstTime) + { + this.FirstError(message, e, errorCode); + } + } + + /// + /// Log the very first error + /// + /// The error message. + /// The exception. + /// The internal error code. + /// + /// + /// Sends the error information to 's Error method. + /// + /// + public virtual void FirstError(string message, Exception e, ErrorCode errorCode) { + this.m_enabledDateUtc = DateTime.UtcNow; + this.m_errorCode = errorCode; + this.m_exception = e; + this.m_message = message; + this.m_firstTime = false; + + if (LogLog.InternalDebugging && !LogLog.QuietMode) { + LogLog.Error(declaringType, "[" + this.m_prefix + "] ErrorCode: " + errorCode.ToString() + ". " + message, e); + } + } + + /// + /// Log an Error + /// + /// The error message. + /// The exception. + /// + /// + /// Invokes if and only if this is the first error or the first error after has been called. + /// + /// + public void Error(string message, Exception e) + { + this.Error(message, e, ErrorCode.GenericFailure); } - /// - /// Log an Error. - /// - /// The error message. - /// The exception. - /// The internal error code. - /// - /// - /// Invokes if and only if this is the first error or the first error after has been called. - /// - /// - public void Error(string message, Exception e, ErrorCode errorCode) - { - if (this.m_firstTime) - { - this.FirstError(message, e, errorCode); - } - } - - /// - /// Log the very first error. - /// - /// The error message. - /// The exception. - /// The internal error code. - /// - /// - /// Sends the error information to 's Error method. - /// - /// - public virtual void FirstError(string message, Exception e, ErrorCode errorCode) - { - this.m_enabledDateUtc = DateTime.UtcNow; - this.m_errorCode = errorCode; - this.m_exception = e; - this.m_message = message; - this.m_firstTime = false; - - if (LogLog.InternalDebugging && !LogLog.QuietMode) - { - LogLog.Error(declaringType, "[" + this.m_prefix + "] ErrorCode: " + errorCode.ToString() + ". " + message, e); - } - } - - /// - /// Log an Error. - /// - /// The error message. - /// The exception. - /// - /// - /// Invokes if and only if this is the first error or the first error after has been called. - /// - /// - public void Error(string message, Exception e) - { - this.Error(message, e, ErrorCode.GenericFailure); - } - - /// - /// Log an error. - /// - /// The error message. - /// - /// - /// Invokes if and only if this is the first error or the first error after has been called. - /// - /// - public void Error(string message) - { - this.Error(message, null, ErrorCode.GenericFailure); + /// + /// Log an error + /// + /// The error message. + /// + /// + /// Invokes if and only if this is the first error or the first error after has been called. + /// + /// + public void Error(string message) + { + this.Error(message, null, ErrorCode.GenericFailure); + } + + /// + /// Is error logging enabled + /// + /// + /// + /// Is error logging enabled. Logging is only enabled for the + /// first error delivered to the . + /// + /// + public bool IsEnabled + { + get { return this.m_firstTime; } } - /// - /// Gets a value indicating whether is error logging enabled. - /// - /// - /// - /// Is error logging enabled. Logging is only enabled for the - /// first error delivered to the . - /// - /// - public bool IsEnabled - { - get { return this.m_firstTime; } - } - - /// - /// Gets the date the first error that trigged this error handler occurred, or if it has not been triggered. - /// - public DateTime EnabledDate - { - get - { + /// + /// The date the first error that trigged this error handler occurred, or if it has not been triggered. + /// + public DateTime EnabledDate + { + get + { if (this.m_enabledDateUtc == DateTime.MinValue) { return DateTime.MinValue; } - return this.m_enabledDateUtc.ToLocalTime(); - } - } - - /// - /// Gets the UTC date the first error that trigged this error handler occured, or if it has not been triggered. - /// - public DateTime EnabledDateUtc - { - get { return this.m_enabledDateUtc; } - } - - /// - /// Gets the message from the first error that trigged this error handler. - /// - public string ErrorMessage - { - get { return this.m_message; } - } - - /// - /// Gets the exception from the first error that trigged this error handler. - /// - /// - /// May be . - /// - public Exception Exception - { - get { return this.m_exception; } - } - - /// - /// Gets the error code from the first error that trigged this error handler. - /// - /// - /// Defaults to . - /// - public ErrorCode ErrorCode - { - get { return this.m_errorCode; } + return this.m_enabledDateUtc.ToLocalTime(); + } + } + + /// + /// The UTC date the first error that trigged this error handler occured, or if it has not been triggered. + /// + public DateTime EnabledDateUtc + { + get { return this.m_enabledDateUtc; } + } + + /// + /// The message from the first error that trigged this error handler. + /// + public string ErrorMessage + { + get { return this.m_message; } + } + + /// + /// The exception from the first error that trigged this error handler. + /// + /// + /// May be . + /// + public Exception Exception + { + get { return this.m_exception; } + } + + /// + /// The error code from the first error that trigged this error handler. + /// + /// + /// Defaults to + /// + public ErrorCode ErrorCode + { + get { return this.m_errorCode; } } - /// - /// The UTC date the error was recorded. - /// - private DateTime m_enabledDateUtc; - - /// - /// Flag to indicate if it is the first error. - /// - private bool m_firstTime = true; - - /// - /// The message recorded during the first error. - /// - private string m_message = null; - - /// - /// The exception recorded during the first error. - /// - private Exception m_exception = null; - - /// - /// The error code recorded during the first error. - /// - private ErrorCode m_errorCode = ErrorCode.GenericFailure; - - /// - /// String to prefix each message with. - /// + /// + /// The UTC date the error was recorded. + /// + private DateTime m_enabledDateUtc; + + /// + /// Flag to indicate if it is the first error + /// + private bool m_firstTime = true; + + /// + /// The message recorded during the first error. + /// + private string m_message = null; + + /// + /// The exception recorded during the first error. + /// + private Exception m_exception = null; + + /// + /// The error code recorded during the first error. + /// + private ErrorCode m_errorCode = ErrorCode.GenericFailure; + + /// + /// String to prefix each message with + /// private readonly string m_prefix; - /// - /// The fully qualified type of the OnlyOnceErrorHandler class. - /// - /// - /// Used by the internal logger to record the Type of the - /// log message. - /// + /// + /// The fully qualified type of the OnlyOnceErrorHandler class. + /// + /// + /// Used by the internal logger to record the Type of the + /// log message. + /// private static readonly Type declaringType = typeof(OnlyOnceErrorHandler); - } -} + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/OptionConverter.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/OptionConverter.cs index f3af76ea8d2..9fd1b98daf9 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/OptionConverter.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/OptionConverter.cs @@ -1,663 +1,656 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.Util -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; - using System.Collections; - using System.Globalization; - using System.Reflection; - using System.Text; - - using log4net.Core; - using log4net.Util.TypeConverters; - - /// - /// A convenience class to convert property values to specific types. - /// - /// - /// - /// Utility functions for converting types and parsing values. - /// - /// - /// Nicko Cadell. - /// Gert Driesen. - public sealed class OptionConverter +using System; +using System.Collections; +using System.Globalization; +using System.Reflection; +using System.Text; + +using log4net.Core; +using log4net.Util.TypeConverters; + +namespace log4net.Util +{ + /// + /// A convenience class to convert property values to specific types. + /// + /// + /// + /// Utility functions for converting types and parsing values. + /// + /// + /// Nicko Cadell + /// Gert Driesen + public sealed class OptionConverter { - /// - /// Initializes a new instance of the class. - /// - /// - /// - /// Uses a private access modifier to prevent instantiation of this class. - /// - /// - private OptionConverter() - { + /// + /// Initializes a new instance of the class. + /// + /// + /// + /// Uses a private access modifier to prevent instantiation of this class. + /// + /// + private OptionConverter() + { + } + + // /// +// /// Concatenates two string arrays. +// /// +// /// Left array. +// /// Right array. +// /// Array containing both left and right arrays. +// public static string[] ConcatenateArrays(string[] l, string[] r) +// { +// return (string[])ConcatenateArrays(l, r); +// } + +// /// +// /// Concatenates two arrays. +// /// +// /// Left array +// /// Right array +// /// Array containing both left and right arrays. +// public static Array ConcatenateArrays(Array l, Array r) +// { +// if (l == null) +// { +// throw new ArgumentNullException("l"); +// } +// if (r == null) +// { +// throw new ArgumentNullException("r"); +// } +// +// int len = l.Length + r.Length; +// Array a = Array.CreateInstance(l.GetType(), len); +// +// Array.Copy(l, 0, a, 0, l.Length); +// Array.Copy(r, 0, a, l.Length, r.Length); +// +// return a; +// } + +// /// +// /// Converts string escape characters back to their correct values. +// /// +// /// String to convert. +// /// Converted result. +// public static string ConvertSpecialChars(string s) +// { +// if (s == null) +// { +// throw new ArgumentNullException("s"); +// } +// char c; +// int len = s.Length; +// StringBuilder buf = new StringBuilder(len); +// +// int i = 0; +// while(i < len) +// { +// c = s[i++]; +// if (c == '\\') +// { +// c = s[i++]; +// if (c == 'n') c = '\n'; +// else if (c == 'r') c = '\r'; +// else if (c == 't') c = '\t'; +// else if (c == 'f') c = '\f'; +// else if (c == '\b') c = '\b'; +// else if (c == '\"') c = '\"'; +// else if (c == '\'') c = '\''; +// else if (c == '\\') c = '\\'; +// } +// buf.Append(c); +// } +// return buf.ToString(); +// } + + /// + /// Converts a string to a value. + /// + /// String to convert. + /// The default value. + /// The value of . + /// + /// + /// If is "true", then true is returned. + /// If is "false", then false is returned. + /// Otherwise, is returned. + /// + /// + public static bool ToBoolean(string argValue, bool defaultValue) + { + if (argValue != null && argValue.Length > 0) + { + try + { + return bool.Parse(argValue); + } + catch(Exception e) + { + LogLog.Error(declaringType, "[" + argValue + "] is not in proper bool form.", e); + } + } + return defaultValue; + } + +// /// +// /// Converts a string to an integer. +// /// +// /// String to convert. +// /// The default value. +// /// The value of . +// /// +// /// +// /// is returned when +// /// cannot be converted to a value. +// /// +// /// +// public static int ToInt(string argValue, int defaultValue) +// { +// if (argValue != null) +// { +// string s = argValue.Trim(); +// try +// { +// return int.Parse(s, NumberFormatInfo.InvariantInfo); +// } +// catch (Exception e) +// { +// LogLog.Error(declaringType, "OptionConverter: [" + s + "] is not in proper int form.", e); +// } +// } +// return defaultValue; +// } + + /// + /// Parses a file size into a number. + /// + /// String to parse. + /// The default value. + /// The value of . + /// + /// + /// Parses a file size of the form: number[KB|MB|GB] into a + /// long value. It is scaled with the appropriate multiplier. + /// + /// + /// is returned when + /// cannot be converted to a value. + /// + /// + public static long ToFileSize(string argValue, long defaultValue) + { + if (argValue == null) + { + return defaultValue; + } + + string s = argValue.Trim().ToUpperInvariant(); + long multiplier = 1; + int index; + + if ((index = s.IndexOf("KB")) != -1) + { + multiplier = 1024; + s = s.Substring(0, index); + } + else if ((index = s.IndexOf("MB")) != -1) + { + multiplier = 1024 * 1024; + s = s.Substring(0, index); + } + else if ((index = s.IndexOf("GB")) != -1) + { + multiplier = 1024 * 1024 * 1024; + s = s.Substring(0, index); + } + if (s != null) + { + // Try again to remove whitespace between the number and the size specifier + s = s.Trim(); + + long longVal; + if (SystemInfo.TryParse(s, out longVal)) + { + return longVal * multiplier; + } + else + { + LogLog.Error(declaringType, "OptionConverter: [" + s + "] is not in the correct file size syntax."); + } + } + return defaultValue; + } + + /// + /// Converts a string to an object. + /// + /// The target type to convert to. + /// The string to convert to an object. + /// + /// The object converted from a string or null when the + /// conversion failed. + /// + /// + /// + /// Converts a string to an object. Uses the converter registry to try + /// to convert the string value into the specified target type. + /// + /// + public static object ConvertStringTo(Type target, string txt) + { + if (target == null) + { + throw new ArgumentNullException("target"); + } + + // If we want a string we already have the correct type + if (typeof(string) == target || typeof(object) == target) + { + return txt; + } + + // First lets try to find a type converter + IConvertFrom typeConverter = ConverterRegistry.GetConvertFrom(target); + if (typeConverter != null && typeConverter.CanConvertFrom(typeof(string))) + { + // Found appropriate converter + return typeConverter.ConvertFrom(txt); + } + else + { +#if NETSTANDARD1_3 + if (target.GetTypeInfo().IsEnum) +#else + if (target.IsEnum) +#endif + { + // Target type is an enum. + + // Use the Enum.Parse(EnumType, string) method to get the enum value + return ParseEnum(target, txt, true); + } + else + { + // We essentially make a guess that to convert from a string + // to an arbitrary type T there will be a static method defined on type T called Parse + // that will take an argument of type string. i.e. T.Parse(string)->T we call this + // method to convert the string to the type required by the property. + MethodInfo meth = target.GetMethod("Parse", new Type[] {typeof(string)}); + if (meth != null) + { + // Call the Parse method +#if NETSTANDARD1_3 + return meth.Invoke(target, new[] { txt }); +#else + return meth.Invoke(null, BindingFlags.InvokeMethod, null, new object[] {txt}, CultureInfo.InvariantCulture); +#endif + } + else + { + // No Parse() method found. + } + } + } + return null; } - // /// - // /// Concatenates two string arrays. - // /// - // /// Left array. - // /// Right array. - // /// Array containing both left and right arrays. - // public static string[] ConcatenateArrays(string[] l, string[] r) - // { - // return (string[])ConcatenateArrays(l, r); - // } - - // /// - // /// Concatenates two arrays. - // /// - // /// Left array - // /// Right array - // /// Array containing both left and right arrays. - // public static Array ConcatenateArrays(Array l, Array r) - // { - // if (l == null) - // { - // throw new ArgumentNullException("l"); - // } - // if (r == null) - // { - // throw new ArgumentNullException("r"); - // } - // - // int len = l.Length + r.Length; - // Array a = Array.CreateInstance(l.GetType(), len); - // - // Array.Copy(l, 0, a, 0, l.Length); - // Array.Copy(r, 0, a, l.Length, r.Length); - // - // return a; - // } - - // /// - // /// Converts string escape characters back to their correct values. - // /// - // /// String to convert. - // /// Converted result. - // public static string ConvertSpecialChars(string s) - // { - // if (s == null) - // { - // throw new ArgumentNullException("s"); - // } - // char c; - // int len = s.Length; - // StringBuilder buf = new StringBuilder(len); - // - // int i = 0; - // while(i < len) - // { - // c = s[i++]; - // if (c == '\\') - // { - // c = s[i++]; - // if (c == 'n') c = '\n'; - // else if (c == 'r') c = '\r'; - // else if (c == 't') c = '\t'; - // else if (c == 'f') c = '\f'; - // else if (c == '\b') c = '\b'; - // else if (c == '\"') c = '\"'; - // else if (c == '\'') c = '\''; - // else if (c == '\\') c = '\\'; - // } - // buf.Append(c); - // } - // return buf.ToString(); - // } - - /// - /// Converts a string to a value. - /// - /// String to convert. - /// The default value. - /// The value of . - /// - /// - /// If is "true", then true is returned. - /// If is "false", then false is returned. - /// Otherwise, is returned. - /// - /// - public static bool ToBoolean(string argValue, bool defaultValue) - { - if (argValue != null && argValue.Length > 0) - { - try - { - return bool.Parse(argValue); - } - catch (Exception e) - { - LogLog.Error(declaringType, "[" + argValue + "] is not in proper bool form.", e); - } - } - - return defaultValue; +// /// +// /// Looks up the for the target type. +// /// +// /// The type to lookup the converter for. +// /// The converter for the specified type. +// public static IConvertFrom GetTypeConverter(Type target) +// { +// IConvertFrom converter = ConverterRegistry.GetConverter(target); +// if (converter == null) +// { +// throw new InvalidOperationException("No type converter defined for [" + target + "]"); +// } +// return converter; +// } + + /// + /// Checks if there is an appropriate type conversion from the source type to the target type. + /// + /// The type to convert from. + /// The type to convert to. + /// true if there is a conversion from the source type to the target type. + /// + /// Checks if there is an appropriate type conversion from the source type to the target type. + /// + /// + /// + public static bool CanConvertTypeTo(Type sourceType, Type targetType) + { + if (sourceType == null || targetType == null) + { + return false; + } + + // Check if we can assign directly from the source type to the target type + if (targetType.IsAssignableFrom(sourceType)) + { + return true; + } + + // Look for a To converter + IConvertTo tcSource = ConverterRegistry.GetConvertTo(sourceType, targetType); + if (tcSource != null) + { + if (tcSource.CanConvertTo(targetType)) + { + return true; + } + } + + // Look for a From converter + IConvertFrom tcTarget = ConverterRegistry.GetConvertFrom(targetType); + if (tcTarget != null) + { + if (tcTarget.CanConvertFrom(sourceType)) + { + return true; + } + } + + return false; } - // /// - // /// Converts a string to an integer. - // /// - // /// String to convert. - // /// The default value. - // /// The value of . - // /// - // /// - // /// is returned when - // /// cannot be converted to a value. - // /// - // /// - // public static int ToInt(string argValue, int defaultValue) - // { - // if (argValue != null) - // { - // string s = argValue.Trim(); - // try - // { - // return int.Parse(s, NumberFormatInfo.InvariantInfo); - // } - // catch (Exception e) - // { - // LogLog.Error(declaringType, "OptionConverter: [" + s + "] is not in proper int form.", e); - // } - // } - // return defaultValue; - // } - - /// - /// Parses a file size into a number. - /// - /// String to parse. - /// The default value. - /// The value of . - /// - /// - /// Parses a file size of the form: number[KB|MB|GB] into a - /// long value. It is scaled with the appropriate multiplier. - /// - /// - /// is returned when - /// cannot be converted to a value. - /// - /// - public static long ToFileSize(string argValue, long defaultValue) - { - if (argValue == null) - { - return defaultValue; - } - - string s = argValue.Trim().ToUpper(CultureInfo.InvariantCulture); - long multiplier = 1; - int index; - - if ((index = s.IndexOf("KB")) != -1) - { - multiplier = 1024; - s = s.Substring(0, index); - } - else if ((index = s.IndexOf("MB")) != -1) - { - multiplier = 1024 * 1024; - s = s.Substring(0, index); - } - else if ((index = s.IndexOf("GB")) != -1) - { - multiplier = 1024 * 1024 * 1024; - s = s.Substring(0, index); - } - - if (s != null) - { - // Try again to remove whitespace between the number and the size specifier - s = s.Trim(); - - long longVal; - if (SystemInfo.TryParse(s, out longVal)) - { - return longVal * multiplier; - } - else - { - LogLog.Error(declaringType, "OptionConverter: [" + s + "] is not in the correct file size syntax."); - } - } - - return defaultValue; - } - - /// - /// Converts a string to an object. - /// - /// The target type to convert to. - /// The string to convert to an object. - /// - /// The object converted from a string or null when the - /// conversion failed. - /// - /// - /// - /// Converts a string to an object. Uses the converter registry to try - /// to convert the string value into the specified target type. - /// - /// - public static object ConvertStringTo(Type target, string txt) - { - if (target == null) - { - throw new ArgumentNullException("target"); - } - - // If we want a string we already have the correct type - if (typeof(string) == target || typeof(object) == target) - { - return txt; - } - - // First lets try to find a type converter - IConvertFrom typeConverter = ConverterRegistry.GetConvertFrom(target); - if (typeConverter != null && typeConverter.CanConvertFrom(typeof(string))) - { - // Found appropriate converter - return typeConverter.ConvertFrom(txt); - } - else - { -#if NETSTANDARD1_3 - if (target.GetTypeInfo().IsEnum) -#else - if (target.IsEnum) -#endif - { - // Target type is an enum. - - // Use the Enum.Parse(EnumType, string) method to get the enum value - return ParseEnum(target, txt, true); - } - else - { - // We essentially make a guess that to convert from a string - // to an arbitrary type T there will be a static method defined on type T called Parse - // that will take an argument of type string. i.e. T.Parse(string)->T we call this - // method to convert the string to the type required by the property. - System.Reflection.MethodInfo meth = target.GetMethod("Parse", new Type[] { typeof(string) }); - if (meth != null) - { - // Call the Parse method -#if NETSTANDARD1_3 - return meth.Invoke(target, new[] { txt }); -#else - return meth.Invoke(null, BindingFlags.InvokeMethod, null, new object[] { txt }, CultureInfo.InvariantCulture); -#endif - } - else - { - // No Parse() method found. - } - } - } - - return null; + /// + /// Converts an object to the target type. + /// + /// The object to convert to the target type. + /// The type to convert to. + /// The converted object. + /// + /// + /// Converts an object to the target type. + /// + /// + public static object ConvertTypeTo(object sourceInstance, Type targetType) + { + Type sourceType = sourceInstance.GetType(); + + // Check if we can assign directly from the source type to the target type + if (targetType.IsAssignableFrom(sourceType)) + { + return sourceInstance; + } + + // Look for a TO converter + IConvertTo tcSource = ConverterRegistry.GetConvertTo(sourceType, targetType); + if (tcSource != null) + { + if (tcSource.CanConvertTo(targetType)) + { + return tcSource.ConvertTo(sourceInstance, targetType); + } + } + + // Look for a FROM converter + IConvertFrom tcTarget = ConverterRegistry.GetConvertFrom(targetType); + if (tcTarget != null) + { + if (tcTarget.CanConvertFrom(sourceType)) + { + return tcTarget.ConvertFrom(sourceInstance); + } + } + + throw new ArgumentException("Cannot convert source object [" + sourceInstance.ToString() + "] to target type [" + targetType.Name + "]", "sourceInstance"); } - // /// - // /// Looks up the for the target type. - // /// - // /// The type to lookup the converter for. - // /// The converter for the specified type. - // public static IConvertFrom GetTypeConverter(Type target) - // { - // IConvertFrom converter = ConverterRegistry.GetConverter(target); - // if (converter == null) - // { - // throw new InvalidOperationException("No type converter defined for [" + target + "]"); - // } - // return converter; - // } - - /// - /// Checks if there is an appropriate type conversion from the source type to the target type. - /// - /// The type to convert from. - /// The type to convert to. - /// true if there is a conversion from the source type to the target type. - /// - /// Checks if there is an appropriate type conversion from the source type to the target type. - /// - /// - /// - public static bool CanConvertTypeTo(Type sourceType, Type targetType) - { - if (sourceType == null || targetType == null) - { - return false; - } - - // Check if we can assign directly from the source type to the target type - if (targetType.IsAssignableFrom(sourceType)) - { - return true; - } - - // Look for a To converter - IConvertTo tcSource = ConverterRegistry.GetConvertTo(sourceType, targetType); - if (tcSource != null) - { - if (tcSource.CanConvertTo(targetType)) - { - return true; - } - } - - // Look for a From converter - IConvertFrom tcTarget = ConverterRegistry.GetConvertFrom(targetType); - if (tcTarget != null) - { - if (tcTarget.CanConvertFrom(sourceType)) - { - return true; - } - } - - return false; - } - - /// - /// Converts an object to the target type. - /// - /// The object to convert to the target type. - /// The type to convert to. - /// The converted object. - /// - /// - /// Converts an object to the target type. - /// - /// - public static object ConvertTypeTo(object sourceInstance, Type targetType) - { - Type sourceType = sourceInstance.GetType(); - - // Check if we can assign directly from the source type to the target type - if (targetType.IsAssignableFrom(sourceType)) - { - return sourceInstance; - } - - // Look for a TO converter - IConvertTo tcSource = ConverterRegistry.GetConvertTo(sourceType, targetType); - if (tcSource != null) - { - if (tcSource.CanConvertTo(targetType)) - { - return tcSource.ConvertTo(sourceInstance, targetType); - } - } - - // Look for a FROM converter - IConvertFrom tcTarget = ConverterRegistry.GetConvertFrom(targetType); - if (tcTarget != null) - { - if (tcTarget.CanConvertFrom(sourceType)) - { - return tcTarget.ConvertFrom(sourceInstance); - } - } - - throw new ArgumentException("Cannot convert source object [" + sourceInstance.ToString() + "] to target type [" + targetType.Name + "]", "sourceInstance"); +// /// +// /// Finds the value corresponding to in +// /// and then perform variable substitution +// /// on the found value. +// /// +// /// The key to lookup. +// /// The association to use for lookups. +// /// The substituted result. +// public static string FindAndSubst(string key, System.Collections.IDictionary props) +// { +// if (props == null) +// { +// throw new ArgumentNullException("props"); +// } +// +// string v = props[key] as string; +// if (v == null) +// { +// return null; +// } +// +// try +// { +// return SubstituteVariables(v, props); +// } +// catch(Exception e) +// { +// LogLog.Error(declaringType, "OptionConverter: Bad option value [" + v + "].", e); +// return v; +// } +// } + + /// + /// Instantiates an object given a class name. + /// + /// The fully qualified class name of the object to instantiate. + /// The class to which the new object should belong. + /// The object to return in case of non-fulfillment. + /// + /// An instance of the or + /// if the object could not be instantiated. + /// + /// + /// + /// Checks that the is a subclass of + /// . If that test fails or the object could + /// not be instantiated, then is returned. + /// + /// + public static object InstantiateByClassName(string className, Type superClass, object defaultValue) + { + if (className != null) + { + try + { +#if NETSTANDARD1_3 + Type classObj = SystemInfo.GetTypeFromString(superClass.GetTypeInfo().Assembly, className, true, true); +#else + Type classObj = SystemInfo.GetTypeFromString(className, true, true); +#endif + if (!superClass.IsAssignableFrom(classObj)) + { + LogLog.Error(declaringType, "OptionConverter: A [" + className + "] object is not assignable to a [" + superClass.FullName + "] variable."); + return defaultValue; + } + return Activator.CreateInstance(classObj); + } + catch (Exception e) + { + LogLog.Error(declaringType, "Could not instantiate class [" + className + "].", e); + } + } + return defaultValue; } - // /// - // /// Finds the value corresponding to in - // /// and then perform variable substitution - // /// on the found value. - // /// - // /// The key to lookup. - // /// The association to use for lookups. - // /// The substituted result. - // public static string FindAndSubst(string key, System.Collections.IDictionary props) - // { - // if (props == null) - // { - // throw new ArgumentNullException("props"); - // } - // - // string v = props[key] as string; - // if (v == null) - // { - // return null; - // } - // - // try - // { - // return SubstituteVariables(v, props); - // } - // catch(Exception e) - // { - // LogLog.Error(declaringType, "OptionConverter: Bad option value [" + v + "].", e); - // return v; - // } - // } - - /// - /// Instantiates an object given a class name. - /// - /// The fully qualified class name of the object to instantiate. - /// The class to which the new object should belong. - /// The object to return in case of non-fulfillment. - /// - /// An instance of the or - /// if the object could not be instantiated. - /// - /// - /// - /// Checks that the is a subclass of - /// . If that test fails or the object could - /// not be instantiated, then is returned. - /// - /// - public static object InstantiateByClassName(string className, Type superClass, object defaultValue) - { - if (className != null) - { - try - { -#if NETSTANDARD1_3 - Type classObj = SystemInfo.GetTypeFromString(superClass.GetTypeInfo().Assembly, className, true, true); -#else - Type classObj = SystemInfo.GetTypeFromString(className, true, true); -#endif - if (!superClass.IsAssignableFrom(classObj)) - { - LogLog.Error(declaringType, "OptionConverter: A [" + className + "] object is not assignable to a [" + superClass.FullName + "] variable."); - return defaultValue; - } - - return Activator.CreateInstance(classObj); - } - catch (Exception e) - { - LogLog.Error(declaringType, "Could not instantiate class [" + className + "].", e); - } - } - - return defaultValue; - } - - /// - /// Performs variable substitution in string from the - /// values of keys found in . - /// - /// The string on which variable substitution is performed. - /// The dictionary to use to lookup variables. - /// The result of the substitutions. - /// - /// - /// The variable substitution delimiters are ${ and }. - /// - /// - /// For example, if props contains key=value, then the call. - /// - /// - /// - /// string s = OptionConverter.SubstituteVariables("Value of key is ${key}."); - /// - /// - /// - /// will set the variable s to "Value of key is value.". - /// - /// - /// If no value could be found for the specified key, then substitution - /// defaults to an empty string. - /// - /// - /// For example, if system properties contains no value for the key - /// "nonExistentKey", then the call. - /// - /// - /// - /// string s = OptionConverter.SubstituteVariables("Value of nonExistentKey is [${nonExistentKey}]"); - /// - /// - /// - /// will set s to "Value of nonExistentKey is []". - /// - /// - /// An Exception is thrown if contains a start - /// delimiter "${" which is not balanced by a stop delimiter "}". - /// - /// - public static string SubstituteVariables(string value, System.Collections.IDictionary props) - { - StringBuilder buf = new StringBuilder(); - - int i = 0; - int j, k; - - while (true) - { - j = value.IndexOf(DELIM_START, i); - if (j == -1) - { - if (i == 0) - { - return value; - } - else - { - buf.Append(value.Substring(i, value.Length - i)); - return buf.ToString(); - } - } - else - { - buf.Append(value.Substring(i, j - i)); - k = value.IndexOf(DELIM_STOP, j); - if (k == -1) - { - throw new LogException("[" + value + "] has no closing brace. Opening brace at position [" + j + "]"); - } - else - { - j += DELIM_START_LEN; - string key = value.Substring(j, k - j); - - string replacement = props[key] as string; - - if (replacement != null) - { - buf.Append(replacement); - } - - i = k + DELIM_STOP_LEN; - } - } - } + /// + /// Performs variable substitution in string from the + /// values of keys found in . + /// + /// The string on which variable substitution is performed. + /// The dictionary to use to lookup variables. + /// The result of the substitutions. + /// + /// + /// The variable substitution delimiters are ${ and }. + /// + /// + /// For example, if props contains key=value, then the call + /// + /// + /// + /// string s = OptionConverter.SubstituteVariables("Value of key is ${key}."); + /// + /// + /// + /// will set the variable s to "Value of key is value.". + /// + /// + /// If no value could be found for the specified key, then substitution + /// defaults to an empty string. + /// + /// + /// For example, if system properties contains no value for the key + /// "nonExistentKey", then the call + /// + /// + /// + /// string s = OptionConverter.SubstituteVariables("Value of nonExistentKey is [${nonExistentKey}]"); + /// + /// + /// + /// will set s to "Value of nonExistentKey is []". + /// + /// + /// An Exception is thrown if contains a start + /// delimiter "${" which is not balanced by a stop delimiter "}". + /// + /// + public static string SubstituteVariables(string value, IDictionary props) + { + StringBuilder buf = new StringBuilder(); + + int i = 0; + int j, k; + + while(true) + { + j = value.IndexOf(DELIM_START, i); + if (j == -1) + { + if (i == 0) + { + return value; + } + else + { + buf.Append(value.Substring(i, value.Length - i)); + return buf.ToString(); + } + } + else + { + buf.Append(value.Substring(i, j - i)); + k = value.IndexOf(DELIM_STOP, j); + if (k == -1) + { + throw new LogException("[" + value + "] has no closing brace. Opening brace at position [" + j + "]"); + } + else + { + j += DELIM_START_LEN; + string key = value.Substring(j, k - j); + + string replacement = props[key] as string; + + if (replacement != null) + { + buf.Append(replacement); + } + i = k + DELIM_STOP_LEN; + } + } + } } - /// - /// Converts the string representation of the name or numeric value of one or - /// more enumerated constants to an equivalent enumerated object. - /// - /// The type to convert to. - /// The enum string value. - /// If true, ignore case; otherwise, regard case. - /// An object of type whose value is represented by . - private static object ParseEnum(System.Type enumType, string value, bool ignoreCase) - { -#if !NETCF - return Enum.Parse(enumType, value, ignoreCase); -#else - FieldInfo[] fields = enumType.GetFields(BindingFlags.Public | BindingFlags.Static); - - string[] names = value.Split(new char[] {','}); - for (int i = 0; i < names.Length; ++i) - { - names[i] = names [i].Trim(); - } - - long retVal = 0; - - try - { - // Attempt to convert to numeric type - return Enum.ToObject(enumType, Convert.ChangeType(value, typeof(long), CultureInfo.InvariantCulture)); - } - catch {} - - foreach (string name in names) - { - bool found = false; - foreach(FieldInfo field in fields) - { - if (String.Compare(name, field.Name, ignoreCase) == 0) - { - retVal |= ((IConvertible) field.GetValue(null)).ToInt64(CultureInfo.InvariantCulture); - found = true; - break; - } - } - if (!found) - { - throw new ArgumentException("Failed to lookup member [" + name + "] from Enum type [" + enumType.Name + "]"); - } - } - return Enum.ToObject(enumType, retVal); -#endif + /// + /// Converts the string representation of the name or numeric value of one or + /// more enumerated constants to an equivalent enumerated object. + /// + /// The type to convert to. + /// The enum string value. + /// If true, ignore case; otherwise, regard case. + /// An object of type whose value is represented by . + private static object ParseEnum(Type enumType, string value, bool ignoreCase) + { +#if !NETCF + return Enum.Parse(enumType, value, ignoreCase); +#else + FieldInfo[] fields = enumType.GetFields(BindingFlags.Public | BindingFlags.Static); + + string[] names = value.Split(new char[] {','}); + for (int i = 0; i < names.Length; ++i) + { + names[i] = names [i].Trim(); + } + + long retVal = 0; + + try + { + // Attempt to convert to numeric type + return Enum.ToObject(enumType, Convert.ChangeType(value, typeof(long), CultureInfo.InvariantCulture)); + } + catch {} + + foreach (string name in names) + { + bool found = false; + foreach(FieldInfo field in fields) + { + if (String.Compare(name, field.Name, ignoreCase) == 0) + { + retVal |= ((IConvertible) field.GetValue(null)).ToInt64(CultureInfo.InvariantCulture); + found = true; + break; + } + } + if (!found) + { + throw new ArgumentException("Failed to lookup member [" + name + "] from Enum type [" + enumType.Name + "]"); + } + } + return Enum.ToObject(enumType, retVal); +#endif } - /// - /// The fully qualified type of the OptionConverter class. - /// - /// - /// Used by the internal logger to record the Type of the - /// log message. - /// - private static readonly Type declaringType = typeof(OptionConverter); - - private const string DELIM_START = "${"; - private const char DELIM_STOP = '}'; - private const int DELIM_START_LEN = 2; - private const int DELIM_STOP_LEN = 1; - } -} + /// + /// The fully qualified type of the OptionConverter class. + /// + /// + /// Used by the internal logger to record the Type of the + /// log message. + /// + private static readonly Type declaringType = typeof(OptionConverter); + + private const string DELIM_START = "${"; + private const char DELIM_STOP = '}'; + private const int DELIM_START_LEN = 2; + private const int DELIM_STOP_LEN = 1; + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/PatternConverter.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/PatternConverter.cs index 34c2d338556..26c9c64a153 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/PatternConverter.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/PatternConverter.cs @@ -1,376 +1,370 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.Util -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System.Collections; - using System.IO; - using System.Text; +using System.Text; +using System.IO; +using System.Collections; - using log4net.Repository; - using log4net.Util; +using log4net.Util; +using log4net.Repository; - /// - /// Abstract class that provides the formatting functionality that - /// derived classes need. - /// - /// - /// - /// Conversion specifiers in a conversion patterns are parsed to - /// individual PatternConverters. Each of which is responsible for - /// converting a logging event in a converter specific manner. - /// - /// - /// Nicko Cadell. - /// Gert Driesen. - public abstract class PatternConverter +namespace log4net.Util +{ + /// + /// Abstract class that provides the formatting functionality that + /// derived classes need. + /// + /// + /// + /// Conversion specifiers in a conversion patterns are parsed to + /// individual PatternConverters. Each of which is responsible for + /// converting a logging event in a converter specific manner. + /// + /// + /// Nicko Cadell + /// Gert Driesen + public abstract class PatternConverter { /// - /// Initializes a new instance of the class. - /// Protected constructor. - /// - /// - /// - /// Initializes a new instance of the class. - /// - /// - protected PatternConverter() - { + /// Protected constructor + /// + /// + /// + /// Initializes a new instance of the class. + /// + /// + protected PatternConverter() + { } - /// - /// Gets get the next pattern converter in the chain. - /// - /// - /// the next pattern converter in the chain. - /// - /// - /// - /// Get the next pattern converter in the chain. - /// - /// - public virtual PatternConverter Next - { - get { return this.m_next; } - } - - /// - /// Gets or sets the formatting info for this converter. - /// - /// - /// The formatting info for this converter. - /// - /// - /// - /// Gets or sets the formatting info for this converter. - /// - /// - public virtual FormattingInfo FormattingInfo - { - get { return new FormattingInfo(this.m_min, this.m_max, this.m_leftAlign); } + /// + /// Get the next pattern converter in the chain + /// + /// + /// the next pattern converter in the chain + /// + /// + /// + /// Get the next pattern converter in the chain + /// + /// + public virtual PatternConverter Next + { + get { return this.m_next; } + } + + /// + /// Gets or sets the formatting info for this converter + /// + /// + /// The formatting info for this converter + /// + /// + /// + /// Gets or sets the formatting info for this converter + /// + /// + public virtual FormattingInfo FormattingInfo + { + get { return new FormattingInfo(this.m_min, this.m_max, this.m_leftAlign); } + set + { + this.m_min = value.Min; + this.m_max = value.Max; + this.m_leftAlign = value.LeftAlign; + } + } - set - { - this.m_min = value.Min; - this.m_max = value.Max; - this.m_leftAlign = value.LeftAlign; - } - } - - /// - /// Gets or sets the option value for this converter. - /// - /// - /// The option for this converter. - /// - /// - /// - /// Gets or sets the option value for this converter. - /// - /// - public virtual string Option - { - get { return this.m_option; } - set { this.m_option = value; } + /// + /// Gets or sets the option value for this converter + /// + /// + /// The option for this converter + /// + /// + /// + /// Gets or sets the option value for this converter + /// + /// + public virtual string Option + { + get { return this.m_option; } + set { this.m_option = value; } } - /// - /// Evaluate this pattern converter and write the output to a writer. - /// - /// that will receive the formatted result. - /// The state object on which the pattern converter should be executed. - /// - /// - /// Derived pattern converters must override this method in order to - /// convert conversion specifiers in the appropriate way. - /// - /// + /// + /// Evaluate this pattern converter and write the output to a writer. + /// + /// that will receive the formatted result. + /// The state object on which the pattern converter should be executed. + /// + /// + /// Derived pattern converters must override this method in order to + /// convert conversion specifiers in the appropriate way. + /// + /// protected abstract void Convert(TextWriter writer, object state); - /// - /// Set the next pattern converter in the chains. - /// - /// the pattern converter that should follow this converter in the chain. - /// the next converter. - /// - /// - /// The PatternConverter can merge with its neighbor during this method (or a sub class). - /// Therefore the return value may or may not be the value of the argument passed in. - /// - /// - public virtual PatternConverter SetNext(PatternConverter patternConverter) - { - this.m_next = patternConverter; - return this.m_next; - } - - /// - /// Write the pattern converter to the writer with appropriate formatting. - /// - /// that will receive the formatted result. - /// The state object on which the pattern converter should be executed. - /// - /// - /// This method calls to allow the subclass to perform - /// appropriate conversion of the pattern converter. If formatting options have - /// been specified via the then this method will - /// apply those formattings before writing the output. - /// - /// - public virtual void Format(TextWriter writer, object state) - { - if (this.m_min < 0 && this.m_max == int.MaxValue) - { - // Formatting options are not in use - this.Convert(writer, state); - } - else - { - string msg = null; - int len; - lock (this.m_formatWriter) - { - this.m_formatWriter.Reset(c_renderBufferMaxCapacity, c_renderBufferSize); - - this.Convert(this.m_formatWriter, state); - - StringBuilder buf = this.m_formatWriter.GetStringBuilder(); - len = buf.Length; - if (len > this.m_max) - { - msg = buf.ToString(len - this.m_max, this.m_max); - len = this.m_max; - } - else - { - msg = buf.ToString(); - } - } - - if (len < this.m_min) - { - if (this.m_leftAlign) - { - writer.Write(msg); - SpacePad(writer, this.m_min - len); - } - else - { - SpacePad(writer, this.m_min - len); - writer.Write(msg); - } - } - else - { - writer.Write(msg); - } - } - } - - private static readonly string[] SPACES = + /// + /// Set the next pattern converter in the chains + /// + /// the pattern converter that should follow this converter in the chain + /// the next converter + /// + /// + /// The PatternConverter can merge with its neighbor during this method (or a sub class). + /// Therefore the return value may or may not be the value of the argument passed in. + /// + /// + public virtual PatternConverter SetNext(PatternConverter patternConverter) + { + this.m_next = patternConverter; + return this.m_next; + } + + /// + /// Write the pattern converter to the writer with appropriate formatting + /// + /// that will receive the formatted result. + /// The state object on which the pattern converter should be executed. + /// + /// + /// This method calls to allow the subclass to perform + /// appropriate conversion of the pattern converter. If formatting options have + /// been specified via the then this method will + /// apply those formattings before writing the output. + /// + /// + public virtual void Format(TextWriter writer, object state) + { + if (this.m_min < 0 && this.m_max == int.MaxValue) + { + // Formatting options are not in use + this.Convert(writer, state); + } + else + { + string msg = null; + int len; + lock (this.m_formatWriter) + { + this.m_formatWriter.Reset(c_renderBufferMaxCapacity, c_renderBufferSize); + + this.Convert(this.m_formatWriter, state); + + StringBuilder buf = this.m_formatWriter.GetStringBuilder(); + len = buf.Length; + if (len > this.m_max) + { + msg = buf.ToString(len - this.m_max, this.m_max); + len = this.m_max; + } + else + { + msg = buf.ToString(); + } + } + + if (len < this.m_min) + { + if (this.m_leftAlign) + { + writer.Write(msg); + SpacePad(writer, this.m_min - len); + } + else + { + SpacePad(writer, this.m_min - len); + writer.Write(msg); + } + } + else + { + writer.Write(msg); + } + } + } + + private static readonly string[] SPACES = { " ", " ", " ", " ", // 1,2,4,8 spaces + " ", // 16 spaces + " " }; // 32 spaces + + /// + /// Fast space padding method. + /// + /// to which the spaces will be appended. + /// The number of spaces to be padded. + /// + /// + /// Fast space padding method. + /// + /// + protected static void SpacePad(TextWriter writer, int length) { - " ", " ", " ", " ", // 1,2,4,8 spaces - " ", // 16 spaces - " ", - }; // 32 spaces - - /// - /// Fast space padding method. - /// - /// to which the spaces will be appended. - /// The number of spaces to be padded. - /// - /// - /// Fast space padding method. - /// - /// - protected static void SpacePad(TextWriter writer, int length) - { - while (length >= 32) - { - writer.Write(SPACES[5]); - length -= 32; - } - - for (int i = 4; i >= 0; i--) - { - if ((length & (1 << i)) != 0) - { - writer.Write(SPACES[i]); - } - } + while(length >= 32) + { + writer.Write(SPACES[5]); + length -= 32; + } + + for(int i = 4; i >= 0; i--) + { + if ((length & (1 << i)) != 0) + { + writer.Write(SPACES[i]); + } + } } - private PatternConverter m_next; - private int m_min = -1; - private int m_max = int.MaxValue; - private bool m_leftAlign = false; - - /// - /// The option string to the converter. - /// - private string m_option = null; - + private PatternConverter m_next; + private int m_min = -1; + private int m_max = int.MaxValue; + private bool m_leftAlign = false; + + /// + /// The option string to the converter + /// + private string m_option = null; + private ReusableStringWriter m_formatWriter = new ReusableStringWriter(System.Globalization.CultureInfo.InvariantCulture); - /// - /// Initial buffer size. - /// - private const int c_renderBufferSize = 256; - - /// - /// Maximum buffer size before it is recycled. - /// + /// + /// Initial buffer size + /// + private const int c_renderBufferSize = 256; + + /// + /// Maximum buffer size before it is recycled + /// private const int c_renderBufferMaxCapacity = 1024; - /// - /// Write an dictionary to a . - /// - /// the writer to write to. - /// a to use for object conversion. - /// the value to write to the writer. - /// - /// - /// Writes the to a writer in the form: - /// - /// - /// {key1=value1, key2=value2, key3=value3} - /// - /// - /// If the specified - /// is not null then it is used to render the key and value to text, otherwise - /// the object's ToString method is called. - /// - /// - protected static void WriteDictionary(TextWriter writer, ILoggerRepository repository, IDictionary value) - { - WriteDictionary(writer, repository, value.GetEnumerator()); - } - - /// - /// Write an dictionary to a . - /// - /// the writer to write to. - /// a to use for object conversion. - /// the value to write to the writer. - /// - /// - /// Writes the to a writer in the form: - /// - /// - /// {key1=value1, key2=value2, key3=value3} - /// - /// - /// If the specified - /// is not null then it is used to render the key and value to text, otherwise - /// the object's ToString method is called. - /// - /// - protected static void WriteDictionary(TextWriter writer, ILoggerRepository repository, IDictionaryEnumerator value) - { - writer.Write("{"); - - bool first = true; - - // Write out all the dictionary key value pairs - while (value.MoveNext()) - { - if (first) - { - first = false; - } - else - { - writer.Write(", "); - } + /// + /// Write an dictionary to a + /// + /// the writer to write to + /// a to use for object conversion + /// the value to write to the writer + /// + /// + /// Writes the to a writer in the form: + /// + /// + /// {key1=value1, key2=value2, key3=value3} + /// + /// + /// If the specified + /// is not null then it is used to render the key and value to text, otherwise + /// the object's ToString method is called. + /// + /// + protected static void WriteDictionary(TextWriter writer, ILoggerRepository repository, IDictionary value) + { + WriteDictionary(writer, repository, value.GetEnumerator()); + } + + /// + /// Write an dictionary to a + /// + /// the writer to write to + /// a to use for object conversion + /// the value to write to the writer + /// + /// + /// Writes the to a writer in the form: + /// + /// + /// {key1=value1, key2=value2, key3=value3} + /// + /// + /// If the specified + /// is not null then it is used to render the key and value to text, otherwise + /// the object's ToString method is called. + /// + /// + protected static void WriteDictionary(TextWriter writer, ILoggerRepository repository, IDictionaryEnumerator value) + { + writer.Write("{"); + + bool first = true; + + // Write out all the dictionary key value pairs + while (value.MoveNext()) + { + if (first) + { + first = false; + } + else + { + writer.Write(", "); + } + WriteObject(writer, repository, value.Key); + writer.Write("="); + WriteObject(writer, repository, value.Value); + } - WriteObject(writer, repository, value.Key); - writer.Write("="); - WriteObject(writer, repository, value.Value); - } - - writer.Write("}"); - } - - /// - /// Write an object to a . - /// - /// the writer to write to. - /// a to use for object conversion. - /// the value to write to the writer. - /// - /// - /// Writes the Object to a writer. If the specified - /// is not null then it is used to render the object to text, otherwise - /// the object's ToString method is called. - /// - /// - protected static void WriteObject(TextWriter writer, ILoggerRepository repository, object value) - { - if (repository != null) - { - repository.RendererMap.FindAndRender(value, writer); - } - else - { - // Don't have a repository to render with so just have to rely on ToString - if (value == null) - { - writer.Write(SystemInfo.NullText); - } - else - { - writer.Write(value.ToString()); - } - } + writer.Write("}"); } - private PropertiesDictionary properties; - - /// - /// - /// - public PropertiesDictionary Properties - { - get { return this.properties; } - set { this.properties = value; } - } - } -} + /// + /// Write an object to a + /// + /// the writer to write to + /// a to use for object conversion + /// the value to write to the writer + /// + /// + /// Writes the Object to a writer. If the specified + /// is not null then it is used to render the object to text, otherwise + /// the object's ToString method is called. + /// + /// + protected static void WriteObject(TextWriter writer, ILoggerRepository repository, object value) + { + if (repository != null) + { + repository.RendererMap.FindAndRender(value, writer); + } + else + { + // Don't have a repository to render with so just have to rely on ToString + if (value == null) + { + writer.Write( SystemInfo.NullText ); + } + else + { + writer.Write( value.ToString() ); + } + } + } + + private PropertiesDictionary properties; + + /// + /// + /// + public PropertiesDictionary Properties + { + get { return this.properties; } + set { this.properties = value; } + } + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/PatternParser.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/PatternParser.cs index cc6b5cbf447..9dfa275d980 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/PatternParser.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/PatternParser.cs @@ -1,405 +1,400 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.Util -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; - using System.Collections; - using System.Globalization; - - using log4net.Core; - using log4net.Layout; - - /// - /// Most of the work of the class - /// is delegated to the PatternParser class. - /// - /// - /// - /// The PatternParser processes a pattern string and - /// returns a chain of objects. - /// - /// - /// Nicko Cadell. - /// Gert Driesen. - public sealed class PatternParser +using System; +using System.Collections; +using System.Globalization; + +using log4net.Core; +using log4net.Layout; + +namespace log4net.Util +{ + /// + /// Most of the work of the class + /// is delegated to the PatternParser class. + /// + /// + /// + /// The PatternParser processes a pattern string and + /// returns a chain of objects. + /// + /// + /// Nicko Cadell + /// Gert Driesen + public sealed class PatternParser { /// - /// Initializes a new instance of the class. - /// Constructor. - /// - /// The pattern to parse. - /// - /// - /// Initializes a new instance of the class - /// with the specified pattern string. - /// - /// - public PatternParser(string pattern) - { - this.m_pattern = pattern; + /// Constructor + /// + /// The pattern to parse. + /// + /// + /// Initializes a new instance of the class + /// with the specified pattern string. + /// + /// + public PatternParser(string pattern) + { + this.m_pattern = pattern; } - /// - /// Parses the pattern into a chain of pattern converters. - /// - /// The head of a chain of pattern converters. - /// - /// - /// Parses the pattern into a chain of pattern converters. - /// - /// - public PatternConverter Parse() - { - string[] converterNamesCache = this.BuildCache(); - - this.ParseInternal(this.m_pattern, converterNamesCache); - - return this.m_head; + /// + /// Parses the pattern into a chain of pattern converters. + /// + /// The head of a chain of pattern converters. + /// + /// + /// Parses the pattern into a chain of pattern converters. + /// + /// + public PatternConverter Parse() + { + string[] converterNamesCache = this.BuildCache(); + + this.ParseInternal(this.m_pattern, converterNamesCache); + + return this.m_head; } - /// - /// Gets get the converter registry used by this parser. - /// - /// - /// The converter registry used by this parser. - /// - /// - /// - /// Get the converter registry used by this parser. - /// - /// - public Hashtable PatternConverters - { - get { return this.m_patternConverters; } + /// + /// Get the converter registry used by this parser + /// + /// + /// The converter registry used by this parser + /// + /// + /// + /// Get the converter registry used by this parser + /// + /// + public Hashtable PatternConverters + { + get { return this.m_patternConverters; } } - /// - /// Build the unified cache of converters from the static and instance maps. - /// - /// the list of all the converter names. - /// - /// - /// Build the unified cache of converters from the static and instance maps. - /// - /// - private string[] BuildCache() - { - string[] converterNamesCache = new string[this.m_patternConverters.Keys.Count]; - this.m_patternConverters.Keys.CopyTo(converterNamesCache, 0); - - // sort array so that longer strings come first - Array.Sort(converterNamesCache, 0, converterNamesCache.Length, StringLengthComparer.Instance); - - return converterNamesCache; + /// + /// Build the unified cache of converters from the static and instance maps + /// + /// the list of all the converter names + /// + /// + /// Build the unified cache of converters from the static and instance maps + /// + /// + private string[] BuildCache() + { + string[] converterNamesCache = new string[this.m_patternConverters.Keys.Count]; + this.m_patternConverters.Keys.CopyTo(converterNamesCache, 0); + + // sort array so that longer strings come first + Array.Sort(converterNamesCache, 0, converterNamesCache.Length, StringLengthComparer.Instance); + + return converterNamesCache; } - /// - /// Sort strings by length. - /// - /// - /// - /// that orders strings by string length. - /// The longest strings are placed first. - /// - /// - private sealed class StringLengthComparer : IComparer - { - public static readonly StringLengthComparer Instance = new StringLengthComparer(); - - private StringLengthComparer() - { + /// + /// Sort strings by length + /// + /// + /// + /// that orders strings by string length. + /// The longest strings are placed first + /// + /// + private sealed class StringLengthComparer : IComparer + { + public static readonly StringLengthComparer Instance = new StringLengthComparer(); + + private StringLengthComparer() + { } - public int Compare(object x, object y) - { - string s1 = x as string; - string s2 = y as string; - - if (s1 == null && s2 == null) - { - return 0; - } - - if (s1 == null) - { - return 1; - } - - if (s2 == null) - { - return -1; - } - - return s2.Length.CompareTo(s1.Length); + public int Compare(object x, object y) + { + string s1 = x as string; + string s2 = y as string; + + if (s1 == null && s2 == null) + { + return 0; + } + if (s1 == null) + { + return 1; + } + if (s2 == null) + { + return -1; + } + + return s2.Length.CompareTo(s1.Length); } } - /// - /// Internal method to parse the specified pattern to find specified matches. - /// - /// the pattern to parse. - /// the converter names to match in the pattern. - /// - /// - /// The matches param must be sorted such that longer strings come before shorter ones. - /// - /// - private void ParseInternal(string pattern, string[] matches) - { - int offset = 0; - while (offset < pattern.Length) - { - int i = pattern.IndexOf('%', offset); - if (i < 0 || i == pattern.Length - 1) - { - this.ProcessLiteral(pattern.Substring(offset)); - offset = pattern.Length; - } - else - { - if (pattern[i + 1] == '%') - { - // Escaped - this.ProcessLiteral(pattern.Substring(offset, i - offset + 1)); - offset = i + 2; - } - else - { - this.ProcessLiteral(pattern.Substring(offset, i - offset)); - offset = i + 1; - - FormattingInfo formattingInfo = new FormattingInfo(); - - // Process formatting options - - // Look for the align flag - if (offset < pattern.Length) - { - if (pattern[offset] == '-') - { - // Seen align flag - formattingInfo.LeftAlign = true; - offset++; - } - } - - // Look for the minimum length - while (offset < pattern.Length && char.IsDigit(pattern[offset])) - { - // Seen digit - if (formattingInfo.Min < 0) - { - formattingInfo.Min = 0; - } - - formattingInfo.Min = (formattingInfo.Min * 10) + int.Parse(pattern[offset].ToString(), NumberFormatInfo.InvariantInfo); - - offset++; - } - - // Look for the separator between min and max - if (offset < pattern.Length) - { - if (pattern[offset] == '.') - { - // Seen separator - offset++; - } - } - - // Look for the maximum length - while (offset < pattern.Length && char.IsDigit(pattern[offset])) - { - // Seen digit - if (formattingInfo.Max == int.MaxValue) - { - formattingInfo.Max = 0; - } - - formattingInfo.Max = (formattingInfo.Max * 10) + int.Parse(pattern[offset].ToString(), NumberFormatInfo.InvariantInfo); - - offset++; - } - - int remainingStringLength = pattern.Length - offset; - - // Look for pattern - for (int m = 0; m < matches.Length; m++) - { - string key = matches[m]; - - if (key.Length <= remainingStringLength) - { - if (string.Compare(pattern, offset, key, 0, key.Length) == 0) - { - // Found match - offset = offset + matches[m].Length; - - string option = null; - - // Look for option - if (offset < pattern.Length) - { - if (pattern[offset] == '{') - { - // Seen option start - offset++; - - int optEnd = pattern.IndexOf('}', offset); - if (optEnd < 0) - { - // error - } - else - { - option = pattern.Substring(offset, optEnd - offset); - offset = optEnd + 1; - } - } - } - - this.ProcessConverter(matches[m], option, formattingInfo); - break; - } - } - } - } - } - } - } - - /// - /// Process a parsed literal. - /// - /// the literal text. - private void ProcessLiteral(string text) - { - if (text.Length > 0) - { - // Convert into a pattern - this.ProcessConverter("literal", text, new FormattingInfo()); - } - } - - /// - /// Process a parsed converter pattern. - /// - /// the name of the converter. - /// the optional option for the converter. - /// the formatting info for the converter. - private void ProcessConverter(string converterName, string option, FormattingInfo formattingInfo) - { - LogLog.Debug(declaringType, "Converter [" + converterName + "] Option [" + option + "] Format [min=" + formattingInfo.Min + ",max=" + formattingInfo.Max + ",leftAlign=" + formattingInfo.LeftAlign + "]"); - - // Lookup the converter type - ConverterInfo converterInfo = (ConverterInfo)this.m_patternConverters[converterName]; - if (converterInfo == null) - { - LogLog.Error(declaringType, "Unknown converter name [" + converterName + "] in conversion pattern."); - } - else - { - // Create the pattern converter - PatternConverter pc = null; - try - { - pc = (PatternConverter)Activator.CreateInstance(converterInfo.Type); - } - catch (Exception createInstanceEx) - { - LogLog.Error(declaringType, "Failed to create instance of Type [" + converterInfo.Type.FullName + "] using default constructor. Exception: " + createInstanceEx.ToString()); - } - - // formattingInfo variable is an instance variable, occasionally reset - // and used over and over again - pc.FormattingInfo = formattingInfo; - pc.Option = option; - pc.Properties = converterInfo.Properties; - - IOptionHandler optionHandler = pc as IOptionHandler; - if (optionHandler != null) - { - optionHandler.ActivateOptions(); - } - - this.AddConverter(pc); - } - } - - /// - /// Resets the internal state of the parser and adds the specified pattern converter - /// to the chain. - /// - /// The pattern converter to add. - private void AddConverter(PatternConverter pc) - { - // Add the pattern converter to the list. - if (this.m_head == null) - { - this.m_head = this.m_tail = pc; - } - else - { - // Set the next converter on the tail - // Update the tail reference - // note that a converter may combine the 'next' into itself - // and therefore the tail would not change! - this.m_tail = this.m_tail.SetNext(pc); - } + /// + /// Internal method to parse the specified pattern to find specified matches + /// + /// the pattern to parse + /// the converter names to match in the pattern + /// + /// + /// The matches param must be sorted such that longer strings come before shorter ones. + /// + /// + private void ParseInternal(string pattern, string[] matches) + { + int offset = 0; + while(offset < pattern.Length) + { + int i = pattern.IndexOf('%', offset); + if (i < 0 || i == pattern.Length - 1) + { + this.ProcessLiteral(pattern.Substring(offset)); + offset = pattern.Length; + } + else + { + if (pattern[i+1] == '%') + { + // Escaped + this.ProcessLiteral(pattern.Substring(offset, i - offset + 1)); + offset = i + 2; + } + else + { + this.ProcessLiteral(pattern.Substring(offset, i - offset)); + offset = i + 1; + + FormattingInfo formattingInfo = new FormattingInfo(); + + // Process formatting options + + // Look for the align flag + if (offset < pattern.Length) + { + if (pattern[offset] == '-') + { + // Seen align flag + formattingInfo.LeftAlign = true; + offset++; + } + } + // Look for the minimum length + while (offset < pattern.Length && char.IsDigit(pattern[offset])) + { + // Seen digit + if (formattingInfo.Min < 0) + { + formattingInfo.Min = 0; + } + + formattingInfo.Min = (formattingInfo.Min * 10) + int.Parse(pattern[offset].ToString(), NumberFormatInfo.InvariantInfo); + + offset++; + } + // Look for the separator between min and max + if (offset < pattern.Length) + { + if (pattern[offset] == '.') + { + // Seen separator + offset++; + } + } + // Look for the maximum length + while (offset < pattern.Length && char.IsDigit(pattern[offset])) + { + // Seen digit + if (formattingInfo.Max == int.MaxValue) + { + formattingInfo.Max = 0; + } + + formattingInfo.Max = (formattingInfo.Max * 10) + int.Parse(pattern[offset].ToString(), NumberFormatInfo.InvariantInfo); + + offset++; + } + + int remainingStringLength = pattern.Length - offset; + + // Look for pattern + for(int m = 0; m + /// Process a parsed literal + /// + /// the literal text + private void ProcessLiteral(string text) + { + if (text.Length > 0) + { + // Convert into a pattern + this.ProcessConverter("literal", text, new FormattingInfo()); + } + } + + /// + /// Process a parsed converter pattern + /// + /// the name of the converter + /// the optional option for the converter + /// the formatting info for the converter + private void ProcessConverter(string converterName, string option, FormattingInfo formattingInfo) + { + LogLog.Debug(declaringType, "Converter [" + converterName + "] Option [" + option + "] Format [min=" + formattingInfo.Min + ",max=" + formattingInfo.Max + ",leftAlign=" + formattingInfo.LeftAlign + "]"); + + // Lookup the converter type + ConverterInfo converterInfo = (ConverterInfo)this.m_patternConverters[converterName]; + if (converterInfo == null) + { + LogLog.Error(declaringType, "Unknown converter name [" + converterName + "] in conversion pattern."); + } + else + { + // Create the pattern converter + PatternConverter pc = null; + try + { + pc = (PatternConverter)Activator.CreateInstance(converterInfo.Type); + } + catch(Exception createInstanceEx) + { + LogLog.Error(declaringType, "Failed to create instance of Type [" + converterInfo.Type.FullName + "] using default constructor. Exception: " + createInstanceEx.ToString()); + } + + // formattingInfo variable is an instance variable, occasionally reset + // and used over and over again + pc.FormattingInfo = formattingInfo; + pc.Option = option; + pc.Properties = converterInfo.Properties; + + IOptionHandler optionHandler = pc as IOptionHandler; + if (optionHandler != null) + { + optionHandler.ActivateOptions(); + } + + this.AddConverter(pc); + } + } + + /// + /// Resets the internal state of the parser and adds the specified pattern converter + /// to the chain. + /// + /// The pattern converter to add. + private void AddConverter(PatternConverter pc) + { + // Add the pattern converter to the list. + + if (this.m_head == null) + { + this.m_head = this.m_tail = pc; + } + else + { + // Set the next converter on the tail + // Update the tail reference + // note that a converter may combine the 'next' into itself + // and therefore the tail would not change! + this.m_tail = this.m_tail.SetNext(pc); + } } private const char ESCAPE_CHAR = '%'; - /// - /// The first pattern converter in the chain. - /// - private PatternConverter m_head; - - /// - /// the last pattern converter in the chain. - /// - private PatternConverter m_tail; - - /// - /// The pattern. - /// - private string m_pattern; - - /// - /// Internal map of converter identifiers to converter types. - /// - /// - /// - /// This map overrides the static s_globalRulesRegistry map. - /// - /// + /// + /// The first pattern converter in the chain + /// + private PatternConverter m_head; + + /// + /// the last pattern converter in the chain + /// + private PatternConverter m_tail; + + /// + /// The pattern + /// + private string m_pattern; + + /// + /// Internal map of converter identifiers to converter types + /// + /// + /// + /// This map overrides the static s_globalRulesRegistry map. + /// + /// private Hashtable m_patternConverters = new Hashtable(); - /// - /// The fully qualified type of the PatternParser class. - /// - /// - /// Used by the internal logger to record the Type of the - /// log message. - /// + /// + /// The fully qualified type of the PatternParser class. + /// + /// + /// Used by the internal logger to record the Type of the + /// log message. + /// private static readonly Type declaringType = typeof(PatternParser); - } -} + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/PatternString.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/PatternString.cs index 42cba7675f9..11b0b9de89d 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/PatternString.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/PatternString.cs @@ -1,505 +1,497 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +using System; +using System.Collections; +using System.IO; -#if NETSTANDARD1_3 -using System.Reflection; -#endif - -using log4net.Core; -using log4net.Util; -using log4net.Util.PatternStringConverters; - -namespace log4net.Util -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; - using System.Collections; - using System.IO; +using log4net.Util.PatternStringConverters; +using log4net.Core; - /// - /// This class implements a patterned string. - /// - /// - /// - /// This string has embedded patterns that are resolved and expanded - /// when the string is formatted. - /// - /// - /// This class functions similarly to the - /// in that it accepts a pattern and renders it to a string. Unlike the - /// however the PatternString - /// does not render the properties of a specific but - /// of the process in general. - /// - /// - /// The recognized conversion pattern names are: - /// - /// - /// - /// Conversion Pattern Name - /// Effect - /// - /// - /// appdomain - /// - /// - /// Used to output the friendly name of the current AppDomain. - /// - /// - /// - /// - /// appsetting - /// - /// - /// Used to output the value of a specific appSetting key in the application - /// configuration file. - /// - /// - /// - /// - /// date - /// - /// - /// Used to output the current date and time in the local time zone. - /// To output the date in universal time use the %utcdate pattern. - /// The date conversion - /// specifier may be followed by a date format specifier enclosed - /// between braces. For example, %date{HH:mm:ss,fff} or - /// %date{dd MMM yyyy HH:mm:ss,fff}. If no date format specifier is - /// given then ISO8601 format is - /// assumed (). - /// - /// - /// The date format specifier admits the same syntax as the - /// time pattern string of the . - /// - /// - /// For better results it is recommended to use the log4net date - /// formatters. These can be specified using one of the strings - /// "ABSOLUTE", "DATE" and "ISO8601" for specifying - /// , - /// and respectively - /// . For example, - /// %date{ISO8601} or %date{ABSOLUTE}. - /// - /// - /// These dedicated date formatters perform significantly - /// better than . - /// - /// - /// - /// - /// env - /// - /// - /// Used to output the a specific environment variable. The key to - /// lookup must be specified within braces and directly following the - /// pattern specifier, e.g. %env{COMPUTERNAME} would include the value - /// of the COMPUTERNAME environment variable. - /// - /// - /// The env pattern is not supported on the .NET Compact Framework. - /// - /// - /// - /// - /// identity - /// - /// - /// Used to output the user name for the currently active user - /// (Principal.Identity.Name). - /// - /// - /// - /// - /// newline - /// - /// - /// Outputs the platform dependent line separator character or - /// characters. - /// - /// - /// This conversion pattern name offers the same performance as using - /// non-portable line separator strings such as "\n", or "\r\n". - /// Thus, it is the preferred way of specifying a line separator. - /// - /// - /// - /// - /// processid - /// - /// - /// Used to output the system process ID for the current process. - /// - /// - /// - /// - /// property - /// - /// - /// Used to output a specific context property. The key to - /// lookup must be specified within braces and directly following the - /// pattern specifier, e.g. %property{user} would include the value - /// from the property that is keyed by the string 'user'. Each property value - /// that is to be included in the log must be specified separately. - /// Properties are stored in logging contexts. By default - /// the log4net:HostName property is set to the name of machine on - /// which the event was originally logged. - /// - /// - /// If no key is specified, e.g. %property then all the keys and their - /// values are printed in a comma separated list. - /// - /// - /// The properties of an event are combined from a number of different - /// contexts. These are listed below in the order in which they are searched. - /// - /// - /// - /// the thread properties - /// - /// The that are set on the current - /// thread. These properties are shared by all events logged on this thread. - /// - /// - /// - /// the global properties - /// - /// The that are set globally. These - /// properties are shared by all the threads in the AppDomain. - /// - /// - /// - /// - /// - /// - /// random - /// - /// - /// Used to output a random string of characters. The string is made up of - /// uppercase letters and numbers. By default the string is 4 characters long. - /// The length of the string can be specified within braces directly following the - /// pattern specifier, e.g. %random{8} would output an 8 character string. - /// - /// - /// - /// - /// username - /// - /// - /// Used to output the WindowsIdentity for the currently - /// active user. - /// - /// - /// - /// - /// utcdate - /// - /// - /// Used to output the date of the logging event in universal time. - /// The date conversion - /// specifier may be followed by a date format specifier enclosed - /// between braces. For example, %utcdate{HH:mm:ss,fff} or - /// %utcdate{dd MMM yyyy HH:mm:ss,fff}. If no date format specifier is - /// given then ISO8601 format is - /// assumed (). - /// - /// - /// The date format specifier admits the same syntax as the - /// time pattern string of the . - /// - /// - /// For better results it is recommended to use the log4net date - /// formatters. These can be specified using one of the strings - /// "ABSOLUTE", "DATE" and "ISO8601" for specifying - /// , - /// and respectively - /// . For example, - /// %utcdate{ISO8601} or %utcdate{ABSOLUTE}. - /// - /// - /// These dedicated date formatters perform significantly - /// better than . - /// - /// - /// - /// - /// % - /// - /// - /// The sequence %% outputs a single percent sign. - /// - /// - /// - /// - /// - /// Additional pattern converters may be registered with a specific - /// instance using or - /// . - /// - /// - /// See the for details on the - /// format modifiers supported by the patterns. - /// - /// - /// Nicko Cadell. - public class PatternString : IOptionHandler +namespace log4net.Util +{ + /// + /// This class implements a patterned string. + /// + /// + /// + /// This string has embedded patterns that are resolved and expanded + /// when the string is formatted. + /// + /// + /// This class functions similarly to the + /// in that it accepts a pattern and renders it to a string. Unlike the + /// however the PatternString + /// does not render the properties of a specific but + /// of the process in general. + /// + /// + /// The recognized conversion pattern names are: + /// + /// + /// + /// Conversion Pattern Name + /// Effect + /// + /// + /// appdomain + /// + /// + /// Used to output the friendly name of the current AppDomain. + /// + /// + /// + /// + /// appsetting + /// + /// + /// Used to output the value of a specific appSetting key in the application + /// configuration file. + /// + /// + /// + /// + /// date + /// + /// + /// Used to output the current date and time in the local time zone. + /// To output the date in universal time use the %utcdate pattern. + /// The date conversion + /// specifier may be followed by a date format specifier enclosed + /// between braces. For example, %date{HH:mm:ss,fff} or + /// %date{dd MMM yyyy HH:mm:ss,fff}. If no date format specifier is + /// given then ISO8601 format is + /// assumed (). + /// + /// + /// The date format specifier admits the same syntax as the + /// time pattern string of the . + /// + /// + /// For better results it is recommended to use the log4net date + /// formatters. These can be specified using one of the strings + /// "ABSOLUTE", "DATE" and "ISO8601" for specifying + /// , + /// and respectively + /// . For example, + /// %date{ISO8601} or %date{ABSOLUTE}. + /// + /// + /// These dedicated date formatters perform significantly + /// better than . + /// + /// + /// + /// + /// env + /// + /// + /// Used to output the a specific environment variable. The key to + /// lookup must be specified within braces and directly following the + /// pattern specifier, e.g. %env{COMPUTERNAME} would include the value + /// of the COMPUTERNAME environment variable. + /// + /// + /// The env pattern is not supported on the .NET Compact Framework. + /// + /// + /// + /// + /// identity + /// + /// + /// Used to output the user name for the currently active user + /// (Principal.Identity.Name). + /// + /// + /// + /// + /// newline + /// + /// + /// Outputs the platform dependent line separator character or + /// characters. + /// + /// + /// This conversion pattern name offers the same performance as using + /// non-portable line separator strings such as "\n", or "\r\n". + /// Thus, it is the preferred way of specifying a line separator. + /// + /// + /// + /// + /// processid + /// + /// + /// Used to output the system process ID for the current process. + /// + /// + /// + /// + /// property + /// + /// + /// Used to output a specific context property. The key to + /// lookup must be specified within braces and directly following the + /// pattern specifier, e.g. %property{user} would include the value + /// from the property that is keyed by the string 'user'. Each property value + /// that is to be included in the log must be specified separately. + /// Properties are stored in logging contexts. By default + /// the log4net:HostName property is set to the name of machine on + /// which the event was originally logged. + /// + /// + /// If no key is specified, e.g. %property then all the keys and their + /// values are printed in a comma separated list. + /// + /// + /// The properties of an event are combined from a number of different + /// contexts. These are listed below in the order in which they are searched. + /// + /// + /// + /// the thread properties + /// + /// The that are set on the current + /// thread. These properties are shared by all events logged on this thread. + /// + /// + /// + /// the global properties + /// + /// The that are set globally. These + /// properties are shared by all the threads in the AppDomain. + /// + /// + /// + /// + /// + /// + /// random + /// + /// + /// Used to output a random string of characters. The string is made up of + /// uppercase letters and numbers. By default the string is 4 characters long. + /// The length of the string can be specified within braces directly following the + /// pattern specifier, e.g. %random{8} would output an 8 character string. + /// + /// + /// + /// + /// username + /// + /// + /// Used to output the WindowsIdentity for the currently + /// active user. + /// + /// + /// + /// + /// utcdate + /// + /// + /// Used to output the date of the logging event in universal time. + /// The date conversion + /// specifier may be followed by a date format specifier enclosed + /// between braces. For example, %utcdate{HH:mm:ss,fff} or + /// %utcdate{dd MMM yyyy HH:mm:ss,fff}. If no date format specifier is + /// given then ISO8601 format is + /// assumed (). + /// + /// + /// The date format specifier admits the same syntax as the + /// time pattern string of the . + /// + /// + /// For better results it is recommended to use the log4net date + /// formatters. These can be specified using one of the strings + /// "ABSOLUTE", "DATE" and "ISO8601" for specifying + /// , + /// and respectively + /// . For example, + /// %utcdate{ISO8601} or %utcdate{ABSOLUTE}. + /// + /// + /// These dedicated date formatters perform significantly + /// better than . + /// + /// + /// + /// + /// % + /// + /// + /// The sequence %% outputs a single percent sign. + /// + /// + /// + /// + /// + /// Additional pattern converters may be registered with a specific + /// instance using or + /// . + /// + /// + /// See the for details on the + /// format modifiers supported by the patterns. + /// + /// + /// Nicko Cadell + public class PatternString : IOptionHandler { - /// - /// Internal map of converter identifiers to converter types. - /// + /// + /// Internal map of converter identifiers to converter types. + /// private static Hashtable s_globalRulesRegistry; - /// - /// the pattern. - /// - private string m_pattern; - - /// - /// the head of the pattern converter chain. - /// - private PatternConverter m_head; - - /// - /// patterns defined on this PatternString only. - /// + /// + /// the pattern + /// + private string m_pattern; + + /// + /// the head of the pattern converter chain + /// + private PatternConverter m_head; + + /// + /// patterns defined on this PatternString only + /// private Hashtable m_instanceRulesRegistry = new Hashtable(); /// - /// Initializes static members of the class. - /// Initialize the global registry. - /// - static PatternString() - { - s_globalRulesRegistry = new Hashtable(18); - - s_globalRulesRegistry.Add("appdomain", typeof(AppDomainPatternConverter)); - s_globalRulesRegistry.Add("date", typeof(DatePatternConverter)); -#if !NETCF - s_globalRulesRegistry.Add("env", typeof(EnvironmentPatternConverter)); -#if !NETSTANDARD1_3 // EnvironmentFolderPathPatternConverter not yet supported - s_globalRulesRegistry.Add("envFolderPath", typeof(EnvironmentFolderPathPatternConverter)); -#endif -#endif - s_globalRulesRegistry.Add("identity", typeof(IdentityPatternConverter)); - s_globalRulesRegistry.Add("literal", typeof(LiteralPatternConverter)); - s_globalRulesRegistry.Add("newline", typeof(NewLinePatternConverter)); - s_globalRulesRegistry.Add("processid", typeof(ProcessIdPatternConverter)); - s_globalRulesRegistry.Add("property", typeof(PropertyPatternConverter)); - s_globalRulesRegistry.Add("random", typeof(RandomStringPatternConverter)); - s_globalRulesRegistry.Add("username", typeof(UserNamePatternConverter)); - - s_globalRulesRegistry.Add("utcdate", typeof(UtcDatePatternConverter)); - s_globalRulesRegistry.Add("utcDate", typeof(UtcDatePatternConverter)); - s_globalRulesRegistry.Add("UtcDate", typeof(UtcDatePatternConverter)); -#if !NETCF && !NETSTANDARD1_3 - // TODO - have added common variants of casing like utcdate above. - // Wouldn't it be better to use a case-insensitive Hashtable? - s_globalRulesRegistry.Add("appsetting", typeof(AppSettingPatternConverter)); - s_globalRulesRegistry.Add("appSetting", typeof(AppSettingPatternConverter)); - s_globalRulesRegistry.Add("AppSetting", typeof(AppSettingPatternConverter)); -#endif + /// Initialize the global registry + /// + static PatternString() + { + s_globalRulesRegistry = new Hashtable(18); + + s_globalRulesRegistry.Add("appdomain", typeof(AppDomainPatternConverter)); + s_globalRulesRegistry.Add("date", typeof(DatePatternConverter)); +#if !NETCF + s_globalRulesRegistry.Add("env", typeof(EnvironmentPatternConverter)); +#if !NETSTANDARD1_3 // EnvironmentFolderPathPatternConverter not yet supported + s_globalRulesRegistry.Add("envFolderPath", typeof(EnvironmentFolderPathPatternConverter)); +#endif +#endif + s_globalRulesRegistry.Add("identity", typeof(IdentityPatternConverter)); + s_globalRulesRegistry.Add("literal", typeof(LiteralPatternConverter)); + s_globalRulesRegistry.Add("newline", typeof(NewLinePatternConverter)); + s_globalRulesRegistry.Add("processid", typeof(ProcessIdPatternConverter)); + s_globalRulesRegistry.Add("property", typeof(PropertyPatternConverter)); + s_globalRulesRegistry.Add("random", typeof(RandomStringPatternConverter)); + s_globalRulesRegistry.Add("username", typeof(UserNamePatternConverter)); + + s_globalRulesRegistry.Add("utcdate", typeof(UtcDatePatternConverter)); + s_globalRulesRegistry.Add("utcDate", typeof(UtcDatePatternConverter)); + s_globalRulesRegistry.Add("UtcDate", typeof(UtcDatePatternConverter)); +#if !NETCF && !NETSTANDARD1_3 + // TODO - have added common variants of casing like utcdate above. + // Wouldn't it be better to use a case-insensitive Hashtable? + s_globalRulesRegistry.Add("appsetting", typeof(AppSettingPatternConverter)); + s_globalRulesRegistry.Add("appSetting", typeof(AppSettingPatternConverter)); + s_globalRulesRegistry.Add("AppSetting", typeof(AppSettingPatternConverter)); +#endif + } + + /// + /// Default constructor + /// + /// + /// + /// Initialize a new instance of + /// + /// + public PatternString() + { } /// - /// Initializes a new instance of the class. - /// Default constructor. - /// - /// - /// - /// Initialize a new instance of . - /// - /// - public PatternString() - { + /// Constructs a PatternString + /// + /// The pattern to use with this PatternString + /// + /// + /// Initialize a new instance of with the pattern specified. + /// + /// + public PatternString(string pattern) + { + this.m_pattern = pattern; + this.ActivateOptions(); } /// - /// Initializes a new instance of the class. - /// Constructs a PatternString. - /// - /// The pattern to use with this PatternString. - /// - /// - /// Initialize a new instance of with the pattern specified. - /// - /// - public PatternString(string pattern) - { - this.m_pattern = pattern; - this.ActivateOptions(); + /// Gets or sets the pattern formatting string + /// + /// + /// The pattern formatting string + /// + /// + /// + /// The ConversionPattern option. This is the string which + /// controls formatting and consists of a mix of literal content and + /// conversion specifiers. + /// + /// + public string ConversionPattern + { + get { return this.m_pattern; } + set { this.m_pattern = value; } } - /// - /// Gets or sets the pattern formatting string. - /// - /// - /// The pattern formatting string. - /// - /// - /// - /// The ConversionPattern option. This is the string which - /// controls formatting and consists of a mix of literal content and - /// conversion specifiers. - /// - /// - public string ConversionPattern - { - get { return this.m_pattern; } - set { this.m_pattern = value; } + /// + /// Initialize object options + /// + /// + /// + /// This is part of the delayed object + /// activation scheme. The method must + /// be called on this object after the configuration properties have + /// been set. Until is called this + /// object is in an undefined state and must not be used. + /// + /// + /// If any of the configuration properties are modified then + /// must be called again. + /// + /// + public virtual void ActivateOptions() + { + this.m_head = this.CreatePatternParser(this.m_pattern).Parse(); + } + + /// + /// Create the used to parse the pattern + /// + /// the pattern to parse + /// The + /// + /// + /// Returns PatternParser used to parse the conversion string. Subclasses + /// may override this to return a subclass of PatternParser which recognize + /// custom conversion pattern name. + /// + /// + private PatternParser CreatePatternParser(string pattern) + { + PatternParser patternParser = new PatternParser(pattern); + + // Add all the builtin patterns + foreach(DictionaryEntry entry in s_globalRulesRegistry) + { + ConverterInfo converterInfo = new ConverterInfo(); + converterInfo.Name = (string)entry.Key; + converterInfo.Type = (Type)entry.Value; + patternParser.PatternConverters.Add(entry.Key, converterInfo); + } + // Add the instance patterns + foreach(DictionaryEntry entry in this.m_instanceRulesRegistry) + { + patternParser.PatternConverters[entry.Key] = entry.Value; + } + + return patternParser; } + + /// + /// Produces a formatted string as specified by the conversion pattern. + /// + /// The TextWriter to write the formatted event to + /// + /// + /// Format the pattern to the . + /// + /// + public void Format(TextWriter writer) + { + if (writer == null) + { + throw new ArgumentNullException("writer"); + } + + PatternConverter c = this.m_head; - /// - /// Initialize object options. - /// - /// - /// - /// This is part of the delayed object - /// activation scheme. The method must - /// be called on this object after the configuration properties have - /// been set. Until is called this - /// object is in an undefined state and must not be used. - /// - /// - /// If any of the configuration properties are modified then - /// must be called again. - /// - /// - public virtual void ActivateOptions() - { - this.m_head = this.CreatePatternParser(this.m_pattern).Parse(); + // loop through the chain of pattern converters + while(c != null) + { + c.Format(writer, null); + c = c.Next; + } } - /// - /// Create the used to parse the pattern. - /// - /// the pattern to parse. - /// The . - /// - /// - /// Returns PatternParser used to parse the conversion string. Subclasses - /// may override this to return a subclass of PatternParser which recognize - /// custom conversion pattern name. - /// - /// - private PatternParser CreatePatternParser(string pattern) - { - PatternParser patternParser = new PatternParser(pattern); - - // Add all the builtin patterns - foreach (DictionaryEntry entry in s_globalRulesRegistry) - { - ConverterInfo converterInfo = new ConverterInfo(); - converterInfo.Name = (string)entry.Key; - converterInfo.Type = (Type)entry.Value; - patternParser.PatternConverters.Add(entry.Key, converterInfo); - } + /// + /// Format the pattern as a string + /// + /// the pattern formatted as a string + /// + /// + /// Format the pattern to a string. + /// + /// + public string Format() + { + using (var writer = new StringWriter(System.Globalization.CultureInfo.InvariantCulture)) + { + this.Format(writer); + return writer.ToString(); + } + } - // Add the instance patterns - foreach (DictionaryEntry entry in this.m_instanceRulesRegistry) - { - patternParser.PatternConverters[entry.Key] = entry.Value; - } - - return patternParser; - } - - /// - /// Produces a formatted string as specified by the conversion pattern. - /// - /// The TextWriter to write the formatted event to. - /// - /// - /// Format the pattern to the . - /// - /// - public void Format(TextWriter writer) - { - if (writer == null) - { - throw new ArgumentNullException("writer"); - } - - PatternConverter c = this.m_head; - - // loop through the chain of pattern converters - while (c != null) - { - c.Format(writer, null); - c = c.Next; - } - } - - /// - /// Format the pattern as a string. - /// - /// the pattern formatted as a string. - /// - /// - /// Format the pattern to a string. - /// - /// - public string Format() - { - StringWriter writer = new StringWriter(System.Globalization.CultureInfo.InvariantCulture); - this.Format(writer); - return writer.ToString(); - } - - /// - /// Add a converter to this PatternString. - /// - /// the converter info. - /// - /// - /// This version of the method is used by the configurator. - /// Programmatic users should use the alternative method. - /// - /// - public void AddConverter(ConverterInfo converterInfo) - { + /// + /// Add a converter to this PatternString + /// + /// the converter info + /// + /// + /// This version of the method is used by the configurator. + /// Programmatic users should use the alternative method. + /// + /// + public void AddConverter(ConverterInfo converterInfo) + { if (converterInfo == null) { throw new ArgumentNullException("converterInfo"); } - if (!typeof(PatternConverter).IsAssignableFrom(converterInfo.Type)) - { - throw new ArgumentException("The converter type specified [" + converterInfo.Type + "] must be a subclass of log4net.Util.PatternConverter", "converterInfo"); - } + if (!typeof(PatternConverter).IsAssignableFrom(converterInfo.Type)) + { + throw new ArgumentException("The converter type specified [" + converterInfo.Type + "] must be a subclass of log4net.Util.PatternConverter", "converterInfo"); + } - this.m_instanceRulesRegistry[converterInfo.Name] = converterInfo; - } - - /// - /// Add a converter to this PatternString. - /// - /// the name of the conversion pattern for this converter. - /// the type of the converter. - /// - /// - /// Add a converter to this PatternString. - /// - /// - public void AddConverter(string name, Type type) - { + this.m_instanceRulesRegistry[converterInfo.Name] = converterInfo; + } + + /// + /// Add a converter to this PatternString + /// + /// the name of the conversion pattern for this converter + /// the type of the converter + /// + /// + /// Add a converter to this PatternString + /// + /// + public void AddConverter(string name, Type type) + { if (name == null) { throw new ArgumentNullException("name"); @@ -510,11 +502,11 @@ public void AddConverter(string name, Type type) throw new ArgumentNullException("type"); } - ConverterInfo converterInfo = new ConverterInfo(); - converterInfo.Name = name; - converterInfo.Type = type; - - this.AddConverter(converterInfo); - } - } -} + ConverterInfo converterInfo = new ConverterInfo(); + converterInfo.Name = name; + converterInfo.Type = type; + + this.AddConverter(converterInfo); + } + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/PatternStringConverters/AppDomainPatternConverter.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/PatternStringConverters/AppDomainPatternConverter.cs index 62174263be0..0e47d5667c8 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/PatternStringConverters/AppDomainPatternConverter.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/PatternStringConverters/AppDomainPatternConverter.cs @@ -1,55 +1,55 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.Util.PatternStringConverters -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; - using System.IO; - using System.Text; +using System; +using System.Text; +using System.IO; - using log4net.Util; +using log4net.Util; - /// - /// Write the name of the current AppDomain to the output. - /// - /// - /// - /// Write the name of the current AppDomain to the output writer. - /// - /// - /// Nicko Cadell. - internal sealed class AppDomainPatternConverter : PatternConverter - { - /// - /// Write the name of the current AppDomain to the output. - /// - /// the writer to write to. - /// null, state is not set. - /// - /// - /// Writes name of the current AppDomain to the output . - /// - /// - protected override void Convert(TextWriter writer, object state) - { - writer.Write(SystemInfo.ApplicationFriendlyName); - } - } -} +namespace log4net.Util.PatternStringConverters +{ + /// + /// Write the name of the current AppDomain to the output + /// + /// + /// + /// Write the name of the current AppDomain to the output writer + /// + /// + /// Nicko Cadell + internal sealed class AppDomainPatternConverter : PatternConverter + { + /// + /// Write the name of the current AppDomain to the output + /// + /// the writer to write to + /// null, state is not set + /// + /// + /// Writes name of the current AppDomain to the output . + /// + /// + protected override void Convert(TextWriter writer, object state) + { + writer.Write(SystemInfo.ApplicationFriendlyName); + } + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/PatternStringConverters/AppSettingPatternConverter.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/PatternStringConverters/AppSettingPatternConverter.cs index cd5fc21370c..bbe400ecd7d 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/PatternStringConverters/AppSettingPatternConverter.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/PatternStringConverters/AppSettingPatternConverter.cs @@ -1,116 +1,109 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -// .NET Compact Framework 1.0 has no support for application .config files -#if !NETCF - -using System; -using System.Collections; -using System.IO; -using System.Text; +// .NET Compact Framework 1.0 has no support for application .config files +#if !NETCF && (NET_2_0 || NETSTANDARD2_0) -using log4net.Core; -using log4net.Repository; -using log4net.Util; - -namespace log4net.Util.PatternStringConverters -{ - /// - /// AppSetting pattern converter. - /// - /// - /// - /// This pattern converter reads appSettings from the application configuration file. - /// - /// - /// If the is specified then that will be used to - /// lookup a single appSettings value. If no is specified - /// then all appSettings will be dumped as a list of key value pairs. - /// - /// - /// A typical use is to specify a base directory for log files, e.g. - /// - /// - /// - /// - /// ... - /// - /// - /// ]]> - /// - /// - /// - internal sealed class AppSettingPatternConverter : PatternConverter - { - private static IDictionary AppSettingsDictionary - { - get - { - if (_appSettingsHashTable == null) - { - Hashtable h = new Hashtable(); - foreach (string key in System.Configuration.ConfigurationManager.AppSettings) - { - h.Add(key, System.Configuration.ConfigurationManager.AppSettings[key]); - } +using System.IO; +using System.Collections; +using System.Configuration; - _appSettingsHashTable = h; - } +namespace log4net.Util.PatternStringConverters +{ + /// + /// AppSetting pattern converter + /// + /// + /// + /// This pattern converter reads appSettings from the application configuration file. + /// + /// + /// If the is specified then that will be used to + /// lookup a single appSettings value. If no is specified + /// then all appSettings will be dumped as a list of key value pairs. + /// + /// + /// A typical use is to specify a base directory for log files, e.g. + /// + /// + /// + /// + /// ... + /// + /// + /// ]]> + /// + /// + /// + internal sealed class AppSettingPatternConverter : PatternConverter + { + private static IDictionary AppSettingsDictionary + { + get + { + if (_appSettingsHashTable == null) + { + Hashtable h = new Hashtable(); + foreach(string key in ConfigurationManager.AppSettings) + { + h.Add(key, ConfigurationManager.AppSettings[key]); + } + _appSettingsHashTable = h; + } + return _appSettingsHashTable; + } - return _appSettingsHashTable; - } - } + } + private static Hashtable _appSettingsHashTable; - private static Hashtable _appSettingsHashTable; - - /// - /// Write the property value to the output. - /// - /// that will receive the formatted result. - /// null, state is not set. - /// - /// - /// Writes out the value of a named property. The property name - /// should be set in the - /// property. - /// - /// - /// If the is set to null - /// then all the properties are written as key value pairs. - /// - /// - protected override void Convert(TextWriter writer, object state) - { - if (this.Option != null) - { - // Write the value for the specified key - WriteObject(writer, null, System.Configuration.ConfigurationManager.AppSettings[this.Option]); - } - else - { - // Write all the key value pairs - WriteDictionary(writer, null, AppSettingsDictionary); - } - } - } -} -#endif + /// + /// Write the property value to the output + /// + /// that will receive the formatted result. + /// null, state is not set + /// + /// + /// Writes out the value of a named property. The property name + /// should be set in the + /// property. + /// + /// + /// If the is set to null + /// then all the properties are written as key value pairs. + /// + /// + protected override void Convert(TextWriter writer, object state) + { + + if (this.Option != null) + { + // Write the value for the specified key + WriteObject(writer, null, ConfigurationManager.AppSettings[this.Option]); + } + else + { + // Write all the key value pairs + WriteDictionary(writer, null, AppSettingsDictionary); + } + } + } +} +#endif // !NETCF && NET_2_0 diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/PatternStringConverters/DatePatternConverter.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/PatternStringConverters/DatePatternConverter.cs index d19fe902409..b9774106233 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/PatternStringConverters/DatePatternConverter.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/PatternStringConverters/DatePatternConverter.cs @@ -1,182 +1,182 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.Util.PatternStringConverters -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; - using System.IO; +using System; +using System.IO; - using log4net.Core; - using log4net.DateFormatter; +using log4net.DateFormatter; +using log4net.Core; - /// - /// Write the current date to the output. - /// - /// - /// - /// Date pattern converter, uses a to format - /// the current date and time to the writer as a string. - /// - /// - /// The value of the determines - /// the formatting of the date. The following values are allowed: - /// - /// - /// Option value - /// Output - /// - /// - /// ISO8601 - /// - /// Uses the formatter. - /// Formats using the "yyyy-MM-dd HH:mm:ss,fff" pattern. - /// - /// - /// - /// DATE - /// - /// Uses the formatter. - /// Formats using the "dd MMM yyyy HH:mm:ss,fff" for example, "06 Nov 1994 15:49:37,459". - /// - /// - /// - /// ABSOLUTE - /// - /// Uses the formatter. - /// Formats using the "HH:mm:ss,fff" for example, "15:49:37,459". - /// - /// - /// - /// other - /// - /// Any other pattern string uses the formatter. - /// This formatter passes the pattern string to the - /// method. - /// For details on valid patterns see - /// DateTimeFormatInfo Class. - /// - /// - /// - /// - /// - /// The date and time is in the local time zone and is rendered in that zone. - /// To output the time in Universal time see . - /// - /// - /// Nicko Cadell. - internal class DatePatternConverter : PatternConverter, IOptionHandler - { - /// - /// The used to render the date to a string. - /// - /// - /// - /// The used to render the date to a string. - /// - /// +namespace log4net.Util.PatternStringConverters +{ + /// + /// Write the current date to the output + /// + /// + /// + /// Date pattern converter, uses a to format + /// the current date and time to the writer as a string. + /// + /// + /// The value of the determines + /// the formatting of the date. The following values are allowed: + /// + /// + /// Option value + /// Output + /// + /// + /// ISO8601 + /// + /// Uses the formatter. + /// Formats using the "yyyy-MM-dd HH:mm:ss,fff" pattern. + /// + /// + /// + /// DATE + /// + /// Uses the formatter. + /// Formats using the "dd MMM yyyy HH:mm:ss,fff" for example, "06 Nov 1994 15:49:37,459". + /// + /// + /// + /// ABSOLUTE + /// + /// Uses the formatter. + /// Formats using the "HH:mm:ss,fff" for example, "15:49:37,459". + /// + /// + /// + /// other + /// + /// Any other pattern string uses the formatter. + /// This formatter passes the pattern string to the + /// method. + /// For details on valid patterns see + /// DateTimeFormatInfo Class. + /// + /// + /// + /// + /// + /// The date and time is in the local time zone and is rendered in that zone. + /// To output the time in Universal time see . + /// + /// + /// Nicko Cadell + internal class DatePatternConverter : PatternConverter, IOptionHandler + { + /// + /// The used to render the date to a string + /// + /// + /// + /// The used to render the date to a string + /// + /// protected IDateFormatter m_dateFormatter; - /// - /// Initialize the converter options. - /// - /// - /// - /// This is part of the delayed object - /// activation scheme. The method must - /// be called on this object after the configuration properties have - /// been set. Until is called this - /// object is in an undefined state and must not be used. - /// - /// - /// If any of the configuration properties are modified then - /// must be called again. - /// - /// - public void ActivateOptions() - { - string dateFormatStr = this.Option; - - if (dateFormatStr == null) - { - dateFormatStr = AbsoluteTimeDateFormatter.Iso8601TimeDateFormat; - } - - if (SystemInfo.EqualsIgnoringCase(dateFormatStr, AbsoluteTimeDateFormatter.Iso8601TimeDateFormat)) - { - this.m_dateFormatter = new Iso8601DateFormatter(); - } - else if (SystemInfo.EqualsIgnoringCase(dateFormatStr, AbsoluteTimeDateFormatter.AbsoluteTimeDateFormat)) - { - this.m_dateFormatter = new AbsoluteTimeDateFormatter(); - } - else if (SystemInfo.EqualsIgnoringCase(dateFormatStr, AbsoluteTimeDateFormatter.DateAndTimeDateFormat)) - { - this.m_dateFormatter = new DateTimeDateFormatter(); - } - else - { - try - { - this.m_dateFormatter = new SimpleDateFormatter(dateFormatStr); - } - catch (Exception e) - { - LogLog.Error(declaringType, "Could not instantiate SimpleDateFormatter with [" + dateFormatStr + "]", e); - this.m_dateFormatter = new Iso8601DateFormatter(); - } - } + /// + /// Initialize the converter options + /// + /// + /// + /// This is part of the delayed object + /// activation scheme. The method must + /// be called on this object after the configuration properties have + /// been set. Until is called this + /// object is in an undefined state and must not be used. + /// + /// + /// If any of the configuration properties are modified then + /// must be called again. + /// + /// + public void ActivateOptions() + { + string dateFormatStr = this.Option; + + if (dateFormatStr == null) + { + dateFormatStr = AbsoluteTimeDateFormatter.Iso8601TimeDateFormat; + } + + if (SystemInfo.EqualsIgnoringCase(dateFormatStr, AbsoluteTimeDateFormatter.Iso8601TimeDateFormat)) + { + this.m_dateFormatter = new Iso8601DateFormatter(); + } + else if (SystemInfo.EqualsIgnoringCase(dateFormatStr, AbsoluteTimeDateFormatter.AbsoluteTimeDateFormat)) + { + this.m_dateFormatter = new AbsoluteTimeDateFormatter(); + } + else if (SystemInfo.EqualsIgnoringCase(dateFormatStr, AbsoluteTimeDateFormatter.DateAndTimeDateFormat)) + { + this.m_dateFormatter = new DateTimeDateFormatter(); + } + else + { + try + { + this.m_dateFormatter = new SimpleDateFormatter(dateFormatStr); + } + catch (Exception e) + { + LogLog.Error(declaringType, "Could not instantiate SimpleDateFormatter with ["+dateFormatStr+"]", e); + this.m_dateFormatter = new Iso8601DateFormatter(); + } + } } - /// - /// Write the current date to the output. - /// - /// that will receive the formatted result. - /// null, state is not set. - /// - /// - /// Pass the current date and time to the - /// for it to render it to the writer. - /// - /// - /// The date and time passed is in the local time zone. - /// - /// - protected override void Convert(TextWriter writer, object state) - { - try - { - this.m_dateFormatter.FormatDate(DateTime.Now, writer); - } - catch (Exception ex) - { - LogLog.Error(declaringType, "Error occurred while converting date.", ex); - } + /// + /// Write the current date to the output + /// + /// that will receive the formatted result. + /// null, state is not set + /// + /// + /// Pass the current date and time to the + /// for it to render it to the writer. + /// + /// + /// The date and time passed is in the local time zone. + /// + /// + protected override void Convert(TextWriter writer, object state) + { + try + { + this.m_dateFormatter.FormatDate(DateTime.Now, writer); + } + catch (Exception ex) + { + LogLog.Error(declaringType, "Error occurred while converting date.", ex); + } } - /// - /// The fully qualified type of the DatePatternConverter class. - /// - /// - /// Used by the internal logger to record the Type of the - /// log message. - /// + /// + /// The fully qualified type of the DatePatternConverter class. + /// + /// + /// Used by the internal logger to record the Type of the + /// log message. + /// private static readonly Type declaringType = typeof(DatePatternConverter); - } -} + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/PatternStringConverters/EnvironmentFolderPathPatternConverter.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/PatternStringConverters/EnvironmentFolderPathPatternConverter.cs index 9c503909149..54e7108d3f1 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/PatternStringConverters/EnvironmentFolderPathPatternConverter.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/PatternStringConverters/EnvironmentFolderPathPatternConverter.cs @@ -1,95 +1,95 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#if !NETCF - -using System; -using System.IO; - -namespace log4net.Util.PatternStringConverters -{ - /// - /// Write an folder path to the output. - /// - /// - /// - /// Write an special path environment folder path to the output writer. - /// The value of the determines - /// the name of the variable to output. - /// should be a value in the enumeration. - /// - /// - /// Ron Grabowski. - internal sealed class EnvironmentFolderPathPatternConverter : PatternConverter - { - /// - /// Write an special path environment folder path to the output. - /// - /// the writer to write to. - /// null, state is not set. - /// - /// - /// Writes the special path environment folder path to the output . - /// The name of the special path environment folder path to output must be set - /// using the - /// property. - /// - /// - protected override void Convert(TextWriter writer, object state) - { - try - { - if (this.Option != null && this.Option.Length > 0) - { - Environment.SpecialFolder specialFolder = - (Environment.SpecialFolder)Enum.Parse(typeof(Environment.SpecialFolder), this.Option, true); - - string envFolderPathValue = Environment.GetFolderPath(specialFolder); - if (envFolderPathValue != null && envFolderPathValue.Length > 0) - { - writer.Write(envFolderPathValue); - } - } - } - catch (System.Security.SecurityException secEx) - { - // This security exception will occur if the caller does not have - // unrestricted environment permission. If this occurs the expansion - // will be skipped with the following warning message. - LogLog.Debug(declaringType, "Security exception while trying to expand environment variables. Error Ignored. No Expansion.", secEx); - } - catch (Exception ex) - { - LogLog.Error(declaringType, "Error occurred while converting environment variable.", ex); - } +#if !NETCF && (NET_2_0 || NETSTANDARD2_0) + +using System; +using System.IO; + +namespace log4net.Util.PatternStringConverters +{ + /// + /// Write an folder path to the output + /// + /// + /// + /// Write an special path environment folder path to the output writer. + /// The value of the determines + /// the name of the variable to output. + /// should be a value in the enumeration. + /// + /// + /// Ron Grabowski + internal sealed class EnvironmentFolderPathPatternConverter : PatternConverter + { + /// + /// Write an special path environment folder path to the output + /// + /// the writer to write to + /// null, state is not set + /// + /// + /// Writes the special path environment folder path to the output . + /// The name of the special path environment folder path to output must be set + /// using the + /// property. + /// + /// + protected override void Convert(TextWriter writer, object state) + { + try + { + if (this.Option != null && this.Option.Length > 0) + { + Environment.SpecialFolder specialFolder = + (Environment.SpecialFolder)Enum.Parse(typeof(Environment.SpecialFolder), this.Option, true); + + string envFolderPathValue = Environment.GetFolderPath(specialFolder); + if (envFolderPathValue != null && envFolderPathValue.Length > 0) + { + writer.Write(envFolderPathValue); + } + } + } + catch (System.Security.SecurityException secEx) + { + // This security exception will occur if the caller does not have + // unrestricted environment permission. If this occurs the expansion + // will be skipped with the following warning message. + LogLog.Debug(declaringType, "Security exception while trying to expand environment variables. Error Ignored. No Expansion.", secEx); + } + catch (Exception ex) + { + LogLog.Error(declaringType, "Error occurred while converting environment variable.", ex); + } } - /// - /// The fully qualified type of the EnvironmentFolderPathPatternConverter class. - /// - /// - /// Used by the internal logger to record the Type of the - /// log message. - /// + /// + /// The fully qualified type of the EnvironmentFolderPathPatternConverter class. + /// + /// + /// Used by the internal logger to record the Type of the + /// log message. + /// private static readonly Type declaringType = typeof(EnvironmentFolderPathPatternConverter); - } -} - -#endif // !NETCF + } +} + +#endif // !NETCF && NET_2_0 diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/PatternStringConverters/EnvironmentPatternConverter.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/PatternStringConverters/EnvironmentPatternConverter.cs index 9e9304cd4bc..1b2bedf5712 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/PatternStringConverters/EnvironmentPatternConverter.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/PatternStringConverters/EnvironmentPatternConverter.cs @@ -1,114 +1,108 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -// .NET Compact Framework 1.0 has no support for Environment.GetEnvironmentVariable() -#if !NETCF - -using System; -using System.IO; -using System.Text; +// .NET Compact Framework 1.0 has no support for Environment.GetEnvironmentVariable() +#if !NETCF -using log4net.Core; -using log4net.DateFormatter; -using log4net.Util; - -namespace log4net.Util.PatternStringConverters -{ - /// - /// Write an environment variable to the output. - /// - /// - /// - /// Write an environment variable to the output writer. - /// The value of the determines - /// the name of the variable to output. - /// - /// - /// Nicko Cadell. - internal sealed class EnvironmentPatternConverter : PatternConverter - { - /// - /// Write an environment variable to the output. - /// - /// the writer to write to. - /// null, state is not set. - /// - /// - /// Writes the environment variable to the output . - /// The name of the environment variable to output must be set - /// using the - /// property. - /// - /// - protected override void Convert(TextWriter writer, object state) - { - try - { - if (this.Option != null && this.Option.Length > 0) - { - // Lookup the environment variable - string envValue = Environment.GetEnvironmentVariable(this.Option); - -#if NET_2_0 - // If we didn't see it for the process, try a user level variable. - if (envValue == null) - { - envValue = Environment.GetEnvironmentVariable(this.Option, EnvironmentVariableTarget.User); - } - - // If we still didn't find it, try a system level one. - if (envValue == null) - { - envValue = Environment.GetEnvironmentVariable(this.Option, EnvironmentVariableTarget.Machine); - } -#endif - - if (envValue != null && envValue.Length > 0) - { - writer.Write(envValue); - } - } - } - catch (System.Security.SecurityException secEx) - { - // This security exception will occur if the caller does not have - // unrestricted environment permission. If this occurs the expansion - // will be skipped with the following warning message. - LogLog.Debug(declaringType, "Security exception while trying to expand environment variables. Error Ignored. No Expansion.", secEx); - } - catch (Exception ex) - { - LogLog.Error(declaringType, "Error occurred while converting environment variable.", ex); - } +using System; +using System.IO; + +namespace log4net.Util.PatternStringConverters +{ + /// + /// Write an environment variable to the output + /// + /// + /// + /// Write an environment variable to the output writer. + /// The value of the determines + /// the name of the variable to output. + /// + /// + /// Nicko Cadell + internal sealed class EnvironmentPatternConverter : PatternConverter + { + /// + /// Write an environment variable to the output + /// + /// the writer to write to + /// null, state is not set + /// + /// + /// Writes the environment variable to the output . + /// The name of the environment variable to output must be set + /// using the + /// property. + /// + /// + protected override void Convert(TextWriter writer, object state) + { + try + { + if (this.Option != null && this.Option.Length > 0) + { + // Lookup the environment variable + string envValue = Environment.GetEnvironmentVariable(this.Option); + +#if NET_2_0 || NETSTANDARD2_0 + // If we didn't see it for the process, try a user level variable. + if (envValue == null) + { + envValue = Environment.GetEnvironmentVariable(this.Option, EnvironmentVariableTarget.User); + } + + // If we still didn't find it, try a system level one. + if (envValue == null) + { + envValue = Environment.GetEnvironmentVariable(this.Option, EnvironmentVariableTarget.Machine); + } +#endif + + if (envValue != null && envValue.Length > 0) + { + writer.Write(envValue); + } + } + } + catch(System.Security.SecurityException secEx) + { + // This security exception will occur if the caller does not have + // unrestricted environment permission. If this occurs the expansion + // will be skipped with the following warning message. + LogLog.Debug(declaringType, "Security exception while trying to expand environment variables. Error Ignored. No Expansion.", secEx); + } + catch (Exception ex) + { + LogLog.Error(declaringType, "Error occurred while converting environment variable.", ex); + } } - /// - /// The fully qualified type of the EnvironmentPatternConverter class. - /// - /// - /// Used by the internal logger to record the Type of the - /// log message. - /// + /// + /// The fully qualified type of the EnvironmentPatternConverter class. + /// + /// + /// Used by the internal logger to record the Type of the + /// log message. + /// private static readonly Type declaringType = typeof(EnvironmentPatternConverter); - } -} - -#endif // !NETCF + } +} + +#endif // !NETCF diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/PatternStringConverters/IdentityPatternConverter.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/PatternStringConverters/IdentityPatternConverter.cs index 5ca00f216de..995609725a6 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/PatternStringConverters/IdentityPatternConverter.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/PatternStringConverters/IdentityPatternConverter.cs @@ -1,85 +1,85 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.Util.PatternStringConverters -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; - using System.IO; - using System.Text; +using System; +using System.Text; +using System.IO; - using log4net.Util; +using log4net.Util; - /// - /// Write the current thread identity to the output. - /// - /// - /// - /// Write the current thread identity to the output writer. - /// - /// - /// Nicko Cadell. - internal sealed class IdentityPatternConverter : PatternConverter - { - /// - /// Write the current thread identity to the output. - /// - /// the writer to write to. - /// null, state is not set. - /// - /// - /// Writes the current thread identity to the output . - /// - /// - protected override void Convert(TextWriter writer, object state) - { -#if NETCF || SSCLI || NETSTANDARD1_3 - // On compact framework there's no notion of current thread principals - writer.Write( SystemInfo.NotAvailableText ); -#else - try - { - if (System.Threading.Thread.CurrentPrincipal != null && - System.Threading.Thread.CurrentPrincipal.Identity != null && - System.Threading.Thread.CurrentPrincipal.Identity.Name != null) - { - writer.Write(System.Threading.Thread.CurrentPrincipal.Identity.Name); - } - } - catch (System.Security.SecurityException) - { - // This security exception will occur if the caller does not have - // some undefined set of SecurityPermission flags. - LogLog.Debug(declaringType, "Security exception while trying to get current thread principal. Error Ignored."); - - writer.Write(SystemInfo.NotAvailableText); - } -#endif +namespace log4net.Util.PatternStringConverters +{ + /// + /// Write the current thread identity to the output + /// + /// + /// + /// Write the current thread identity to the output writer + /// + /// + /// Nicko Cadell + internal sealed class IdentityPatternConverter : PatternConverter + { + /// + /// Write the current thread identity to the output + /// + /// the writer to write to + /// null, state is not set + /// + /// + /// Writes the current thread identity to the output . + /// + /// + protected override void Convert(TextWriter writer, object state) + { +#if (NETCF || SSCLI || NETSTANDARD1_3) + // On compact framework there's no notion of current thread principals + writer.Write( SystemInfo.NotAvailableText ); +#else + try + { + if (System.Threading.Thread.CurrentPrincipal != null && + System.Threading.Thread.CurrentPrincipal.Identity != null && + System.Threading.Thread.CurrentPrincipal.Identity.Name != null) + { + writer.Write(System.Threading.Thread.CurrentPrincipal.Identity.Name); + } + } + catch(System.Security.SecurityException) + { + // This security exception will occur if the caller does not have + // some undefined set of SecurityPermission flags. + LogLog.Debug(declaringType, "Security exception while trying to get current thread principal. Error Ignored."); + + writer.Write(SystemInfo.NotAvailableText); + } +#endif } - /// - /// The fully qualified type of the IdentityPatternConverter class. - /// - /// - /// Used by the internal logger to record the Type of the - /// log message. - /// + /// + /// The fully qualified type of the IdentityPatternConverter class. + /// + /// + /// Used by the internal logger to record the Type of the + /// log message. + /// private static readonly Type declaringType = typeof(IdentityPatternConverter); - } -} + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/PatternStringConverters/LiteralPatternConverter.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/PatternStringConverters/LiteralPatternConverter.cs index de417e99b5c..d9e5dad9dfd 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/PatternStringConverters/LiteralPatternConverter.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/PatternStringConverters/LiteralPatternConverter.cs @@ -1,108 +1,108 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.Util.PatternStringConverters -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; - using System.IO; - using System.Text; +using System; +using System.Text; +using System.IO; - using log4net.Util; +using log4net.Util; - /// - /// Pattern converter for literal string instances in the pattern. - /// - /// - /// - /// Writes the literal string value specified in the - /// property to - /// the output. - /// - /// - /// Nicko Cadell. - internal class LiteralPatternConverter : PatternConverter - { - /// - /// Set the next converter in the chain. - /// - /// The next pattern converter in the chain. - /// The next pattern converter. - /// - /// - /// Special case the building of the pattern converter chain - /// for instances. Two adjacent - /// literals in the pattern can be represented by a single combined - /// pattern converter. This implementation detects when a - /// is added to the chain - /// after this converter and combines its value with this converter's - /// literal value. - /// - /// - public override PatternConverter SetNext(PatternConverter pc) - { - LiteralPatternConverter literalPc = pc as LiteralPatternConverter; - if (literalPc != null) - { - // Combine the two adjacent literals together - this.Option = this.Option + literalPc.Option; - - // We are the next converter now - return this; - } - - return base.SetNext(pc); - } - - /// - /// Write the literal to the output. - /// - /// the writer to write to. - /// null, not set. - /// - /// - /// Override the formatting behavior to ignore the FormattingInfo - /// because we have a literal instead. - /// - /// - /// Writes the value of - /// to the output . - /// - /// - public override void Format(TextWriter writer, object state) - { - writer.Write(this.Option); - } - - /// - /// Convert this pattern into the rendered message. - /// - /// that will receive the formatted result. - /// null, not set. - /// - /// - /// This method is not used. - /// - /// - protected override void Convert(TextWriter writer, object state) - { - throw new InvalidOperationException("Should never get here because of the overridden Format method"); - } - } -} +namespace log4net.Util.PatternStringConverters +{ + /// + /// Pattern converter for literal string instances in the pattern + /// + /// + /// + /// Writes the literal string value specified in the + /// property to + /// the output. + /// + /// + /// Nicko Cadell + internal class LiteralPatternConverter : PatternConverter + { + /// + /// Set the next converter in the chain + /// + /// The next pattern converter in the chain + /// The next pattern converter + /// + /// + /// Special case the building of the pattern converter chain + /// for instances. Two adjacent + /// literals in the pattern can be represented by a single combined + /// pattern converter. This implementation detects when a + /// is added to the chain + /// after this converter and combines its value with this converter's + /// literal value. + /// + /// + public override PatternConverter SetNext(PatternConverter pc) + { + LiteralPatternConverter literalPc = pc as LiteralPatternConverter; + if (literalPc != null) + { + // Combine the two adjacent literals together + this.Option = this.Option + literalPc.Option; + + // We are the next converter now + return this; + } + + return base.SetNext(pc); + } + + /// + /// Write the literal to the output + /// + /// the writer to write to + /// null, not set + /// + /// + /// Override the formatting behavior to ignore the FormattingInfo + /// because we have a literal instead. + /// + /// + /// Writes the value of + /// to the output . + /// + /// + public override void Format(TextWriter writer, object state) + { + writer.Write(this.Option); + } + + /// + /// Convert this pattern into the rendered message + /// + /// that will receive the formatted result. + /// null, not set + /// + /// + /// This method is not used. + /// + /// + protected override void Convert(TextWriter writer, object state) + { + throw new InvalidOperationException("Should never get here because of the overridden Format method"); + } + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/PatternStringConverters/NewLinePatternConverter.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/PatternStringConverters/NewLinePatternConverter.cs index e5754fed1ce..7f87072d56c 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/PatternStringConverters/NewLinePatternConverter.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/PatternStringConverters/NewLinePatternConverter.cs @@ -1,83 +1,83 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.Util.PatternStringConverters -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using log4net.Core; +using log4net.Core; - /// - /// Writes a newline to the output. - /// - /// - /// - /// Writes the system dependent line terminator to the output. - /// This behavior can be overridden by setting the : - /// - /// - /// - /// Option Value - /// Output - /// - /// - /// DOS - /// DOS or Windows line terminator "\r\n" - /// - /// - /// UNIX - /// UNIX line terminator "\n" - /// - /// - /// - /// Nicko Cadell. - internal sealed class NewLinePatternConverter : LiteralPatternConverter, IOptionHandler +namespace log4net.Util.PatternStringConverters +{ + /// + /// Writes a newline to the output + /// + /// + /// + /// Writes the system dependent line terminator to the output. + /// This behavior can be overridden by setting the : + /// + /// + /// + /// Option Value + /// Output + /// + /// + /// DOS + /// DOS or Windows line terminator "\r\n" + /// + /// + /// UNIX + /// UNIX line terminator "\n" + /// + /// + /// + /// Nicko Cadell + internal sealed class NewLinePatternConverter : LiteralPatternConverter, IOptionHandler { - /// - /// Initialize the converter. - /// - /// - /// - /// This is part of the delayed object - /// activation scheme. The method must - /// be called on this object after the configuration properties have - /// been set. Until is called this - /// object is in an undefined state and must not be used. - /// - /// - /// If any of the configuration properties are modified then - /// must be called again. - /// - /// - public void ActivateOptions() - { - if (SystemInfo.EqualsIgnoringCase(this.Option, "DOS")) - { - this.Option = "\r\n"; - } - else if (SystemInfo.EqualsIgnoringCase(this.Option, "UNIX")) - { - this.Option = "\n"; - } - else - { - this.Option = SystemInfo.NewLine; - } + /// + /// Initialize the converter + /// + /// + /// + /// This is part of the delayed object + /// activation scheme. The method must + /// be called on this object after the configuration properties have + /// been set. Until is called this + /// object is in an undefined state and must not be used. + /// + /// + /// If any of the configuration properties are modified then + /// must be called again. + /// + /// + public void ActivateOptions() + { + if (SystemInfo.EqualsIgnoringCase(this.Option, "DOS")) + { + this.Option = "\r\n"; + } + else if (SystemInfo.EqualsIgnoringCase(this.Option, "UNIX")) + { + this.Option = "\n"; + } + else + { + this.Option = SystemInfo.NewLine; + } } - } -} + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/PatternStringConverters/ProcessIdPatternConverter.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/PatternStringConverters/ProcessIdPatternConverter.cs index ff48fbb6cf2..61397b69787 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/PatternStringConverters/ProcessIdPatternConverter.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/PatternStringConverters/ProcessIdPatternConverter.cs @@ -1,83 +1,80 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.Util.PatternStringConverters -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; - using System.IO; - using System.Text; +using System; +using System.IO; - using log4net.Util; - - /// - /// Write the current process ID to the output. - /// - /// - /// - /// Write the current process ID to the output writer. - /// - /// - /// Nicko Cadell. - internal sealed class ProcessIdPatternConverter : PatternConverter +namespace log4net.Util.PatternStringConverters +{ + /// + /// Write the current process ID to the output + /// + /// + /// + /// Write the current process ID to the output writer + /// + /// + /// Nicko Cadell + internal sealed class ProcessIdPatternConverter : PatternConverter { - /// - /// Write the current process ID to the output. - /// - /// the writer to write to. - /// null, state is not set. - /// - /// - /// Write the current process ID to the output . - /// - /// -#if NET_4_0 || MONO_4_0 || NETSTANDARD1_3 - [System.Security.SecuritySafeCritical] -#endif - protected override void Convert(TextWriter writer, object state) - { -#if NETCF || SSCLI - // On compact framework there is no System.Diagnostics.Process class - writer.Write( SystemInfo.NotAvailableText ); -#else - try - { - writer.Write(System.Diagnostics.Process.GetCurrentProcess().Id); - } - catch (System.Security.SecurityException) - { - // This security exception will occur if the caller does not have - // some undefined set of SecurityPermission flags. - LogLog.Debug(declaringType, "Security exception while trying to get current process id. Error Ignored."); - - writer.Write(SystemInfo.NotAvailableText); - } -#endif + /// + /// Write the current process ID to the output + /// + /// the writer to write to + /// null, state is not set + /// + /// + /// Write the current process ID to the output . + /// + /// +#if NET_4_0 || MONO_4_0 || NETSTANDARD + [System.Security.SecuritySafeCritical] +#endif + protected override void Convert(TextWriter writer, object state) + { +#if (NETCF || SSCLI) + // On compact framework there is no System.Diagnostics.Process class + writer.Write( SystemInfo.NotAvailableText ); +#else + try + { + writer.Write(System.Diagnostics.Process.GetCurrentProcess().Id); + } + catch(System.Security.SecurityException) + { + // This security exception will occur if the caller does not have + // some undefined set of SecurityPermission flags. + LogLog.Debug(declaringType, "Security exception while trying to get current process id. Error Ignored."); + + writer.Write(SystemInfo.NotAvailableText); + } +#endif } - /// - /// The fully qualified type of the ProcessIdPatternConverter class. - /// - /// - /// Used by the internal logger to record the Type of the - /// log message. - /// + /// + /// The fully qualified type of the ProcessIdPatternConverter class. + /// + /// + /// Used by the internal logger to record the Type of the + /// log message. + /// private static readonly Type declaringType = typeof(ProcessIdPatternConverter); - } -} + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/PatternStringConverters/PropertyPatternConverter.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/PatternStringConverters/PropertyPatternConverter.cs index 2e11e983a2d..f2d88d209fc 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/PatternStringConverters/PropertyPatternConverter.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/PatternStringConverters/PropertyPatternConverter.cs @@ -1,100 +1,93 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.Util.PatternStringConverters -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; - using System.Collections; - using System.IO; - using System.Text; +using System.IO; - using log4net.Core; - using log4net.Repository; - using log4net.Util; +namespace log4net.Util.PatternStringConverters +{ + /// + /// Property pattern converter + /// + /// + /// + /// This pattern converter reads the thread and global properties. + /// The thread properties take priority over global properties. + /// See for details of the + /// thread properties. See for + /// details of the global properties. + /// + /// + /// If the is specified then that will be used to + /// lookup a single property. If no is specified + /// then all properties will be dumped as a list of key value pairs. + /// + /// + /// Nicko Cadell + internal sealed class PropertyPatternConverter : PatternConverter + { + /// + /// Write the property value to the output + /// + /// that will receive the formatted result. + /// null, state is not set + /// + /// + /// Writes out the value of a named property. The property name + /// should be set in the + /// property. + /// + /// + /// If the is set to null + /// then all the properties are written as key value pairs. + /// + /// + protected override void Convert(TextWriter writer, object state) + { + CompositeProperties compositeProperties = new CompositeProperties(); - /// - /// Property pattern converter. - /// - /// - /// - /// This pattern converter reads the thread and global properties. - /// The thread properties take priority over global properties. - /// See for details of the - /// thread properties. See for - /// details of the global properties. - /// - /// - /// If the is specified then that will be used to - /// lookup a single property. If no is specified - /// then all properties will be dumped as a list of key value pairs. - /// - /// - /// Nicko Cadell. - internal sealed class PropertyPatternConverter : PatternConverter - { - /// - /// Write the property value to the output. - /// - /// that will receive the formatted result. - /// null, state is not set. - /// - /// - /// Writes out the value of a named property. The property name - /// should be set in the - /// property. - /// - /// - /// If the is set to null - /// then all the properties are written as key value pairs. - /// - /// - protected override void Convert(TextWriter writer, object state) - { - CompositeProperties compositeProperties = new CompositeProperties(); - -#if !(NETCF || NETSTANDARD1_3) - PropertiesDictionary logicalThreadProperties = LogicalThreadContext.Properties.GetProperties(false); - if (logicalThreadProperties != null) - { - compositeProperties.Add(logicalThreadProperties); - } -#endif - PropertiesDictionary threadProperties = ThreadContext.Properties.GetProperties(false); - if (threadProperties != null) - { - compositeProperties.Add(threadProperties); - } - - // TODO: Add Repository Properties - compositeProperties.Add(GlobalContext.Properties.GetReadOnlyProperties()); - - if (this.Option != null) - { - // Write the value for the specified key - WriteObject(writer, null, compositeProperties[this.Option]); - } - else - { - // Write all the key value pairs - WriteDictionary(writer, null, compositeProperties.Flatten()); - } - } - } -} +#if !NETCF + PropertiesDictionary logicalThreadProperties = LogicalThreadContext.Properties.GetProperties(false); + if (logicalThreadProperties != null) + { + compositeProperties.Add(logicalThreadProperties); + } +#endif + PropertiesDictionary threadProperties = ThreadContext.Properties.GetProperties(false); + if (threadProperties != null) + { + compositeProperties.Add(threadProperties); + } + + // TODO: Add Repository Properties + compositeProperties.Add(GlobalContext.Properties.GetReadOnlyProperties()); + + if (this.Option != null) + { + // Write the value for the specified key + WriteObject(writer, null, compositeProperties[this.Option]); + } + else + { + // Write all the key value pairs + WriteDictionary(writer, null, compositeProperties.Flatten()); + } + } + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/PatternStringConverters/RandomStringPatternConverter.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/PatternStringConverters/RandomStringPatternConverter.cs index 1cc9cbe5081..bc95fbda6a3 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/PatternStringConverters/RandomStringPatternConverter.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/PatternStringConverters/RandomStringPatternConverter.cs @@ -1,149 +1,149 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.Util.PatternStringConverters -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; - using System.IO; - using System.Text; +using System; +using System.Text; +using System.IO; - using log4net.Core; - using log4net.DateFormatter; - using log4net.Util; +using log4net.Util; +using log4net.DateFormatter; +using log4net.Core; - /// - /// A Pattern converter that generates a string of random characters. - /// - /// - /// - /// The converter generates a string of random characters. By default - /// the string is length 4. This can be changed by setting the - /// to the string value of the length required. - /// - /// - /// The random characters in the string are limited to uppercase letters - /// and numbers only. - /// - /// - /// The random number generator used by this class is not cryptographically secure. - /// - /// - /// Nicko Cadell. - internal sealed class RandomStringPatternConverter : PatternConverter, IOptionHandler - { - /// - /// Shared random number generator. - /// - private static readonly Random s_random = new Random(); - - /// - /// Length of random string to generate. Default length 4. - /// +namespace log4net.Util.PatternStringConverters +{ + /// + /// A Pattern converter that generates a string of random characters + /// + /// + /// + /// The converter generates a string of random characters. By default + /// the string is length 4. This can be changed by setting the + /// to the string value of the length required. + /// + /// + /// The random characters in the string are limited to uppercase letters + /// and numbers only. + /// + /// + /// The random number generator used by this class is not cryptographically secure. + /// + /// + /// Nicko Cadell + internal sealed class RandomStringPatternConverter : PatternConverter, IOptionHandler + { + /// + /// Shared random number generator + /// + private static readonly Random s_random = new Random(); + + /// + /// Length of random string to generate. Default length 4. + /// private int m_length = 4; - /// - /// Initialize the converter options. - /// - /// - /// - /// This is part of the delayed object - /// activation scheme. The method must - /// be called on this object after the configuration properties have - /// been set. Until is called this - /// object is in an undefined state and must not be used. - /// - /// - /// If any of the configuration properties are modified then - /// must be called again. - /// - /// - public void ActivateOptions() - { - string optionStr = this.Option; - if (optionStr != null && optionStr.Length > 0) - { - int lengthVal; - if (SystemInfo.TryParse(optionStr, out lengthVal)) - { - this.m_length = lengthVal; - } - else - { - LogLog.Error(declaringType, "RandomStringPatternConverter: Could not convert Option [" + optionStr + "] to Length Int32"); - } - } + /// + /// Initialize the converter options + /// + /// + /// + /// This is part of the delayed object + /// activation scheme. The method must + /// be called on this object after the configuration properties have + /// been set. Until is called this + /// object is in an undefined state and must not be used. + /// + /// + /// If any of the configuration properties are modified then + /// must be called again. + /// + /// + public void ActivateOptions() + { + string optionStr = this.Option; + if (optionStr != null && optionStr.Length > 0) + { + int lengthVal; + if (SystemInfo.TryParse(optionStr, out lengthVal)) + { + this.m_length = lengthVal; + } + else + { + LogLog.Error(declaringType, "RandomStringPatternConverter: Could not convert Option ["+optionStr+"] to Length Int32"); + } + } } - /// - /// Write a randoim string to the output. - /// - /// the writer to write to. - /// null, state is not set. - /// - /// - /// Write a randoim string to the output . - /// - /// - protected override void Convert(TextWriter writer, object state) - { - try - { - lock (s_random) - { - for (int i = 0; i < this.m_length; i++) - { - int randValue = s_random.Next(36); - - if (randValue < 26) - { - // Letter - char ch = (char)('A' + randValue); - writer.Write(ch); - } - else if (randValue < 36) - { - // Number - char ch = (char)('0' + (randValue - 26)); - writer.Write(ch); - } - else - { - // Should not get here - writer.Write('X'); - } - } - } - } - catch (Exception ex) - { - LogLog.Error(declaringType, "Error occurred while converting.", ex); - } + /// + /// Write a randoim string to the output + /// + /// the writer to write to + /// null, state is not set + /// + /// + /// Write a randoim string to the output . + /// + /// + protected override void Convert(TextWriter writer, object state) + { + try + { + lock(s_random) + { + for(int i = 0; i< this.m_length; i++) + { + int randValue = s_random.Next(36); + + if (randValue < 26) + { + // Letter + char ch = (char)('A' + randValue); + writer.Write(ch); + } + else if (randValue < 36) + { + // Number + char ch = (char)('0' + (randValue - 26)); + writer.Write(ch); + } + else + { + // Should not get here + writer.Write('X'); + } + } + } + } + catch (Exception ex) + { + LogLog.Error(declaringType, "Error occurred while converting.", ex); + } } - /// - /// The fully qualified type of the RandomStringPatternConverter class. - /// - /// - /// Used by the internal logger to record the Type of the - /// log message. - /// + /// + /// The fully qualified type of the RandomStringPatternConverter class. + /// + /// + /// Used by the internal logger to record the Type of the + /// log message. + /// private static readonly Type declaringType = typeof(RandomStringPatternConverter); - } -} + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/PatternStringConverters/UserNamePatternConverter.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/PatternStringConverters/UserNamePatternConverter.cs index ddcbd449467..0b1ec7d7cc5 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/PatternStringConverters/UserNamePatternConverter.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/PatternStringConverters/UserNamePatternConverter.cs @@ -1,85 +1,82 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.Util.PatternStringConverters -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; - using System.IO; - using System.Text; +using System; +using System.IO; - using log4net.Util; +namespace log4net.Util.PatternStringConverters +{ + /// + /// Write the current threads username to the output + /// + /// + /// + /// Write the current threads username to the output writer + /// + /// + /// Nicko Cadell + internal sealed class UserNamePatternConverter : PatternConverter + { + /// + /// Write the current threads username to the output + /// + /// the writer to write to + /// null, state is not set + /// + /// + /// Write the current threads username to the output . + /// + /// + protected override void Convert(TextWriter writer, object state) + { +#if (NETCF || SSCLI || NETSTANDARD1_3) + // On compact framework there's no notion of current Windows user + writer.Write( SystemInfo.NotAvailableText ); +#else + try + { + System.Security.Principal.WindowsIdentity windowsIdentity = null; + windowsIdentity = System.Security.Principal.WindowsIdentity.GetCurrent(); + if (windowsIdentity != null && windowsIdentity.Name != null) + { + writer.Write(windowsIdentity.Name); + } + } + catch(System.Security.SecurityException) + { + // This security exception will occur if the caller does not have + // some undefined set of SecurityPermission flags. + LogLog.Debug(declaringType, "Security exception while trying to get current windows identity. Error Ignored."); - /// - /// Write the current threads username to the output. - /// - /// - /// - /// Write the current threads username to the output writer. - /// - /// - /// Nicko Cadell. - internal sealed class UserNamePatternConverter : PatternConverter - { - /// - /// Write the current threads username to the output. - /// - /// the writer to write to. - /// null, state is not set. - /// - /// - /// Write the current threads username to the output . - /// - /// - protected override void Convert(TextWriter writer, object state) - { -#if NETCF || SSCLI || NETSTANDARD1_3 - // On compact framework there's no notion of current Windows user - writer.Write( SystemInfo.NotAvailableText ); -#else - try - { - System.Security.Principal.WindowsIdentity windowsIdentity = null; - windowsIdentity = System.Security.Principal.WindowsIdentity.GetCurrent(); - if (windowsIdentity != null && windowsIdentity.Name != null) - { - writer.Write(windowsIdentity.Name); - } - } - catch (System.Security.SecurityException) - { - // This security exception will occur if the caller does not have - // some undefined set of SecurityPermission flags. - LogLog.Debug(declaringType, "Security exception while trying to get current windows identity. Error Ignored."); - - writer.Write(SystemInfo.NotAvailableText); - } -#endif + writer.Write(SystemInfo.NotAvailableText); + } +#endif } - /// - /// The fully qualified type of the UserNamePatternConverter class. - /// - /// - /// Used by the internal logger to record the Type of the - /// log message. - /// + /// + /// The fully qualified type of the UserNamePatternConverter class. + /// + /// + /// Used by the internal logger to record the Type of the + /// log message. + /// private static readonly Type declaringType = typeof(UserNamePatternConverter); - } -} + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/PatternStringConverters/UtcDatePatternConverter.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/PatternStringConverters/UtcDatePatternConverter.cs index 35c72776f5c..900b2eaaa6c 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/PatternStringConverters/UtcDatePatternConverter.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/PatternStringConverters/UtcDatePatternConverter.cs @@ -1,83 +1,83 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.Util.PatternStringConverters -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; - using System.IO; - using System.Text; +using System; +using System.Text; +using System.IO; - using log4net.Core; - using log4net.DateFormatter; - using log4net.Util; +using log4net.Core; +using log4net.Util; +using log4net.DateFormatter; - /// - /// Write the UTC date time to the output. - /// - /// - /// - /// Date pattern converter, uses a to format - /// the current date and time in Universal time. - /// - /// - /// See the for details on the date pattern syntax. - /// - /// - /// - /// Nicko Cadell. - internal class UtcDatePatternConverter : DatePatternConverter - { - /// - /// Write the current date and time to the output. - /// - /// that will receive the formatted result. - /// null, state is not set. - /// - /// - /// Pass the current date and time to the - /// for it to render it to the writer. - /// - /// - /// The date is in Universal time when it is rendered. - /// - /// - /// - protected override void Convert(TextWriter writer, object state) - { - try - { - this.m_dateFormatter.FormatDate(DateTime.UtcNow, writer); - } - catch (Exception ex) - { - LogLog.Error(declaringType, "Error occurred while converting date.", ex); - } +namespace log4net.Util.PatternStringConverters +{ + /// + /// Write the UTC date time to the output + /// + /// + /// + /// Date pattern converter, uses a to format + /// the current date and time in Universal time. + /// + /// + /// See the for details on the date pattern syntax. + /// + /// + /// + /// Nicko Cadell + internal class UtcDatePatternConverter : DatePatternConverter + { + /// + /// Write the current date and time to the output + /// + /// that will receive the formatted result. + /// null, state is not set + /// + /// + /// Pass the current date and time to the + /// for it to render it to the writer. + /// + /// + /// The date is in Universal time when it is rendered. + /// + /// + /// + protected override void Convert(TextWriter writer, object state) + { + try + { + this.m_dateFormatter.FormatDate(DateTime.UtcNow, writer); + } + catch (Exception ex) + { + LogLog.Error(declaringType, "Error occurred while converting date.", ex); + } } - /// - /// The fully qualified type of the UtcDatePatternConverter class. - /// - /// - /// Used by the internal logger to record the Type of the - /// log message. - /// + /// + /// The fully qualified type of the UtcDatePatternConverter class. + /// + /// + /// Used by the internal logger to record the Type of the + /// log message. + /// private static readonly Type declaringType = typeof(UtcDatePatternConverter); - } -} + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/PropertiesDictionary.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/PropertiesDictionary.cs index 6d30e123196..ca13e3de25b 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/PropertiesDictionary.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/PropertiesDictionary.cs @@ -1,319 +1,308 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -#if !NETCF -using System.Runtime.Serialization; -using System.Xml; +using System; +using System.Collections; +using System.Runtime.Serialization; -#endif - -namespace log4net.Util -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; - using System.Collections; - - /// - /// String keyed object map. - /// - /// - /// - /// While this collection is serializable only member - /// objects that are serializable will - /// be serialized along with this collection. - /// - /// - /// Nicko Cadell. - /// Gert Driesen. -#if NETCF - public sealed class PropertiesDictionary : ReadOnlyPropertiesDictionary, IDictionary -#else +namespace log4net.Util +{ + /// + /// String keyed object map. + /// + /// + /// + /// While this collection is serializable only member + /// objects that are serializable will + /// be serialized along with this collection. + /// + /// + /// Nicko Cadell + /// Gert Driesen +#if NETCF + public sealed class PropertiesDictionary : ReadOnlyPropertiesDictionary, IDictionary +#else [Serializable] - public sealed class PropertiesDictionary : ReadOnlyPropertiesDictionary, ISerializable, IDictionary -#endif + public sealed class PropertiesDictionary : ReadOnlyPropertiesDictionary, ISerializable, IDictionary +#endif { /// - /// Initializes a new instance of the class. - /// Constructor. - /// - /// - /// - /// Initializes a new instance of the class. - /// - /// - public PropertiesDictionary() - { + /// Constructor + /// + /// + /// + /// Initializes a new instance of the class. + /// + /// + public PropertiesDictionary() + { } /// - /// Initializes a new instance of the class. - /// Constructor. - /// - /// properties to copy. - /// - /// - /// Initializes a new instance of the class. - /// - /// - public PropertiesDictionary(ReadOnlyPropertiesDictionary propertiesDictionary) - : base(propertiesDictionary) - { + /// Constructor + /// + /// properties to copy + /// + /// + /// Initializes a new instance of the class. + /// + /// + public PropertiesDictionary(ReadOnlyPropertiesDictionary propertiesDictionary) : base(propertiesDictionary) + { } -#if !(NETCF || NETSTANDARD1_3) - /// - /// Initializes a new instance of the class - /// with serialized data. - /// - /// The that holds the serialized object data. - /// The that contains contextual information about the source or destination. - /// - /// - /// Because this class is sealed the serialization constructor is private. - /// - /// - private PropertiesDictionary(SerializationInfo info, StreamingContext context) - : base(info, context) - { +#if !NETCF + /// + /// Initializes a new instance of the class + /// with serialized data. + /// + /// The that holds the serialized object data. + /// The that contains contextual information about the source or destination. + /// + /// + /// Because this class is sealed the serialization constructor is private. + /// + /// + private PropertiesDictionary(SerializationInfo info, StreamingContext context) : base(info, context) + { } -#endif +#endif - /// - /// Gets or sets the value of the property with the specified key. - /// - /// - /// The value of the property with the specified key. - /// - /// The key of the property to get or set. - /// - /// - /// The property value will only be serialized if it is serializable. - /// If it cannot be serialized it will be silently ignored if - /// a serialization operation is performed. - /// - /// - public override object this[string key] - { - get { return this.InnerHashtable[key]; } - set { this.InnerHashtable[key] = value; } + /// + /// Gets or sets the value of the property with the specified key. + /// + /// + /// The value of the property with the specified key. + /// + /// The key of the property to get or set. + /// + /// + /// The property value will only be serialized if it is serializable. + /// If it cannot be serialized it will be silently ignored if + /// a serialization operation is performed. + /// + /// + public override object this[string key] + { + get { return this.InnerHashtable[key]; } + set { this.InnerHashtable[key] = value; } } - /// - /// Remove the entry with the specified key from this dictionary. - /// - /// the key for the entry to remove. - /// - /// - /// Remove the entry with the specified key from this dictionary. - /// - /// - public void Remove(string key) - { - this.InnerHashtable.Remove(key); + /// + /// Remove the entry with the specified key from this dictionary + /// + /// the key for the entry to remove + /// + /// + /// Remove the entry with the specified key from this dictionary + /// + /// + public void Remove(string key) + { + this.InnerHashtable.Remove(key); } - /// - /// See . - /// - /// an enumerator. - /// - /// - /// Returns a over the contest of this collection. - /// - /// - IDictionaryEnumerator IDictionary.GetEnumerator() - { - return this.InnerHashtable.GetEnumerator(); - } - - /// - /// See . - /// - /// the key to remove. - /// - /// - /// Remove the entry with the specified key from this dictionary. - /// - /// - void IDictionary.Remove(object key) - { - this.InnerHashtable.Remove(key); - } - - /// - /// See . - /// - /// the key to lookup in the collection. - /// true if the collection contains the specified key. - /// - /// - /// Test if this collection contains a specified key. - /// - /// - bool IDictionary.Contains(object key) - { - return this.InnerHashtable.Contains(key); - } - - /// - /// Remove all properties from the properties collection. - /// - /// - /// - /// Remove all properties from the properties collection. - /// - /// - public override void Clear() - { - this.InnerHashtable.Clear(); - } - - /// - /// See . - /// - /// the key. - /// the value to store for the key. - /// - /// - /// Store a value for the specified . - /// - /// - /// Thrown if the is not a string. - void IDictionary.Add(object key, object value) - { - if (!(key is string)) - { - throw new ArgumentException("key must be a string", "key"); - } + /// + /// See + /// + /// an enumerator + /// + /// + /// Returns a over the contest of this collection. + /// + /// + IDictionaryEnumerator IDictionary.GetEnumerator() + { + return this.InnerHashtable.GetEnumerator(); + } - this.InnerHashtable.Add(key, value); - } - - /// - /// Gets a value indicating whether see . - /// - /// - /// false. - /// - /// - /// - /// This collection is modifiable. This property always - /// returns false. - /// - /// - bool IDictionary.IsReadOnly - { - get { return false; } - } - - /// - /// See . - /// - /// - /// The value for the key specified. - /// - /// - /// - /// Get or set a value for the specified . - /// - /// - /// Thrown if the is not a string. - object IDictionary.this[object key] - { - get - { - if (!(key is string)) - { - throw new ArgumentException("key must be a string", "key"); - } + /// + /// See + /// + /// the key to remove + /// + /// + /// Remove the entry with the specified key from this dictionary + /// + /// + void IDictionary.Remove(object key) + { + this.InnerHashtable.Remove(key); + } - return this.InnerHashtable[key]; - } + /// + /// See + /// + /// the key to lookup in the collection + /// true if the collection contains the specified key + /// + /// + /// Test if this collection contains a specified key. + /// + /// + bool IDictionary.Contains(object key) + { + return this.InnerHashtable.Contains(key); + } + + /// + /// Remove all properties from the properties collection + /// + /// + /// + /// Remove all properties from the properties collection + /// + /// + public override void Clear() + { + this.InnerHashtable.Clear(); + } - set - { - if (!(key is string)) - { - throw new ArgumentException("key must be a string", "key"); - } + /// + /// See + /// + /// the key + /// the value to store for the key + /// + /// + /// Store a value for the specified . + /// + /// + /// Thrown if the is not a string + void IDictionary.Add(object key, object value) + { + if (!(key is string)) + { + throw new ArgumentException("key must be a string", "key"); + } - this.InnerHashtable[key] = value; - } - } - - /// - /// Gets see . - /// - ICollection IDictionary.Values - { - get { return this.InnerHashtable.Values; } - } - - /// - /// Gets see . - /// - ICollection IDictionary.Keys - { - get { return this.InnerHashtable.Keys; } - } - - /// - /// Gets a value indicating whether see . - /// - bool IDictionary.IsFixedSize - { - get { return false; } + this.InnerHashtable.Add(key, value); } - /// - /// See . - /// - /// - /// - void ICollection.CopyTo(Array array, int index) - { - this.InnerHashtable.CopyTo(array, index); - } - - /// - /// Gets a value indicating whether see . - /// - bool ICollection.IsSynchronized - { - get { return this.InnerHashtable.IsSynchronized; } - } - - /// - /// Gets see . - /// - object ICollection.SyncRoot - { - get { return this.InnerHashtable.SyncRoot; } + /// + /// See + /// + /// + /// false + /// + /// + /// + /// This collection is modifiable. This property always + /// returns false. + /// + /// + bool IDictionary.IsReadOnly + { + get { return false; } } - /// - /// See . + /// + /// See /// - /// - IEnumerator IEnumerable.GetEnumerator() - { - return ((IEnumerable)this.InnerHashtable).GetEnumerator(); + /// + /// The value for the key specified. + /// + /// + /// + /// Get or set a value for the specified . + /// + /// + /// Thrown if the is not a string + object IDictionary.this[object key] + { + get + { + if (!(key is string)) + { + throw new ArgumentException("key must be a string", "key"); + } + return this.InnerHashtable[key]; + } + set + { + if (!(key is string)) + { + throw new ArgumentException("key must be a string", "key"); + } + + this.InnerHashtable[key] = value; + } } - } + + /// + /// See + /// + ICollection IDictionary.Values + { + get { return this.InnerHashtable.Values; } + } + + /// + /// See + /// + ICollection IDictionary.Keys + { + get { return this.InnerHashtable.Keys; } + } + + /// + /// See + /// + bool IDictionary.IsFixedSize + { + get { return false; } + } + + /// + /// See + /// + /// + /// + void ICollection.CopyTo(Array array, int index) + { + this.InnerHashtable.CopyTo(array, index); + } + + /// + /// See + /// + bool ICollection.IsSynchronized + { + get { return this.InnerHashtable.IsSynchronized; } + } + + /// + /// See + /// + object ICollection.SyncRoot + { + get { return this.InnerHashtable.SyncRoot; } + } + + /// + /// See + /// + IEnumerator IEnumerable.GetEnumerator() + { + return ((IEnumerable)this.InnerHashtable).GetEnumerator(); + } + } } + diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/PropertyEntry.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/PropertyEntry.cs index 3d4dce2d9f8..1a4fadfbfaf 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/PropertyEntry.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/PropertyEntry.cs @@ -1,84 +1,79 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * -*/ - -namespace log4net.Util -{ - /// - /// A class to hold the key and data for a property set in the config file. - /// - /// - /// - /// A class to hold the key and data for a property set in the config file. - /// - /// - public class PropertyEntry - { - private string m_key = null; - private object m_value = null; - - /// - /// Gets or sets property Key. - /// - /// - /// Property Key. - /// - /// - /// - /// Property Key. - /// - /// - public string Key - { - get { return this.m_key; } - set { this.m_key = value; } - } - - /// - /// Gets or sets property Value. - /// - /// - /// Property Value. - /// - /// - /// - /// Property Value. - /// - /// - public object Value - { - get { return this.m_value; } - set { this.m_value = value; } - } - - /// - /// Override Object.ToString to return sensible debug info. - /// - /// string info about this object. - public override string ToString() - { - return "PropertyEntry(Key=" + this.m_key + ", Value=" + this.m_value + ")"; - } - } -} +namespace log4net.Util +{ + /// + /// A class to hold the key and data for a property set in the config file + /// + /// + /// + /// A class to hold the key and data for a property set in the config file + /// + /// + public class PropertyEntry + { + private string m_key = null; + private object m_value = null; + + /// + /// Property Key + /// + /// + /// Property Key + /// + /// + /// + /// Property Key. + /// + /// + public string Key + { + get { return this.m_key; } + set { this.m_key = value; } + } + + /// + /// Property Value + /// + /// + /// Property Value + /// + /// + /// + /// Property Value. + /// + /// + public object Value + { + get { return this.m_value; } + set { this.m_value = value; } + } + + /// + /// Override Object.ToString to return sensible debug info + /// + /// string info about this object + public override string ToString() + { + return "PropertyEntry(Key=" + this.m_key + ", Value=" + this.m_value + ")"; + } + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/ProtectCloseTextWriter.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/ProtectCloseTextWriter.cs index b82e1569c5d..c35994e99fe 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/ProtectCloseTextWriter.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/ProtectCloseTextWriter.cs @@ -1,84 +1,82 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.Util -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; - using System.IO; - using System.Text; +using System; +using System.IO; +using System.Text; - using log4net.Core; +using log4net.Core; - /// - /// A that ignores the message. - /// - /// - /// - /// This writer is used in special cases where it is necessary - /// to protect a writer from being closed by a client. - /// - /// - /// Nicko Cadell. - public class ProtectCloseTextWriter : TextWriterAdapter +namespace log4net.Util +{ + /// + /// A that ignores the message + /// + /// + /// + /// This writer is used in special cases where it is necessary + /// to protect a writer from being closed by a client. + /// + /// + /// Nicko Cadell + public class ProtectCloseTextWriter : TextWriterAdapter { /// - /// Initializes a new instance of the class. - /// Constructor. - /// - /// the writer to actually write to. - /// - /// - /// Create a new ProtectCloseTextWriter using a writer. - /// - /// - public ProtectCloseTextWriter(TextWriter writer) - : base(writer) - { + /// Constructor + /// + /// the writer to actually write to + /// + /// + /// Create a new ProtectCloseTextWriter using a writer + /// + /// + public ProtectCloseTextWriter(TextWriter writer) : base(writer) + { } - /// - /// Attach this instance to a different underlying . - /// - /// the writer to attach to. - /// - /// - /// Attach this instance to a different underlying . - /// - /// - public void Attach(TextWriter writer) - { - this.Writer = writer; + /// + /// Attach this instance to a different underlying + /// + /// the writer to attach to + /// + /// + /// Attach this instance to a different underlying + /// + /// + public void Attach(TextWriter writer) + { + this.Writer = writer; } - /// - /// Does not close the underlying output writer. - /// - /// - /// - /// Does not close the underlying output writer. - /// This method does nothing. - /// - /// - public override void Close() - { - // do nothing + /// + /// Does not close the underlying output writer. + /// + /// + /// + /// Does not close the underlying output writer. + /// This method does nothing. + /// + /// + public override void Close() + { + // do nothing } - } -} + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/QuietTextWriter.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/QuietTextWriter.cs index 07299581e24..7aff22a35a2 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/QuietTextWriter.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/QuietTextWriter.cs @@ -1,195 +1,192 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.Util -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; - using System.IO; +using System; +using System.IO; - using log4net.Core; +using log4net.Core; - /// - /// that does not leak exceptions. - /// - /// - /// - /// does not throw exceptions when things go wrong. - /// Instead, it delegates error handling to its . - /// - /// - /// Nicko Cadell. - /// Gert Driesen. - public class QuietTextWriter : TextWriterAdapter +namespace log4net.Util +{ + /// + /// that does not leak exceptions + /// + /// + /// + /// does not throw exceptions when things go wrong. + /// Instead, it delegates error handling to its . + /// + /// + /// Nicko Cadell + /// Gert Driesen + public class QuietTextWriter : TextWriterAdapter { /// - /// Initializes a new instance of the class. - /// Constructor. - /// - /// the writer to actually write to. - /// the error handler to report error to. - /// - /// - /// Create a new QuietTextWriter using a writer and error handler. - /// - /// - public QuietTextWriter(TextWriter writer, IErrorHandler errorHandler) - : base(writer) - { - if (errorHandler == null) - { - throw new ArgumentNullException("errorHandler"); - } + /// Constructor + /// + /// the writer to actually write to + /// the error handler to report error to + /// + /// + /// Create a new QuietTextWriter using a writer and error handler + /// + /// + public QuietTextWriter(TextWriter writer, IErrorHandler errorHandler) : base(writer) + { + if (errorHandler == null) + { + throw new ArgumentNullException("errorHandler"); + } - this.ErrorHandler = errorHandler; + this.ErrorHandler = errorHandler; } - /// - /// Gets or sets the error handler that all errors are passed to. - /// - /// - /// The error handler that all errors are passed to. - /// - /// - /// - /// Gets or sets the error handler that all errors are passed to. - /// - /// - public IErrorHandler ErrorHandler - { - get { return this.m_errorHandler; } + /// + /// Gets or sets the error handler that all errors are passed to. + /// + /// + /// The error handler that all errors are passed to. + /// + /// + /// + /// Gets or sets the error handler that all errors are passed to. + /// + /// + public IErrorHandler ErrorHandler + { + get { return this.m_errorHandler; } + set + { + if (value == null) + { + // This is a programming error on the part of the enclosing appender. + throw new ArgumentNullException("value"); + } - set - { - if (value == null) - { - // This is a programming error on the part of the enclosing appender. - throw new ArgumentNullException("value"); - } + this.m_errorHandler = value; + } + } - this.m_errorHandler = value; - } - } - - /// - /// Gets a value indicating whether this writer is closed. - /// - /// - /// true if this writer is closed, otherwise false. - /// - /// - /// - /// Gets a value indicating whether this writer is closed. - /// - /// - public bool Closed - { - get { return this.m_closed; } + /// + /// Gets a value indicating whether this writer is closed. + /// + /// + /// true if this writer is closed, otherwise false. + /// + /// + /// + /// Gets a value indicating whether this writer is closed. + /// + /// + public bool Closed + { + get { return this.m_closed; } } - /// - /// Writes a character to the underlying writer. - /// - /// the char to write. - /// - /// - /// Writes a character to the underlying writer. - /// - /// - public override void Write(char value) - { - try - { - base.Write(value); - } - catch (Exception e) - { - this.m_errorHandler.Error("Failed to write [" + value + "].", e, ErrorCode.WriteFailure); - } - } - - /// - /// Writes a buffer to the underlying writer. - /// - /// the buffer to write. - /// the start index to write from. - /// the number of characters to write. - /// - /// - /// Writes a buffer to the underlying writer. - /// - /// - public override void Write(char[] buffer, int index, int count) - { - try - { - base.Write(buffer, index, count); - } - catch (Exception e) - { - this.m_errorHandler.Error("Failed to write buffer.", e, ErrorCode.WriteFailure); - } - } - - /// - /// Writes a string to the output. - /// - /// The string data to write to the output. - /// - /// - /// Writes a string to the output. - /// - /// - public override void Write(string value) - { - try - { - base.Write(value); - } - catch (Exception e) - { - this.m_errorHandler.Error("Failed to write [" + value + "].", e, ErrorCode.WriteFailure); - } - } - - /// - /// Closes the underlying output writer. - /// - /// - /// - /// Closes the underlying output writer. - /// - /// - public override void Close() - { - this.m_closed = true; - base.Close(); + /// + /// Writes a character to the underlying writer + /// + /// the char to write + /// + /// + /// Writes a character to the underlying writer + /// + /// + public override void Write(char value) + { + try + { + base.Write(value); + } + catch(Exception e) + { + this.m_errorHandler.Error("Failed to write [" + value + "].", e, ErrorCode.WriteFailure); + } + } + + /// + /// Writes a buffer to the underlying writer + /// + /// the buffer to write + /// the start index to write from + /// the number of characters to write + /// + /// + /// Writes a buffer to the underlying writer + /// + /// + public override void Write(char[] buffer, int index, int count) + { + try + { + base.Write(buffer, index, count); + } + catch(Exception e) + { + this.m_errorHandler.Error("Failed to write buffer.", e, ErrorCode.WriteFailure); + } + } + + /// + /// Writes a string to the output. + /// + /// The string data to write to the output. + /// + /// + /// Writes a string to the output. + /// + /// + public override void Write(string value) + { + try + { + base.Write(value); + } + catch(Exception e) + { + this.m_errorHandler.Error("Failed to write [" + value + "].", e, ErrorCode.WriteFailure); + } } - /// - /// The error handler instance to pass all errors to. - /// - private IErrorHandler m_errorHandler; - - /// - /// Flag to indicate if this writer is closed. - /// + /// + /// Closes the underlying output writer. + /// + /// + /// + /// Closes the underlying output writer. + /// + /// + public override void Close() + { + this.m_closed = true; + base.Close(); + } + + /// + /// The error handler instance to pass all errors to + /// + private IErrorHandler m_errorHandler; + + /// + /// Flag to indicate if this writer is closed + /// private bool m_closed = false; - } -} + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/ReadOnlyPropertiesDictionary.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/ReadOnlyPropertiesDictionary.cs index c09d93af17c..4e26c22ade7 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/ReadOnlyPropertiesDictionary.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/ReadOnlyPropertiesDictionary.cs @@ -1,364 +1,368 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -#if !NETCF -using System.Runtime.Serialization; -using System.Xml; +using System; +using System.Collections; +#if NETSTANDARD1_3 +using System.Reflection; +#endif +using System.Runtime.Serialization; +using System.Xml; -#endif - -namespace log4net.Util -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; - using System.Collections; - using System.Reflection; - - /// - /// String keyed object map that is read only. - /// - /// - /// - /// This collection is readonly and cannot be modified. - /// - /// - /// While this collection is serializable only member - /// objects that are serializable will - /// be serialized along with this collection. - /// - /// - /// Nicko Cadell. - /// Gert Driesen. -#if NETCF - public class ReadOnlyPropertiesDictionary : IDictionary -#else - [Serializable] - public class ReadOnlyPropertiesDictionary : ISerializable, IDictionary -#endif +namespace log4net.Util +{ + /// + /// String keyed object map that is read only. + /// + /// + /// + /// This collection is readonly and cannot be modified. + /// + /// + /// While this collection is serializable only member + /// objects that are serializable will + /// be serialized along with this collection. + /// + /// + /// Nicko Cadell + /// Gert Driesen +#if NETCF + public class ReadOnlyPropertiesDictionary : IDictionary +#else + [Serializable] public class ReadOnlyPropertiesDictionary : ISerializable, IDictionary +#endif { - /// - /// The Hashtable used to store the properties data. - /// + /// + /// The Hashtable used to store the properties data + /// private readonly Hashtable m_hashtable = new Hashtable(); /// - /// Initializes a new instance of the class. - /// Constructor. - /// - /// - /// - /// Initializes a new instance of the class. - /// - /// - public ReadOnlyPropertiesDictionary() - { + /// Constructor + /// + /// + /// + /// Initializes a new instance of the class. + /// + /// + public ReadOnlyPropertiesDictionary() + { + } + + /// + /// Copy Constructor + /// + /// properties to copy + /// + /// + /// Initializes a new instance of the class. + /// + /// + public ReadOnlyPropertiesDictionary(ReadOnlyPropertiesDictionary propertiesDictionary) + { + foreach(DictionaryEntry entry in propertiesDictionary) + { + this.InnerHashtable.Add(entry.Key, entry.Value); + } + } + +#if !NETCF + /// + /// Deserialization constructor + /// + /// The that holds the serialized object data. + /// The that contains contextual information about the source or destination. + /// + /// + /// Initializes a new instance of the class + /// with serialized data. + /// + /// + protected ReadOnlyPropertiesDictionary(SerializationInfo info, StreamingContext context) + { + foreach(var entry in info) + { + // The keys are stored as Xml encoded names + this.InnerHashtable[XmlConvert.DecodeName(entry.Name)] = entry.Value; + } + } +#endif + + /// + /// Gets the key names. + /// + /// An array of all the keys. + /// + /// + /// Gets the key names. + /// + /// + public string[] GetKeys() + { + var keys = new String[this.InnerHashtable.Count]; + this.InnerHashtable.Keys.CopyTo(keys, 0); + return keys; + } + + /// + /// Gets or sets the value of the property with the specified key. + /// + /// + /// The value of the property with the specified key. + /// + /// The key of the property to get or set. + /// + /// + /// The property value will only be serialized if it is serializable. + /// If it cannot be serialized it will be silently ignored if + /// a serialization operation is performed. + /// + /// + public virtual object this[string key] + { + get { return this.InnerHashtable[key]; } + set { throw new NotSupportedException("This is a Read Only Dictionary and can not be modified"); } } /// - /// Initializes a new instance of the class. - /// Copy Constructor. - /// - /// properties to copy. - /// - /// - /// Initializes a new instance of the class. - /// - /// - public ReadOnlyPropertiesDictionary(ReadOnlyPropertiesDictionary propertiesDictionary) - { - foreach (DictionaryEntry entry in propertiesDictionary) - { - this.InnerHashtable.Add(entry.Key, entry.Value); - } + /// Test if the dictionary contains a specified key + /// + /// the key to look for + /// true if the dictionary contains the specified key + /// + /// + /// Test if the dictionary contains a specified key + /// + /// + public bool Contains(string key) + { + return this.InnerHashtable.Contains(key); } -#if !(NETCF || NETSTANDARD1_3) /// - /// Initializes a new instance of the class. - /// Deserialization constructor. - /// - /// The that holds the serialized object data. - /// The that contains contextual information about the source or destination. - /// - /// - /// Initializes a new instance of the class - /// with serialized data. - /// - /// - protected ReadOnlyPropertiesDictionary(SerializationInfo info, StreamingContext context) - { - foreach (SerializationEntry entry in info) - { - // The keys are stored as Xml encoded names - this.InnerHashtable[XmlConvert.DecodeName(entry.Name)] = entry.Value; - } + /// The hashtable used to store the properties + /// + /// + /// The internal collection used to store the properties + /// + /// + /// + /// The hashtable used to store the properties + /// + /// + protected Hashtable InnerHashtable + { + get { return this.m_hashtable; } } -#endif - /// - /// Gets the key names. - /// - /// An array of all the keys. - /// - /// - /// Gets the key names. - /// - /// - public string[] GetKeys() - { - string[] keys = new string[this.InnerHashtable.Count]; - this.InnerHashtable.Keys.CopyTo(keys, 0); - return keys; - } - - /// - /// Gets or sets the value of the property with the specified key. - /// - /// - /// The value of the property with the specified key. - /// - /// The key of the property to get or set. - /// - /// - /// The property value will only be serialized if it is serializable. - /// If it cannot be serialized it will be silently ignored if - /// a serialization operation is performed. - /// - /// - public virtual object this[string key] - { - get { return this.InnerHashtable[key]; } - set { throw new NotSupportedException("This is a Read Only Dictionary and can not be modified"); } +#if !NETCF + /// + /// Serializes this object into the provided. + /// + /// The to populate with data. + /// The destination for this serialization. + /// + /// + /// Serializes this object into the provided. + /// + /// +#if NET_4_0 || MONO_4_0 || NETSTANDARD + [System.Security.SecurityCritical] +#endif +#if !NETCF && !NETSTANDARD1_3 + [System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Demand, SerializationFormatter = true)] +#endif + public virtual void GetObjectData(SerializationInfo info, StreamingContext context) + { + foreach(DictionaryEntry entry in this.InnerHashtable.Clone() as IDictionary) + { + var entryKey = entry.Key as string; + if (entryKey is null) + { + continue; + } + + var entryValue = entry.Value; + + // If value is serializable then we add it to the list +#if NETSTANDARD1_3 + var isSerializable = entryValue?.GetType().GetTypeInfo().IsSerializable ?? false; +#else + var isSerializable = entryValue?.GetType().IsSerializable ?? false; +#endif + if (!isSerializable) + { + continue; + } + + // Store the keys as an Xml encoded local name as it may contain colons (':') + // which are NOT escaped by the Xml Serialization framework. + // This must be a bug in the serialization framework as we cannot be expected + // to know the implementation details of all the possible transport layers. + var localKeyName = XmlConvert.EncodeLocalName(entryKey); + if (localKeyName != null) + { + info.AddValue(localKeyName, entryValue); + } + } } +#endif - /// - /// Test if the dictionary contains a specified key. - /// - /// the key to look for. - /// true if the dictionary contains the specified key. - /// - /// - /// Test if the dictionary contains a specified key. - /// - /// - public bool Contains(string key) - { - return this.InnerHashtable.Contains(key); + /// + /// See + /// + IDictionaryEnumerator IDictionary.GetEnumerator() + { + return this.InnerHashtable.GetEnumerator(); } - /// - /// Gets the hashtable used to store the properties. - /// - /// - /// The internal collection used to store the properties. - /// - /// - /// - /// The hashtable used to store the properties. - /// - /// - protected Hashtable InnerHashtable - { - get { return this.m_hashtable; } + /// + /// See + /// + /// + void IDictionary.Remove(object key) + { + throw new NotSupportedException("This is a Read Only Dictionary and can not be modified"); } -#if !NETCF - /// - /// Serializes this object into the provided. - /// - /// The to populate with data. - /// The destination for this serialization. - /// - /// - /// Serializes this object into the provided. - /// - /// -#if NET_4_0 || MONO_4_0 || NETSTANDARD1_3 - [System.Security.SecurityCritical] -#else - [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.Demand, SerializationFormatter=true)] -#endif - public virtual void GetObjectData(SerializationInfo info, StreamingContext context) - { - foreach (DictionaryEntry entry in this.InnerHashtable.Clone() as IDictionary) - { - string entryKey = entry.Key as string; - object entryValue = entry.Value; - - // If value is serializable then we add it to the list -#if NETSTANDARD1_3 - bool isSerializable = entryValue.GetType().GetTypeInfo().IsSerializable; -#else - bool isSerializable = entryValue.GetType().IsSerializable; -#endif - if (entryKey != null && entryValue != null && isSerializable) - { - // Store the keys as an Xml encoded local name as it may contain colons (':') - // which are NOT escaped by the Xml Serialization framework. - // This must be a bug in the serialization framework as we cannot be expected - // to know the implementation details of all the possible transport layers. - info.AddValue(XmlConvert.EncodeLocalName(entryKey), entryValue); - } - } + /// + /// See + /// + /// + /// + bool IDictionary.Contains(object key) + { + return this.InnerHashtable.Contains(key); } -#endif - /// - /// See . + /// + /// Remove all properties from the properties collection /// - /// - IDictionaryEnumerator IDictionary.GetEnumerator() - { - return this.InnerHashtable.GetEnumerator(); - } - - /// - /// See . - /// - /// - void IDictionary.Remove(object key) - { - throw new NotSupportedException("This is a Read Only Dictionary and can not be modified"); - } - - /// - /// See . - /// - /// - /// - bool IDictionary.Contains(object key) - { - return this.InnerHashtable.Contains(key); - } - - /// - /// Remove all properties from the properties collection. - /// - public virtual void Clear() - { - throw new NotSupportedException("This is a Read Only Dictionary and can not be modified"); - } - - /// - /// See . - /// - /// - /// - void IDictionary.Add(object key, object value) - { - throw new NotSupportedException("This is a Read Only Dictionary and can not be modified"); - } - - /// - /// Gets a value indicating whether see . - /// - bool IDictionary.IsReadOnly - { - get { return true; } - } - - /// - /// See . - /// - object IDictionary.this[object key] - { - get - { + public virtual void Clear() + { + throw new NotSupportedException("This is a Read Only Dictionary and can not be modified"); + } + + /// + /// See + /// + /// + /// + void IDictionary.Add(object key, object value) + { + throw new NotSupportedException("This is a Read Only Dictionary and can not be modified"); + } + + /// + /// See + /// + bool IDictionary.IsReadOnly + { + get { return true; } + } + + /// + /// See + /// + object IDictionary.this[object key] + { + get + { if (!(key is string)) { throw new ArgumentException("key must be a string"); } - return this.InnerHashtable[key]; - } + return this.InnerHashtable[key]; + } + set + { + throw new NotSupportedException("This is a Read Only Dictionary and can not be modified"); + } + } - set - { - throw new NotSupportedException("This is a Read Only Dictionary and can not be modified"); - } - } - - /// - /// Gets see . - /// - ICollection IDictionary.Values - { - get { return this.InnerHashtable.Values; } - } - - /// - /// Gets see . - /// - ICollection IDictionary.Keys - { - get { return this.InnerHashtable.Keys; } - } - - /// - /// Gets a value indicating whether see . - /// - bool IDictionary.IsFixedSize - { - get { return this.InnerHashtable.IsFixedSize; } + /// + /// See + /// + ICollection IDictionary.Values + { + get { return this.InnerHashtable.Values; } } - /// - /// See . - /// - /// - /// - void ICollection.CopyTo(Array array, int index) - { - this.InnerHashtable.CopyTo(array, index); - } - - /// - /// Gets a value indicating whether see . - /// - bool ICollection.IsSynchronized - { - get { return this.InnerHashtable.IsSynchronized; } - } - - /// - /// Gets the number of properties in this collection. - /// - public int Count - { - get { return this.InnerHashtable.Count; } - } - - /// - /// Gets see . - /// - object ICollection.SyncRoot - { - get { return this.InnerHashtable.SyncRoot; } + /// + /// See + /// + ICollection IDictionary.Keys + { + get { return this.InnerHashtable.Keys; } } - /// - /// See . + /// + /// See /// - /// - IEnumerator IEnumerable.GetEnumerator() - { - return ((IEnumerable)this.InnerHashtable).GetEnumerator(); + bool IDictionary.IsFixedSize + { + get { return this.InnerHashtable.IsFixedSize; } } - } + + /// + /// See + /// + /// + /// + void ICollection.CopyTo(Array array, int index) + { + this.InnerHashtable.CopyTo(array, index); + } + + /// + /// See + /// + bool ICollection.IsSynchronized + { + get { return this.InnerHashtable.IsSynchronized; } + } + + /// + /// The number of properties in this collection + /// + public int Count + { + get { return this.InnerHashtable.Count; } + } + + /// + /// See + /// + object ICollection.SyncRoot + { + get { return this.InnerHashtable.SyncRoot; } + } + + /// + /// See + /// + IEnumerator IEnumerable.GetEnumerator() + { + return ((IEnumerable)this.InnerHashtable).GetEnumerator(); + } + } } + diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/ReaderWriterLock.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/ReaderWriterLock.cs index 510550a3028..a5755aaba2b 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/ReaderWriterLock.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/ReaderWriterLock.cs @@ -1,185 +1,184 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#if !NETCF -#define HAS_READERWRITERLOCK -#endif -#if NET_4_0 || MONO_4_0 -#define HAS_READERWRITERLOCKSLIM -#endif - -using System; - -namespace log4net.Util -{ - /// - /// Defines a lock that supports single writers and multiple readers. - /// - /// - /// - /// ReaderWriterLock is used to synchronize access to a resource. - /// At any given time, it allows either concurrent read access for - /// multiple threads, or write access for a single thread. In a - /// situation where a resource is changed infrequently, a - /// ReaderWriterLock provides better throughput than a simple - /// one-at-a-time lock, such as . - /// - /// - /// If a platform does not support a System.Threading.ReaderWriterLock - /// implementation then all readers and writers are serialized. Therefore - /// the caller must not rely on multiple simultaneous readers. - /// - /// - /// Nicko Cadell. - public sealed class ReaderWriterLock +#if (!NETCF) && !NETSTANDARD1_3 +#define HAS_READERWRITERLOCK +#endif +#if NET_4_0 || MONO_4_0 +#define HAS_READERWRITERLOCKSLIM +#endif + +using System; + +namespace log4net.Util +{ + /// + /// Defines a lock that supports single writers and multiple readers + /// + /// + /// + /// ReaderWriterLock is used to synchronize access to a resource. + /// At any given time, it allows either concurrent read access for + /// multiple threads, or write access for a single thread. In a + /// situation where a resource is changed infrequently, a + /// ReaderWriterLock provides better throughput than a simple + /// one-at-a-time lock, such as . + /// + /// + /// If a platform does not support a System.Threading.ReaderWriterLock + /// implementation then all readers and writers are serialized. Therefore + /// the caller must not rely on multiple simultaneous readers. + /// + /// + /// Nicko Cadell + public sealed class ReaderWriterLock { /// - /// Initializes a new instance of the class. - /// Constructor. - /// - /// - /// - /// Initializes a new instance of the class. - /// - /// - public ReaderWriterLock() - { -#if HAS_READERWRITERLOCK -#if HAS_READERWRITERLOCKSLIM - this.m_lock = new System.Threading.ReaderWriterLockSlim(System.Threading.LockRecursionPolicy.SupportsRecursion); -#else - m_lock = new System.Threading.ReaderWriterLock(); -#endif -#endif + /// Constructor + /// + /// + /// + /// Initializes a new instance of the class. + /// + /// + public ReaderWriterLock() + { + +#if HAS_READERWRITERLOCK +#if HAS_READERWRITERLOCKSLIM + this.m_lock = new System.Threading.ReaderWriterLockSlim(System.Threading.LockRecursionPolicy.SupportsRecursion); +#else + m_lock = new System.Threading.ReaderWriterLock(); +#endif +#endif + } + + /// + /// Acquires a reader lock + /// + /// + /// + /// blocks if a different thread has the writer + /// lock, or if at least one thread is waiting for the writer lock. + /// + /// + public void AcquireReaderLock() + { +#if HAS_READERWRITERLOCK +#if HAS_READERWRITERLOCKSLIM + // prevent ThreadAbort while updating state, see https://issues.apache.org/jira/browse/LOG4NET-443 + try + { + } + finally + { + this.m_lock.EnterReadLock(); + } +#else + m_lock.AcquireReaderLock(-1); +#endif +#else + System.Threading.Monitor.Enter(this); +#endif + } + + /// + /// Decrements the lock count + /// + /// + /// + /// decrements the lock count. When the count + /// reaches zero, the lock is released. + /// + /// + public void ReleaseReaderLock() + { +#if HAS_READERWRITERLOCK +#if HAS_READERWRITERLOCKSLIM + this.m_lock.ExitReadLock(); +#else + m_lock.ReleaseReaderLock(); + +#endif +#else + System.Threading.Monitor.Exit(this); +#endif } - /// - /// Acquires a reader lock. - /// - /// - /// - /// blocks if a different thread has the writer - /// lock, or if at least one thread is waiting for the writer lock. - /// - /// - public void AcquireReaderLock() + /// + /// Acquires the writer lock + /// + /// + /// + /// This method blocks if another thread has a reader lock or writer lock. + /// + /// + public void AcquireWriterLock() { -#if HAS_READERWRITERLOCK -#if HAS_READERWRITERLOCKSLIM - // prevent ThreadAbort while updating state, see https://issues.apache.org/jira/browse/LOG4NET-443 - try - { - } - finally - { - this.m_lock.EnterReadLock(); - } -#else - m_lock.AcquireReaderLock(-1); -#endif -#else - System.Threading.Monitor.Enter(this); -#endif - } - - /// - /// Decrements the lock count. - /// - /// - /// - /// decrements the lock count. When the count - /// reaches zero, the lock is released. - /// - /// - public void ReleaseReaderLock() - { -#if HAS_READERWRITERLOCK -#if HAS_READERWRITERLOCKSLIM - this.m_lock.ExitReadLock(); -#else - m_lock.ReleaseReaderLock(); - -#endif -#else - System.Threading.Monitor.Exit(this); -#endif - } - - /// - /// Acquires the writer lock. - /// - /// - /// - /// This method blocks if another thread has a reader lock or writer lock. - /// - /// - public void AcquireWriterLock() +#if HAS_READERWRITERLOCK +#if HAS_READERWRITERLOCKSLIM + // prevent ThreadAbort while updating state, see https://issues.apache.org/jira/browse/LOG4NET-443 + try + { + } + finally + { + this.m_lock.EnterWriteLock(); + } +#else + m_lock.AcquireWriterLock(-1); +#endif +#else + System.Threading.Monitor.Enter(this); +#endif + } + + /// + /// Decrements the lock count on the writer lock + /// + /// + /// + /// ReleaseWriterLock decrements the writer lock count. + /// When the count reaches zero, the writer lock is released. + /// + /// + public void ReleaseWriterLock() { -#if HAS_READERWRITERLOCK -#if HAS_READERWRITERLOCKSLIM - // prevent ThreadAbort while updating state, see https://issues.apache.org/jira/browse/LOG4NET-443 - try - { - } - finally - { - this.m_lock.EnterWriteLock(); - } -#else - m_lock.AcquireWriterLock(-1); -#endif -#else - System.Threading.Monitor.Enter(this); -#endif - } - - /// - /// Decrements the lock count on the writer lock. - /// - /// - /// - /// ReleaseWriterLock decrements the writer lock count. - /// When the count reaches zero, the writer lock is released. - /// - /// - public void ReleaseWriterLock() - { -#if HAS_READERWRITERLOCK -#if HAS_READERWRITERLOCKSLIM - this.m_lock.ExitWriteLock(); -#else - m_lock.ReleaseWriterLock(); -#endif -#else - System.Threading.Monitor.Exit(this); -#endif +#if HAS_READERWRITERLOCK +#if HAS_READERWRITERLOCKSLIM + this.m_lock.ExitWriteLock(); +#else + m_lock.ReleaseWriterLock(); +#endif +#else + System.Threading.Monitor.Exit(this); +#endif } -#if HAS_READERWRITERLOCK -#if HAS_READERWRITERLOCKSLIM +#if HAS_READERWRITERLOCK +#if HAS_READERWRITERLOCKSLIM private System.Threading.ReaderWriterLockSlim m_lock; -#else - private System.Threading.ReaderWriterLock m_lock; -#endif - -#endif +#else + private System.Threading.ReaderWriterLock m_lock; +#endif - } -} +#endif + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/ReusableStringWriter.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/ReusableStringWriter.cs index ad6fabf7c1e..5ecfff630e9 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/ReusableStringWriter.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/ReusableStringWriter.cs @@ -1,93 +1,91 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.Util -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; - using System.IO; - using System.Text; +using System; +using System.Text; +using System.IO; - /// - /// A that can be and reused. - /// - /// - /// - /// A that can be and reused. - /// This uses a single buffer for string operations. - /// - /// - /// Nicko Cadell. - public class ReusableStringWriter : StringWriter +namespace log4net.Util +{ + /// + /// A that can be and reused + /// + /// + /// + /// A that can be and reused. + /// This uses a single buffer for string operations. + /// + /// + /// Nicko Cadell + public class ReusableStringWriter : StringWriter { /// - /// Initializes a new instance of the class. - /// Create an instance of . - /// - /// the format provider to use. - /// - /// - /// Create an instance of . - /// - /// - public ReusableStringWriter(IFormatProvider formatProvider) - : base(formatProvider) - { + /// Create an instance of + /// + /// the format provider to use + /// + /// + /// Create an instance of + /// + /// + public ReusableStringWriter(IFormatProvider formatProvider) : base(formatProvider) + { } - /// - /// Override Dispose to prevent closing of writer. - /// - /// flag. - /// - /// - /// Override Dispose to prevent closing of writer. - /// - /// - protected override void Dispose(bool disposing) - { - // Do not close the writer - } - - /// - /// Reset this string writer so that it can be reused. - /// - /// the maximum buffer capacity before it is trimmed. - /// the default size to make the buffer. - /// - /// - /// Reset this string writer so that it can be reused. - /// The internal buffers are cleared and reset. - /// - /// - public void Reset(int maxCapacity, int defaultSize) - { - // Reset working string buffer - StringBuilder sb = this.GetStringBuilder(); - - sb.Length = 0; - - // Check if over max size - if (sb.Capacity > maxCapacity) - { - sb.Capacity = defaultSize; - } - } - } -} + /// + /// Override Dispose to prevent closing of writer + /// + /// flag + /// + /// + /// Override Dispose to prevent closing of writer + /// + /// + protected override void Dispose(bool disposing) + { + // Do not close the writer + } + + /// + /// Reset this string writer so that it can be reused. + /// + /// the maximum buffer capacity before it is trimmed + /// the default size to make the buffer + /// + /// + /// Reset this string writer so that it can be reused. + /// The internal buffers are cleared and reset. + /// + /// + public void Reset(int maxCapacity, int defaultSize) + { + // Reset working string buffer + StringBuilder sb = this.GetStringBuilder(); + + sb.Length = 0; + + // Check if over max size + if (sb.Capacity > maxCapacity) + { + sb.Capacity = defaultSize; + } + } + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/SystemInfo.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/SystemInfo.cs index 1bd60bcb5e3..101cfb2d91e 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/SystemInfo.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/SystemInfo.cs @@ -1,1304 +1,1296 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +using System; +#if NETSTANDARD1_3 +using System.Globalization; +#else +using System.Configuration; +#endif +using System.Reflection; +using System.IO; +using System.Collections; -#if NETSTANDARD1_3 -using System.Globalization; -#else -using System.Configuration; - -#endif -using System.Collections; -using System.IO; -using System.Reflection; -using System.Runtime.InteropServices; -using System.Text; - -namespace log4net.Util -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; - - /// - /// Utility class for system specific information. - /// - /// - /// - /// Utility class of static methods for system specific information. - /// - /// - /// Nicko Cadell. - /// Gert Driesen. - /// Alexey Solofnenko. - public sealed class SystemInfo +namespace log4net.Util +{ + /// + /// Utility class for system specific information. + /// + /// + /// + /// Utility class of static methods for system specific information. + /// + /// + /// Nicko Cadell + /// Gert Driesen + /// Alexey Solofnenko + public sealed class SystemInfo { - private const string DEFAULT_NULL_TEXT = "(null)"; + private const string DEFAULT_NULL_TEXT = "(null)"; private const string DEFAULT_NOT_AVAILABLE_TEXT = "NOT AVAILABLE"; /// - /// Initializes a new instance of the class. - /// Private constructor to prevent instances. - /// - /// - /// - /// Only static methods are exposed from this type. - /// - /// - private SystemInfo() - { + /// Private constructor to prevent instances. + /// + /// + /// + /// Only static methods are exposed from this type. + /// + /// + private SystemInfo() + { } /// - /// Initializes static members of the class. - /// Initialize default values for private static fields. - /// - /// - /// - /// Only static methods are exposed from this type. - /// - /// - static SystemInfo() - { - string nullText = DEFAULT_NULL_TEXT; - string notAvailableText = DEFAULT_NOT_AVAILABLE_TEXT; - -#if !NETCF - // Look for log4net.NullText in AppSettings - string nullTextAppSettingsKey = SystemInfo.GetAppSetting("log4net.NullText"); - if (nullTextAppSettingsKey != null && nullTextAppSettingsKey.Length > 0) - { - LogLog.Debug(declaringType, "Initializing NullText value to [" + nullTextAppSettingsKey + "]."); - nullText = nullTextAppSettingsKey; - } - - // Look for log4net.NotAvailableText in AppSettings - string notAvailableTextAppSettingsKey = SystemInfo.GetAppSetting("log4net.NotAvailableText"); - if (notAvailableTextAppSettingsKey != null && notAvailableTextAppSettingsKey.Length > 0) - { - LogLog.Debug(declaringType, "Initializing NotAvailableText value to [" + notAvailableTextAppSettingsKey + "]."); - notAvailableText = notAvailableTextAppSettingsKey; - } -#endif - s_notAvailableText = notAvailableText; - s_nullText = nullText; + /// Initialize default values for private static fields. + /// + /// + /// + /// Only static methods are exposed from this type. + /// + /// + static SystemInfo() + { + string nullText = DEFAULT_NULL_TEXT; + string notAvailableText = DEFAULT_NOT_AVAILABLE_TEXT; + +#if !NETCF + // Look for log4net.NullText in AppSettings + string nullTextAppSettingsKey = GetAppSetting("log4net.NullText"); + if (nullTextAppSettingsKey != null && nullTextAppSettingsKey.Length > 0) + { + LogLog.Debug(declaringType, "Initializing NullText value to [" + nullTextAppSettingsKey + "]."); + nullText = nullTextAppSettingsKey; + } + + // Look for log4net.NotAvailableText in AppSettings + string notAvailableTextAppSettingsKey = GetAppSetting("log4net.NotAvailableText"); + if (notAvailableTextAppSettingsKey != null && notAvailableTextAppSettingsKey.Length > 0) + { + LogLog.Debug(declaringType, "Initializing NotAvailableText value to [" + notAvailableTextAppSettingsKey + "]."); + notAvailableText = notAvailableTextAppSettingsKey; + } +#endif + s_notAvailableText = notAvailableText; + s_nullText = nullText; + } + + /// + /// Gets the system dependent line terminator. + /// + /// + /// The system dependent line terminator. + /// + /// + /// + /// Gets the system dependent line terminator. + /// + /// + public static string NewLine + { + get + { +#if NETCF + return "\r\n"; +#else + return Environment.NewLine; +#endif + } } - /// - /// Gets the system dependent line terminator. - /// - /// - /// The system dependent line terminator. - /// - /// - /// - /// Gets the system dependent line terminator. - /// - /// - public static string NewLine - { - get - { -#if NETCF - return "\r\n"; -#else - return System.Environment.NewLine; -#endif - } - } - - /// - /// Gets the base directory for this . - /// - /// The base directory path for the current . - /// - /// - /// Gets the base directory for this . - /// - /// - /// The value returned may be either a local file path or a URI. - /// - /// - public static string ApplicationBaseDirectory - { - get - { -#if NETCF -- return System.IO.Path.GetDirectoryName(SystemInfo.EntryAssemblyLocation) + System.IO.Path.DirectorySeparatorChar; -#elif NETSTANDARD1_3 - return Directory.GetCurrentDirectory(); -#else - return AppDomain.CurrentDomain.BaseDirectory; -#endif - } - } - - /// - /// Gets the path to the configuration file for the current . - /// - /// The path to the configuration file for the current . - /// - /// - /// The .NET Compact Framework 1.0 does not have a concept of a configuration - /// file. For this runtime, we use the entry assembly location as the root for - /// the configuration file name. - /// - /// - /// The value returned may be either a local file path or a URI. - /// - /// - public static string ConfigurationFileLocation - { - get - { -#if NETCF || NETSTANDARD1_3 - return SystemInfo.EntryAssemblyLocation+".config"; -#else - return System.AppDomain.CurrentDomain.SetupInformation.ConfigurationFile; -#endif - } - } - - /// - /// Gets the path to the file that first executed in the current . - /// - /// The path to the entry assembly. - /// - /// - /// Gets the path to the file that first executed in the current . - /// - /// - public static string EntryAssemblyLocation - { - get - { -#if NETCF - return SystemInfo.NativeEntryAssemblyLocation; -#elif NETSTANDARD1_3 // TODO GetEntryAssembly is available for netstandard1.5 - return AppContext.BaseDirectory; -#else - return System.Reflection.Assembly.GetEntryAssembly().Location; -#endif - } - } - - /// - /// Gets the ID of the current thread. - /// - /// The ID of the current thread. - /// - /// - /// On the .NET framework, the AppDomain.GetCurrentThreadId method - /// is used to obtain the thread ID for the current thread. This is the - /// operating system ID for the thread. - /// - /// - /// On the .NET Compact Framework 1.0 it is not possible to get the - /// operating system thread ID for the current thread. The native method - /// GetCurrentThreadId is implemented inline in a header file - /// and cannot be called. - /// - /// - /// On the .NET Framework 2.0 the Thread.ManagedThreadId is used as this - /// gives a stable id unrelated to the operating system thread ID which may - /// change if the runtime is using fibers. - /// - /// - public static int CurrentThreadId - { - get - { -#if NETCF_1_0 - return System.Threading.Thread.CurrentThread.GetHashCode(); -#elif NET_2_0 || NETCF_2_0 || MONO_2_0 || MONO_3_5 || MONO_4_0 || NETSTANDARD1_3 - return System.Threading.Thread.CurrentThread.ManagedThreadId; -#else - return AppDomain.GetCurrentThreadId(); -#endif - } - } - - /// - /// Gets get the host name or machine name for the current machine. - /// - /// - /// The hostname or machine name. - /// - /// - /// - /// Get the host name or machine name for the current machine. - /// - /// - /// The host name () or - /// the machine name (Environment.MachineName) for - /// the current machine, or if neither of these are available - /// then NOT AVAILABLE is returned. - /// - /// - public static string HostName - { - get - { - if (s_hostName == null) - { - // Get the DNS host name of the current machine - try - { - // Lookup the host name - s_hostName = System.Net.Dns.GetHostName(); - } - catch (System.Net.Sockets.SocketException) - { - LogLog.Debug(declaringType, "Socket exception occurred while getting the dns hostname. Error Ignored."); - } - catch (System.Security.SecurityException) - { - // We may get a security exception looking up the hostname - // You must have Unrestricted DnsPermission to access resource - LogLog.Debug(declaringType, "Security exception occurred while getting the dns hostname. Error Ignored."); - } - catch (Exception ex) - { - LogLog.Debug(declaringType, "Some other exception occurred while getting the dns hostname. Error Ignored.", ex); - } - - // Get the NETBIOS machine name of the current machine - if (s_hostName == null || s_hostName.Length == 0) - { - try - { -#if NETSTANDARD1_3 - s_hostName = Environment.GetEnvironmentVariable("COMPUTERNAME"); -#elif !SSCLI && !NETCF - s_hostName = Environment.MachineName; -#endif - } - catch (InvalidOperationException) - { - } - catch (System.Security.SecurityException) - { - // We may get a security exception looking up the machine name - // You must have Unrestricted EnvironmentPermission to access resource - } - } - - // Couldn't find a value - if (s_hostName == null || s_hostName.Length == 0) - { - s_hostName = s_notAvailableText; - LogLog.Debug(declaringType, "Could not determine the hostname. Error Ignored. Empty host name will be used"); - } - } - - return s_hostName; - } - } - - /// - /// Gets get this application's friendly name. - /// - /// - /// The friendly name of this application as a string. - /// - /// - /// - /// If available the name of the application is retrieved from - /// the AppDomain using AppDomain.CurrentDomain.FriendlyName. - /// - /// - /// Otherwise the file name of the entry assembly is used. - /// - /// - public static string ApplicationFriendlyName - { - get - { - if (s_appFriendlyName == null) - { - try - { -#if !(NETCF || NETSTANDARD1_3) - s_appFriendlyName = AppDomain.CurrentDomain.FriendlyName; -#endif - } - catch (System.Security.SecurityException) - { - // This security exception will occur if the caller does not have - // some undefined set of SecurityPermission flags. - LogLog.Debug(declaringType, "Security exception while trying to get current domain friendly name. Error Ignored."); - } - - if (s_appFriendlyName == null || s_appFriendlyName.Length == 0) - { - try - { - string assemblyLocation = SystemInfo.EntryAssemblyLocation; - s_appFriendlyName = System.IO.Path.GetFileName(assemblyLocation); - } - catch (System.Security.SecurityException) - { - // Caller needs path discovery permission - } - } - - if (s_appFriendlyName == null || s_appFriendlyName.Length == 0) - { - s_appFriendlyName = s_notAvailableText; - } - } - - return s_appFriendlyName; - } - } - - /// - /// Gets get the start time for the current process. - /// - /// - /// - /// This is the time at which the log4net library was loaded into the - /// AppDomain. Due to reports of a hang in the call to System.Diagnostics.Process.StartTime - /// this is not the start time for the current process. - /// - /// - /// The log4net library should be loaded by an application early during its - /// startup, therefore this start time should be a good approximation for - /// the actual start time. - /// - /// - /// Note that AppDomains may be loaded and unloaded within the - /// same process without the process terminating, however this start time - /// will be set per AppDomain. - /// - /// - [Obsolete("Use ProcessStartTimeUtc and convert to local time if needed.. Scheduled removal in v10.0.0.")] - public static DateTime ProcessStartTime - { - get { return s_processStartTimeUtc.ToLocalTime(); } - } - - /// - /// Gets get the UTC start time for the current process. - /// - /// - /// - /// This is the UTC time at which the log4net library was loaded into the - /// AppDomain. Due to reports of a hang in the call to System.Diagnostics.Process.StartTime - /// this is not the start time for the current process. - /// - /// - /// The log4net library should be loaded by an application early during its - /// startup, therefore this start time should be a good approximation for - /// the actual start time. - /// - /// - /// Note that AppDomains may be loaded and unloaded within the - /// same process without the process terminating, however this start time - /// will be set per AppDomain. - /// - /// - public static DateTime ProcessStartTimeUtc - { - get { return s_processStartTimeUtc; } - } - - /// - /// Gets or sets text to output when a null is encountered. - /// - /// - /// - /// Use this value to indicate a null has been encountered while - /// outputting a string representation of an item. - /// - /// - /// The default value is (null). This value can be overridden by specifying - /// a value for the log4net.NullText appSetting in the application's - /// .config file. - /// - /// - public static string NullText - { - get { return s_nullText; } - set { s_nullText = value; } - } - - /// - /// Gets or sets text to output when an unsupported feature is requested. - /// - /// - /// - /// Use this value when an unsupported feature is requested. - /// - /// - /// The default value is NOT AVAILABLE. This value can be overridden by specifying - /// a value for the log4net.NotAvailableText appSetting in the application's - /// .config file. - /// - /// - public static string NotAvailableText - { - get { return s_notAvailableText; } - set { s_notAvailableText = value; } + /// + /// Gets the base directory for this . + /// + /// The base directory path for the current . + /// + /// + /// Gets the base directory for this . + /// + /// + /// The value returned may be either a local file path or a URI. + /// + /// + public static string ApplicationBaseDirectory + { + get + { +#if NETCF +- return System.IO.Path.GetDirectoryName(SystemInfo.EntryAssemblyLocation) + System.IO.Path.DirectorySeparatorChar; +#elif NETSTANDARD1_3 + return Directory.GetCurrentDirectory(); +#else + return AppDomain.CurrentDomain.BaseDirectory; +#endif + } } - /// - /// Gets the assembly location path for the specified assembly. - /// - /// The assembly to get the location for. - /// The location of the assembly. - /// - /// - /// This method does not guarantee to return the correct path - /// to the assembly. If only tries to give an indication as to - /// where the assembly was loaded from. - /// - /// - public static string AssemblyLocationInfo(Assembly myAssembly) - { -#if NETCF - return "Not supported on Microsoft .NET Compact Framework"; -#elif NETSTANDARD1_3 // TODO Assembly.Location available in netstandard1.5 - return "Not supported on .NET Core"; -#else - if (myAssembly.GlobalAssemblyCache) - { - return "Global Assembly Cache"; - } - else - { - try - { -#if NET_4_0 || MONO_4_0 - if (myAssembly.IsDynamic) - { - return "Dynamic Assembly"; - } -#else - if (myAssembly is System.Reflection.Emit.AssemblyBuilder) - { - return "Dynamic Assembly"; - } - else if(myAssembly.GetType().FullName == "System.Reflection.Emit.InternalAssemblyBuilder") - { - return "Dynamic Assembly"; - } -#endif - else - { - // This call requires FileIOPermission for access to the path - // if we don't have permission then we just ignore it and - // carry on. - return myAssembly.Location; - } - } - catch (NotSupportedException) - { - // The location information may be unavailable for dynamic assemblies and a NotSupportedException - // is thrown in those cases. See: http://msdn.microsoft.com/de-de/library/system.reflection.assembly.location.aspx - return "Dynamic Assembly"; - } - catch (TargetInvocationException ex) - { - return "Location Detect Failed (" + ex.Message + ")"; - } - catch (ArgumentException ex) - { - return "Location Detect Failed (" + ex.Message + ")"; - } - catch (System.Security.SecurityException) - { - return "Location Permission Denied"; - } - } -#endif - } - - /// - /// Gets the fully qualified name of the , including - /// the name of the assembly from which the was - /// loaded. - /// - /// The to get the fully qualified name for. - /// The fully qualified name for the . - /// - /// - /// This is equivalent to the Type.AssemblyQualifiedName property, - /// but this method works on the .NET Compact Framework 1.0 as well as - /// the full .NET runtime. - /// - /// - public static string AssemblyQualifiedName(Type type) - { - return type.FullName + ", " -#if NETSTANDARD1_3 - + type.GetTypeInfo().Assembly.FullName; -#else - + type.Assembly.FullName; -#endif - } - - /// - /// Gets the short name of the . - /// - /// The to get the name for. - /// The short name of the . - /// - /// - /// The short name of the assembly is the - /// without the version, culture, or public key. i.e. it is just the - /// assembly's file name without the extension. - /// - /// - /// Use this rather than Assembly.GetName().Name because that - /// is not available on the Compact Framework. - /// - /// - /// Because of a FileIOPermission security demand we cannot do - /// the obvious Assembly.GetName().Name. We are allowed to get - /// the of the assembly so we - /// start from there and strip out just the assembly name. - /// - /// - public static string AssemblyShortName(Assembly myAssembly) - { - string name = myAssembly.FullName; - int offset = name.IndexOf(','); - if (offset > 0) - { - name = name.Substring(0, offset); - } - - return name.Trim(); - - // TODO: Do we need to unescape the assembly name string? - // Doc says '\' is an escape char but has this already been - // done by the string loader? - } - - /// - /// Gets the file name portion of the , including the extension. - /// - /// The to get the file name for. - /// The file name of the assembly. - /// - /// - /// Gets the file name portion of the , including the extension. - /// - /// - public static string AssemblyFileName(Assembly myAssembly) - { -#if NETCF || NETSTANDARD1_3 // TODO Assembly.Location is in netstandard1.5 System.Reflection - // This is not very good because it assumes that only - // the entry assembly can be an EXE. In fact multiple - // EXEs can be loaded in to a process. - - string assemblyShortName = SystemInfo.AssemblyShortName(myAssembly); - string entryAssemblyShortName = System.IO.Path.GetFileNameWithoutExtension(SystemInfo.EntryAssemblyLocation); - - if (string.Compare(assemblyShortName, entryAssemblyShortName, true) == 0) - { - // assembly is entry assembly - return assemblyShortName + ".exe"; - } - else - { - // assembly is not entry assembly - return assemblyShortName + ".dll"; - } -#else - return System.IO.Path.GetFileName(myAssembly.Location); -#endif - } - - /// - /// Loads the type specified in the type string. - /// - /// A sibling type to use to load the type. - /// The name of the type to load. - /// Flag set to true to throw an exception if the type cannot be loaded. - /// true to ignore the case of the type name; otherwise, false. - /// The type loaded or null if it could not be loaded. - /// - /// - /// If the type name is fully qualified, i.e. if contains an assembly name in - /// the type name, the type will be loaded from the system using - /// . - /// - /// - /// If the type name is not fully qualified, it will be loaded from the assembly - /// containing the specified relative type. If the type is not found in the assembly - /// then all the loaded assemblies will be searched for the type. - /// - /// - public static Type GetTypeFromString(Type relativeType, string typeName, bool throwOnError, bool ignoreCase) - { -#if NETSTANDARD1_3 - return GetTypeFromString(relativeType.GetTypeInfo().Assembly, typeName, throwOnError, ignoreCase); -#else - return GetTypeFromString(relativeType.Assembly, typeName, throwOnError, ignoreCase); -#endif - } - -#if !NETSTANDARD1_3 - /// - /// Loads the type specified in the type string. - /// - /// The name of the type to load. - /// Flag set to true to throw an exception if the type cannot be loaded. - /// true to ignore the case of the type name; otherwise, false. - /// The type loaded or null if it could not be loaded. - /// - /// - /// If the type name is fully qualified, i.e. if contains an assembly name in - /// the type name, the type will be loaded from the system using - /// . - /// - /// - /// If the type name is not fully qualified it will be loaded from the - /// assembly that is directly calling this method. If the type is not found - /// in the assembly then all the loaded assemblies will be searched for the type. - /// - /// - public static Type GetTypeFromString(string typeName, bool throwOnError, bool ignoreCase) - { - return GetTypeFromString(Assembly.GetCallingAssembly(), typeName, throwOnError, ignoreCase); - } -#endif - - /// - /// Loads the type specified in the type string. - /// - /// An assembly to load the type from. - /// The name of the type to load. - /// Flag set to true to throw an exception if the type cannot be loaded. - /// true to ignore the case of the type name; otherwise, false. - /// The type loaded or null if it could not be loaded. - /// - /// - /// If the type name is fully qualified, i.e. if contains an assembly name in - /// the type name, the type will be loaded from the system using - /// . - /// - /// - /// If the type name is not fully qualified it will be loaded from the specified - /// assembly. If the type is not found in the assembly then all the loaded assemblies - /// will be searched for the type. - /// - /// - public static Type GetTypeFromString(Assembly relativeAssembly, string typeName, bool throwOnError, bool ignoreCase) - { - // Check if the type name specifies the assembly name - if (typeName.IndexOf(',') == -1) - { - // LogLog.Debug(declaringType, "SystemInfo: Loading type ["+typeName+"] from assembly ["+relativeAssembly.FullName+"]"); -#if NETSTANDARD1_3 - return relativeAssembly.GetType(typeName, throwOnError, ignoreCase); -#elif NETCF - return relativeAssembly.GetType(typeName, throwOnError); -#else - // Attempt to lookup the type from the relativeAssembly - Type type = relativeAssembly.GetType(typeName, false, ignoreCase); - if (type != null) - { - // Found type in relative assembly - // LogLog.Debug(declaringType, "SystemInfo: Loaded type ["+typeName+"] from assembly ["+relativeAssembly.FullName+"]"); - return type; - } - - Assembly[] loadedAssemblies = null; - try - { - loadedAssemblies = AppDomain.CurrentDomain.GetAssemblies(); - } - catch (System.Security.SecurityException) - { - // Insufficient permissions to get the list of loaded assemblies - } - - if (loadedAssemblies != null) - { - Type fallback = null; - - // Search the loaded assemblies for the type - foreach (Assembly assembly in loadedAssemblies) - { - Type t = assembly.GetType(typeName, false, ignoreCase); - if (t != null) - { - // Found type in loaded assembly - LogLog.Debug(declaringType, "Loaded type [" + typeName + "] from assembly [" + assembly.FullName + "] by searching loaded assemblies."); - if (assembly.GlobalAssemblyCache) - { - fallback = t; - } - else - { - return t; - } - } - } - - if (fallback != null) + /// + /// Gets the path to the configuration file for the current . + /// + /// The path to the configuration file for the current . + /// + /// + /// The .NET Compact Framework 1.0 does not have a concept of a configuration + /// file. For this runtime, we use the entry assembly location as the root for + /// the configuration file name. + /// + /// + /// The value returned may be either a local file path or a URI. + /// + /// + public static string ConfigurationFileLocation + { + get + { +#if NETCF || NETSTANDARD + return SystemInfo.EntryAssemblyLocation+".config"; +#else + return AppDomain.CurrentDomain.SetupInformation.ConfigurationFile; +#endif + } + } + + /// + /// Gets the path to the file that first executed in the current . + /// + /// The path to the entry assembly. + /// + /// + /// Gets the path to the file that first executed in the current . + /// + /// + public static string EntryAssemblyLocation + { + get + { +#if NETCF + return SystemInfo.NativeEntryAssemblyLocation; +#elif NETSTANDARD1_3 // TODO GetEntryAssembly is available for netstandard1.5 + return AppContext.BaseDirectory; +#else + return Assembly.GetEntryAssembly().Location; +#endif + } + } + + /// + /// Gets the ID of the current thread. + /// + /// The ID of the current thread. + /// + /// + /// On the .NET framework, the AppDomain.GetCurrentThreadId method + /// is used to obtain the thread ID for the current thread. This is the + /// operating system ID for the thread. + /// + /// + /// On the .NET Compact Framework 1.0 it is not possible to get the + /// operating system thread ID for the current thread. The native method + /// GetCurrentThreadId is implemented inline in a header file + /// and cannot be called. + /// + /// + /// On the .NET Framework 2.0 the Thread.ManagedThreadId is used as this + /// gives a stable id unrelated to the operating system thread ID which may + /// change if the runtime is using fibers. + /// + /// + public static int CurrentThreadId + { + get + { +#if NETCF_1_0 + return System.Threading.Thread.CurrentThread.GetHashCode(); +#elif NET_2_0 || NETCF_2_0 || MONO_2_0 || MONO_3_5 || MONO_4_0 || NETSTANDARD + return System.Threading.Thread.CurrentThread.ManagedThreadId; +#else + return AppDomain.GetCurrentThreadId(); +#endif + } + } + + /// + /// Get the host name or machine name for the current machine + /// + /// + /// The hostname or machine name + /// + /// + /// + /// Get the host name or machine name for the current machine + /// + /// + /// The host name () or + /// the machine name (Environment.MachineName) for + /// the current machine, or if neither of these are available + /// then NOT AVAILABLE is returned. + /// + /// + public static string HostName + { + get + { + if (s_hostName == null) + { + + // Get the DNS host name of the current machine + try + { + // Lookup the host name + s_hostName = System.Net.Dns.GetHostName(); + } + catch (System.Net.Sockets.SocketException) + { + LogLog.Debug(declaringType, "Socket exception occurred while getting the dns hostname. Error Ignored."); + } + catch (System.Security.SecurityException) { - return fallback; - } - } - - // Didn't find the type - if (throwOnError) - { - throw new TypeLoadException("Could not load type [" + typeName + "]. Tried assembly [" + relativeAssembly.FullName + "] and all loaded assemblies"); - } - - return null; -#endif - } - else - { - // Includes explicit assembly name - // LogLog.Debug(declaringType, "SystemInfo: Loading type ["+typeName+"] from global Type"); -#if NETCF - // In NETCF 2 and 3 arg versions seem to behave differently - // https://issues.apache.org/jira/browse/LOG4NET-113 - return Type.GetType(typeName, throwOnError); -#else - return Type.GetType(typeName, throwOnError, ignoreCase); -#endif - } - } - - /// - /// Generate a new guid. - /// - /// A new Guid. - /// - /// - /// Generate a new guid. - /// - /// - public static Guid NewGuid() - { -#if NETCF_1_0 - return PocketGuid.NewGuid(); -#else - return Guid.NewGuid(); -#endif - } - - /// - /// Create an . - /// - /// The name of the parameter that caused the exception. - /// The value of the argument that causes this exception. - /// The message that describes the error. - /// the ArgumentOutOfRangeException object. - /// - /// - /// Create a new instance of the class - /// with a specified error message, the parameter name, and the value - /// of the argument. - /// - /// - /// The Compact Framework does not support the 3 parameter constructor for the - /// type. This method provides an - /// implementation that works for all platforms. - /// - /// - public static ArgumentOutOfRangeException CreateArgumentOutOfRangeException(string parameterName, object actualValue, string message) - { -#if NETCF_1_0 - return new ArgumentOutOfRangeException(message + " [param=" + parameterName + "] [value=" + actualValue + "]"); -#elif NETCF_2_0 - return new ArgumentOutOfRangeException(parameterName, message + " [value=" + actualValue + "]"); -#else - return new ArgumentOutOfRangeException(parameterName, actualValue, message); -#endif - } - - /// - /// Parse a string into an value. - /// - /// the string to parse. - /// out param where the parsed value is placed. - /// true if the string was able to be parsed into an integer. - /// - /// - /// Attempts to parse the string into an integer. If the string cannot - /// be parsed then this method returns false. The method does not throw an exception. - /// - /// - public static bool TryParse(string s, out int val) - { -#if NETCF - val = 0; - try - { - val = int.Parse(s, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture); - return true; - } - catch - { - } - - return false; -#else - // Initialise out param - val = 0; - - try - { - double doubleVal; - if (double.TryParse(s, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out doubleVal)) - { - val = Convert.ToInt32(doubleVal); - return true; - } - } - catch - { - // Ignore exception, just return false - } - - return false; -#endif - } - - /// - /// Parse a string into an value. - /// - /// the string to parse. - /// out param where the parsed value is placed. - /// true if the string was able to be parsed into an integer. - /// - /// - /// Attempts to parse the string into an integer. If the string cannot - /// be parsed then this method returns false. The method does not throw an exception. - /// - /// - public static bool TryParse(string s, out long val) - { -#if NETCF - val = 0; - try - { - val = long.Parse(s, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture); - return true; - } - catch - { - } - - return false; -#else - // Initialise out param - val = 0; - - try - { - double doubleVal; - if (double.TryParse(s, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out doubleVal)) - { - val = Convert.ToInt64(doubleVal); - return true; - } - } - catch - { - // Ignore exception, just return false - } - - return false; -#endif - } - - /// - /// Parse a string into an value. - /// - /// the string to parse. - /// out param where the parsed value is placed. - /// true if the string was able to be parsed into an integer. - /// - /// - /// Attempts to parse the string into an integer. If the string cannot - /// be parsed then this method returns false. The method does not throw an exception. - /// - /// - public static bool TryParse(string s, out short val) - { -#if NETCF - val = 0; - try - { - val = short.Parse(s, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture); - return true; - } - catch - { - } - - return false; -#else - // Initialise out param - val = 0; - - try - { - double doubleVal; - if (double.TryParse(s, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out doubleVal)) - { - val = Convert.ToInt16(doubleVal); - return true; - } - } - catch - { - // Ignore exception, just return false - } - - return false; -#endif - } - - /// - /// Lookup an application setting. - /// - /// the application settings key to lookup. - /// the value for the key, or null. - /// - /// - /// Configuration APIs are not supported under the Compact Framework. - /// - /// - public static string GetAppSetting(string key) - { - try - { -#if NETCF || NETSTANDARD1_3 - // Configuration APIs are not suported under the Compact Framework -#elif NET_2_0 - return ConfigurationManager.AppSettings[key]; -#else - return ConfigurationSettings.AppSettings[key]; -#endif - } - catch (Exception ex) - { - // If an exception is thrown here then it looks like the config file does not parse correctly. - LogLog.Error(declaringType, "Exception while reading ConfigurationSettings. Check your .config file is well formed XML.", ex); - } - - return null; - } - - /// - /// Convert a path into a fully qualified local file path. - /// - /// The path to convert. - /// The fully qualified path. - /// - /// - /// Converts the path specified to a fully - /// qualified path. If the path is relative it is - /// taken as relative from the application base - /// directory. - /// - /// - /// The path specified must be a local file path, a URI is not supported. - /// - /// - public static string ConvertToFullPath(string path) - { - if (path == null) - { - throw new ArgumentNullException("path"); - } - - string baseDirectory = string.Empty; - try - { - string applicationBaseDirectory = SystemInfo.ApplicationBaseDirectory; - if (applicationBaseDirectory != null) - { - // applicationBaseDirectory may be a URI not a local file path - Uri applicationBaseDirectoryUri = new Uri(applicationBaseDirectory); - if (applicationBaseDirectoryUri.IsFile) - { - baseDirectory = applicationBaseDirectoryUri.LocalPath; - } - } - } - catch - { - // Ignore URI exceptions & SecurityExceptions from SystemInfo.ApplicationBaseDirectory - } - - if (baseDirectory != null && baseDirectory.Length > 0) - { - // Note that Path.Combine will return the second path if it is rooted - return Path.GetFullPath(Path.Combine(baseDirectory, path)); - } - - return Path.GetFullPath(path); - } - - /// - /// Creates a new case-insensitive instance of the class with the default initial capacity. - /// - /// A new case-insensitive instance of the class with the default initial capacity. - /// - /// - /// The new Hashtable instance uses the default load factor, the CaseInsensitiveHashCodeProvider, and the CaseInsensitiveComparer. - /// - /// - public static Hashtable CreateCaseInsensitiveHashtable() - { -#if NETCF_1_0 - return new Hashtable(CaseInsensitiveHashCodeProvider.Default, CaseInsensitiveComparer.Default); -#elif NETCF_2_0 || NET_2_0 || MONO_2_0 || MONO_3_5 || MONO_4_0 - return new Hashtable(StringComparer.OrdinalIgnoreCase); -#else - return System.Collections.Specialized.CollectionsUtil.CreateCaseInsensitiveHashtable(); -#endif - } - - /// - /// Tests two strings for equality, the ignoring case. - /// - /// - /// If the platform permits, culture information is ignored completely (ordinal comparison). - /// The aim of this method is to provide a fast comparison that deals with null and ignores different casing. - /// It is not supposed to deal with various, culture-specific habits. - /// Use it to compare against pure ASCII constants, like keywords etc. - /// - /// The one string. - /// The other string. - /// true if the strings are equal, false otherwise. - public static bool EqualsIgnoringCase(string a, string b) - { -#if NET_1_0 || NET_1_1 || NETCF_1_0 - return string.Compare(a, b, true, System.Globalization.CultureInfo.InvariantCulture) == 0 -#elif NETSTANDARD1_3 - return CultureInfo.InvariantCulture.CompareInfo.Compare(a, b, CompareOptions.IgnoreCase) == 0; -#else // >= .NET-2.0 - return string.Equals(a, b, StringComparison.OrdinalIgnoreCase); -#endif + // We may get a security exception looking up the hostname + // You must have Unrestricted DnsPermission to access resource + LogLog.Debug(declaringType, "Security exception occurred while getting the dns hostname. Error Ignored."); + } + catch (Exception ex) + { + LogLog.Debug(declaringType, "Some other exception occurred while getting the dns hostname. Error Ignored.", ex); + } + + // Get the NETBIOS machine name of the current machine + if (s_hostName == null || s_hostName.Length == 0) + { + try + { +#if NETSTANDARD1_3 + s_hostName = Environment.GetEnvironmentVariable("COMPUTERNAME"); +#elif (!SSCLI && !NETCF) + s_hostName = Environment.MachineName; +#endif + } + catch(InvalidOperationException) + { + } + catch(System.Security.SecurityException) + { + // We may get a security exception looking up the machine name + // You must have Unrestricted EnvironmentPermission to access resource + } + } + + // Couldn't find a value + if (s_hostName == null || s_hostName.Length == 0) + { + s_hostName = s_notAvailableText; + LogLog.Debug(declaringType, "Could not determine the hostname. Error Ignored. Empty host name will be used"); + } + } + return s_hostName; + } + } + + /// + /// Get this application's friendly name + /// + /// + /// The friendly name of this application as a string + /// + /// + /// + /// If available the name of the application is retrieved from + /// the AppDomain using AppDomain.CurrentDomain.FriendlyName. + /// + /// + /// Otherwise the file name of the entry assembly is used. + /// + /// + public static string ApplicationFriendlyName + { + get + { + if (s_appFriendlyName == null) + { + try + { +#if !NETCF && !NETSTANDARD1_3 + s_appFriendlyName = AppDomain.CurrentDomain.FriendlyName; +#endif + } + catch(System.Security.SecurityException) + { + // This security exception will occur if the caller does not have + // some undefined set of SecurityPermission flags. + LogLog.Debug(declaringType, "Security exception while trying to get current domain friendly name. Error Ignored."); + } + + if (s_appFriendlyName == null || s_appFriendlyName.Length == 0) + { + try + { + string assemblyLocation = EntryAssemblyLocation; + s_appFriendlyName = Path.GetFileName(assemblyLocation); + } + catch(System.Security.SecurityException) + { + // Caller needs path discovery permission + } + } + + if (s_appFriendlyName == null || s_appFriendlyName.Length == 0) + { + s_appFriendlyName = s_notAvailableText; + } + } + return s_appFriendlyName; + } + } + + /// + /// Get the start time for the current process. + /// + /// + /// + /// This is the time at which the log4net library was loaded into the + /// AppDomain. Due to reports of a hang in the call to System.Diagnostics.Process.StartTime + /// this is not the start time for the current process. + /// + /// + /// The log4net library should be loaded by an application early during its + /// startup, therefore this start time should be a good approximation for + /// the actual start time. + /// + /// + /// Note that AppDomains may be loaded and unloaded within the + /// same process without the process terminating, however this start time + /// will be set per AppDomain. + /// + /// + [Obsolete("Use ProcessStartTimeUtc and convert to local time if needed.")] + public static DateTime ProcessStartTime + { + get { return s_processStartTimeUtc.ToLocalTime(); } } -#if NETCF - private static string NativeEntryAssemblyLocation - { - get - { - StringBuilder moduleName = null; - - IntPtr moduleHandle = GetModuleHandle(IntPtr.Zero); - - if (moduleHandle != IntPtr.Zero) - { - moduleName = new StringBuilder(255); - if (GetModuleFileName(moduleHandle, moduleName, moduleName.Capacity) == 0) - { - throw new NotSupportedException(NativeError.GetLastError().ToString()); - } - } - else - { - throw new NotSupportedException(NativeError.GetLastError().ToString()); - } - - return moduleName.ToString(); - } - } - - [DllImport("CoreDll.dll", SetLastError=true, CharSet=CharSet.Unicode)] - private static extern IntPtr GetModuleHandle(IntPtr ModuleName); - - [DllImport("CoreDll.dll", SetLastError=true, CharSet=CharSet.Unicode)] - private static extern Int32 GetModuleFileName( - IntPtr hModule, - StringBuilder ModuleName, - Int32 cch); - -#endif - - /// - /// Gets an empty array of types. - /// - /// - /// - /// The Type.EmptyTypes field is not available on - /// the .NET Compact Framework 1.0. - /// - /// + /// + /// Get the UTC start time for the current process. + /// + /// + /// + /// This is the UTC time at which the log4net library was loaded into the + /// AppDomain. Due to reports of a hang in the call to System.Diagnostics.Process.StartTime + /// this is not the start time for the current process. + /// + /// + /// The log4net library should be loaded by an application early during its + /// startup, therefore this start time should be a good approximation for + /// the actual start time. + /// + /// + /// Note that AppDomains may be loaded and unloaded within the + /// same process without the process terminating, however this start time + /// will be set per AppDomain. + /// + /// + public static DateTime ProcessStartTimeUtc + { + get { return s_processStartTimeUtc; } + } + + /// + /// Text to output when a null is encountered. + /// + /// + /// + /// Use this value to indicate a null has been encountered while + /// outputting a string representation of an item. + /// + /// + /// The default value is (null). This value can be overridden by specifying + /// a value for the log4net.NullText appSetting in the application's + /// .config file. + /// + /// + public static string NullText + { + get { return s_nullText; } + set { s_nullText = value; } + } + + /// + /// Text to output when an unsupported feature is requested. + /// + /// + /// + /// Use this value when an unsupported feature is requested. + /// + /// + /// The default value is NOT AVAILABLE. This value can be overridden by specifying + /// a value for the log4net.NotAvailableText appSetting in the application's + /// .config file. + /// + /// + public static string NotAvailableText + { + get { return s_notAvailableText; } + set { s_notAvailableText = value; } + } + + /// + /// Gets the assembly location path for the specified assembly. + /// + /// The assembly to get the location for. + /// The location of the assembly. + /// + /// + /// This method does not guarantee to return the correct path + /// to the assembly. If only tries to give an indication as to + /// where the assembly was loaded from. + /// + /// + public static string AssemblyLocationInfo(Assembly myAssembly) + { +#if NETCF + return "Not supported on Microsoft .NET Compact Framework"; +#elif NETSTANDARD1_3 + return "Not supported on .NET Core"; +#else + if (myAssembly.GlobalAssemblyCache) + { + return "Global Assembly Cache"; + } + else + { + try + { +#if NET_4_0 || MONO_4_0 + if (myAssembly.IsDynamic) + { + return "Dynamic Assembly"; + } +#else +#if !NETSTANDARD2_0 + if (myAssembly is System.Reflection.Emit.AssemblyBuilder) + { + return "Dynamic Assembly"; + } +#endif + + if (myAssembly.GetType().FullName == "System.Reflection.Emit.InternalAssemblyBuilder") + { + return "Dynamic Assembly"; + } +#endif + else + { + // This call requires FileIOPermission for access to the path + // if we don't have permission then we just ignore it and + // carry on. + return myAssembly.Location; + } + } + catch (NotSupportedException) + { + // The location information may be unavailable for dynamic assemblies and a NotSupportedException + // is thrown in those cases. See: http://msdn.microsoft.com/de-de/library/system.reflection.assembly.location.aspx + return "Dynamic Assembly"; + } + catch (TargetInvocationException ex) + { + return "Location Detect Failed (" + ex.Message + ")"; + } + catch (ArgumentException ex) + { + return "Location Detect Failed (" + ex.Message + ")"; + } + catch (System.Security.SecurityException) + { + return "Location Permission Denied"; + } + } +#endif + } + + /// + /// Gets the fully qualified name of the , including + /// the name of the assembly from which the was + /// loaded. + /// + /// The to get the fully qualified name for. + /// The fully qualified name for the . + /// + /// + /// This is equivalent to the Type.AssemblyQualifiedName property, + /// but this method works on the .NET Compact Framework 1.0 as well as + /// the full .NET runtime. + /// + /// + public static string AssemblyQualifiedName(Type type) + { + return type.FullName + ", " +#if NETSTANDARD1_3 + + type.GetTypeInfo().Assembly.FullName; +#else + + type.Assembly.FullName; +#endif + } + + /// + /// Gets the short name of the . + /// + /// The to get the name for. + /// The short name of the . + /// + /// + /// The short name of the assembly is the + /// without the version, culture, or public key. i.e. it is just the + /// assembly's file name without the extension. + /// + /// + /// Use this rather than Assembly.GetName().Name because that + /// is not available on the Compact Framework. + /// + /// + /// Because of a FileIOPermission security demand we cannot do + /// the obvious Assembly.GetName().Name. We are allowed to get + /// the of the assembly so we + /// start from there and strip out just the assembly name. + /// + /// + public static string AssemblyShortName(Assembly myAssembly) + { + string name = myAssembly.FullName; + int offset = name.IndexOf(','); + if (offset > 0) + { + name = name.Substring(0, offset); + } + return name.Trim(); + + // TODO: Do we need to unescape the assembly name string? + // Doc says '\' is an escape char but has this already been + // done by the string loader? + } + + /// + /// Gets the file name portion of the , including the extension. + /// + /// The to get the file name for. + /// The file name of the assembly. + /// + /// + /// Gets the file name portion of the , including the extension. + /// + /// + public static string AssemblyFileName(Assembly myAssembly) + { +#if NETCF || NETSTANDARD1_3 // TODO Assembly.Location is in netstandard1.5 System.Reflection + // This is not very good because it assumes that only + // the entry assembly can be an EXE. In fact multiple + // EXEs can be loaded in to a process. + + string assemblyShortName = SystemInfo.AssemblyShortName(myAssembly); + string entryAssemblyShortName = System.IO.Path.GetFileNameWithoutExtension(SystemInfo.EntryAssemblyLocation); + + if (string.Compare(assemblyShortName, entryAssemblyShortName, true) == 0) + { + // assembly is entry assembly + return assemblyShortName + ".exe"; + } + else + { + // assembly is not entry assembly + return assemblyShortName + ".dll"; + } +#else + return Path.GetFileName(myAssembly.Location); +#endif + } + + /// + /// Loads the type specified in the type string. + /// + /// A sibling type to use to load the type. + /// The name of the type to load. + /// Flag set to true to throw an exception if the type cannot be loaded. + /// true to ignore the case of the type name; otherwise, false + /// The type loaded or null if it could not be loaded. + /// + /// + /// If the type name is fully qualified, i.e. if contains an assembly name in + /// the type name, the type will be loaded from the system using + /// . + /// + /// + /// If the type name is not fully qualified, it will be loaded from the assembly + /// containing the specified relative type. If the type is not found in the assembly + /// then all the loaded assemblies will be searched for the type. + /// + /// + public static Type GetTypeFromString(Type relativeType, string typeName, bool throwOnError, bool ignoreCase) + { +#if NETSTANDARD1_3 + return GetTypeFromString(relativeType.GetTypeInfo().Assembly, typeName, throwOnError, ignoreCase); +#else + return GetTypeFromString(relativeType.Assembly, typeName, throwOnError, ignoreCase); +#endif + } + +#if !NETSTANDARD1_3 + /// + /// Loads the type specified in the type string. + /// + /// The name of the type to load. + /// Flag set to true to throw an exception if the type cannot be loaded. + /// true to ignore the case of the type name; otherwise, false + /// The type loaded or null if it could not be loaded. + /// + /// + /// If the type name is fully qualified, i.e. if contains an assembly name in + /// the type name, the type will be loaded from the system using + /// . + /// + /// + /// If the type name is not fully qualified it will be loaded from the + /// assembly that is directly calling this method. If the type is not found + /// in the assembly then all the loaded assemblies will be searched for the type. + /// + /// + public static Type GetTypeFromString(string typeName, bool throwOnError, bool ignoreCase) + { + return GetTypeFromString(Assembly.GetCallingAssembly(), typeName, throwOnError, ignoreCase); + } +#endif + + /// + /// Loads the type specified in the type string. + /// + /// An assembly to load the type from. + /// The name of the type to load. + /// Flag set to true to throw an exception if the type cannot be loaded. + /// true to ignore the case of the type name; otherwise, false + /// The type loaded or null if it could not be loaded. + /// + /// + /// If the type name is fully qualified, i.e. if contains an assembly name in + /// the type name, the type will be loaded from the system using + /// . + /// + /// + /// If the type name is not fully qualified it will be loaded from the specified + /// assembly. If the type is not found in the assembly then all the loaded assemblies + /// will be searched for the type. + /// + /// + public static Type GetTypeFromString(Assembly relativeAssembly, string typeName, bool throwOnError, bool ignoreCase) + { + // Check if the type name specifies the assembly name + if(typeName.IndexOf(',') == -1) + { + //LogLog.Debug(declaringType, "SystemInfo: Loading type ["+typeName+"] from assembly ["+relativeAssembly.FullName+"]"); +#if NETSTANDARD1_3 + return relativeAssembly.GetType(typeName, throwOnError, ignoreCase); +#elif NETCF + return relativeAssembly.GetType(typeName, throwOnError); +#else + // Attempt to lookup the type from the relativeAssembly + Type type = relativeAssembly.GetType(typeName, false, ignoreCase); + if (type != null) + { + // Found type in relative assembly + //LogLog.Debug(declaringType, "SystemInfo: Loaded type ["+typeName+"] from assembly ["+relativeAssembly.FullName+"]"); + return type; + } + + Assembly[] loadedAssemblies = null; + try + { + loadedAssemblies = AppDomain.CurrentDomain.GetAssemblies(); + } + catch(System.Security.SecurityException) + { + // Insufficient permissions to get the list of loaded assemblies + } + + if (loadedAssemblies != null) + { + Type fallback = null; + // Search the loaded assemblies for the type + foreach (Assembly assembly in loadedAssemblies) + { + Type t = assembly.GetType(typeName, false, ignoreCase); + if (t != null) + { + // Found type in loaded assembly + LogLog.Debug(declaringType, "Loaded type [" + typeName + "] from assembly [" + assembly.FullName + "] by searching loaded assemblies."); + if (assembly.GlobalAssemblyCache) + { + fallback = t; + } + else + { + return t; + } + } + } + if (fallback != null) + { + return fallback; + } + } + + // Didn't find the type + if (throwOnError) + { + throw new TypeLoadException("Could not load type [" + typeName + "]. Tried assembly [" + relativeAssembly.FullName + "] and all loaded assemblies"); + } + return null; +#endif + } + else + { + // Includes explicit assembly name + // LogLog.Debug(declaringType, "SystemInfo: Loading type ["+typeName+"] from global Type"); + +#if NETCF + // In NETCF 2 and 3 arg versions seem to behave differently + // https://issues.apache.org/jira/browse/LOG4NET-113 + return Type.GetType(typeName, throwOnError); +#else + return Type.GetType(typeName, throwOnError, ignoreCase); +#endif + } + } + + + /// + /// Generate a new guid + /// + /// A new Guid + /// + /// + /// Generate a new guid + /// + /// + public static Guid NewGuid() + { +#if NETCF_1_0 + return PocketGuid.NewGuid(); +#else + return Guid.NewGuid(); +#endif + } + + /// + /// Create an + /// + /// The name of the parameter that caused the exception + /// The value of the argument that causes this exception + /// The message that describes the error + /// the ArgumentOutOfRangeException object + /// + /// + /// Create a new instance of the class + /// with a specified error message, the parameter name, and the value + /// of the argument. + /// + /// + /// The Compact Framework does not support the 3 parameter constructor for the + /// type. This method provides an + /// implementation that works for all platforms. + /// + /// + public static ArgumentOutOfRangeException CreateArgumentOutOfRangeException(string parameterName, object actualValue, string message) + { +#if NETCF_1_0 + return new ArgumentOutOfRangeException(message + " [param=" + parameterName + "] [value=" + actualValue + "]"); +#elif NETCF_2_0 + return new ArgumentOutOfRangeException(parameterName, message + " [value=" + actualValue + "]"); +#else + return new ArgumentOutOfRangeException(parameterName, actualValue, message); +#endif + } + + + /// + /// Parse a string into an value + /// + /// the string to parse + /// out param where the parsed value is placed + /// true if the string was able to be parsed into an integer + /// + /// + /// Attempts to parse the string into an integer. If the string cannot + /// be parsed then this method returns false. The method does not throw an exception. + /// + /// + public static bool TryParse(string s, out int val) + { +#if NETCF + val = 0; + try + { + val = int.Parse(s, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture); + return true; + } + catch + { + } + + return false; +#else + // Initialise out param + val = 0; + + try + { + double doubleVal; + if (Double.TryParse(s, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out doubleVal)) + { + val = Convert.ToInt32(doubleVal); + return true; + } + } + catch + { + // Ignore exception, just return false + } + + return false; +#endif + } + + /// + /// Parse a string into an value + /// + /// the string to parse + /// out param where the parsed value is placed + /// true if the string was able to be parsed into an integer + /// + /// + /// Attempts to parse the string into an integer. If the string cannot + /// be parsed then this method returns false. The method does not throw an exception. + /// + /// + public static bool TryParse(string s, out long val) + { +#if NETCF + val = 0; + try + { + val = long.Parse(s, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture); + return true; + } + catch + { + } + + return false; +#else + // Initialise out param + val = 0; + + try + { + double doubleVal; + if (Double.TryParse(s, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out doubleVal)) + { + val = Convert.ToInt64(doubleVal); + return true; + } + } + catch + { + // Ignore exception, just return false + } + + return false; +#endif + } + + /// + /// Parse a string into an value + /// + /// the string to parse + /// out param where the parsed value is placed + /// true if the string was able to be parsed into an integer + /// + /// + /// Attempts to parse the string into an integer. If the string cannot + /// be parsed then this method returns false. The method does not throw an exception. + /// + /// + public static bool TryParse(string s, out short val) + { +#if NETCF + val = 0; + try + { + val = short.Parse(s, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture); + return true; + } + catch + { + } + + return false; +#else + // Initialise out param + val = 0; + + try + { + double doubleVal; + if (Double.TryParse(s, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out doubleVal)) + { + val = Convert.ToInt16(doubleVal); + return true; + } + } + catch + { + // Ignore exception, just return false + } + + return false; +#endif + } + + /// + /// Lookup an application setting + /// + /// the application settings key to lookup + /// the value for the key, or null + /// + /// + /// Configuration APIs are not supported under the Compact Framework + /// + /// + public static string GetAppSetting(string key) + { + try + { +#if NETCF || NETSTANDARD1_3 + // Configuration APIs are not suported under the Compact Framework +#elif NET_2_0 || NETSTANDARD2_0 + return ConfigurationManager.AppSettings[key]; +#else + return ConfigurationSettings.AppSettings[key]; +#endif + } + catch(Exception ex) + { + // If an exception is thrown here then it looks like the config file does not parse correctly. + LogLog.Error(declaringType, "Exception while reading ConfigurationSettings. Check your .config file is well formed XML.", ex); + } + return null; + } + + /// + /// Convert a path into a fully qualified local file path. + /// + /// The path to convert. + /// The fully qualified path. + /// + /// + /// Converts the path specified to a fully + /// qualified path. If the path is relative it is + /// taken as relative from the application base + /// directory. + /// + /// + /// The path specified must be a local file path, a URI is not supported. + /// + /// + public static string ConvertToFullPath(string path) + { + if (path == null) + { + throw new ArgumentNullException("path"); + } + + string baseDirectory = string.Empty; + try + { + string applicationBaseDirectory = ApplicationBaseDirectory; + if (applicationBaseDirectory != null) + { + // applicationBaseDirectory may be a URI not a local file path + Uri applicationBaseDirectoryUri = new Uri(applicationBaseDirectory); + if (applicationBaseDirectoryUri.IsFile) + { + baseDirectory = applicationBaseDirectoryUri.LocalPath; + } + } + } + catch + { + // Ignore URI exceptions & SecurityExceptions from SystemInfo.ApplicationBaseDirectory + } + + if (baseDirectory != null && baseDirectory.Length > 0) + { + // Note that Path.Combine will return the second path if it is rooted + return Path.GetFullPath(Path.Combine(baseDirectory, path)); + } + return Path.GetFullPath(path); + } + + /// + /// Creates a new case-insensitive instance of the class with the default initial capacity. + /// + /// A new case-insensitive instance of the class with the default initial capacity + /// + /// + /// The new Hashtable instance uses the default load factor, the CaseInsensitiveHashCodeProvider, and the CaseInsensitiveComparer. + /// + /// + public static Hashtable CreateCaseInsensitiveHashtable() + { +#if NETCF_1_0 + return new Hashtable(CaseInsensitiveHashCodeProvider.Default, CaseInsensitiveComparer.Default); +#elif NETCF_2_0 || NET_2_0 || MONO_2_0 || MONO_3_5 || MONO_4_0 + return new Hashtable(StringComparer.OrdinalIgnoreCase); +#else + return System.Collections.Specialized.CollectionsUtil.CreateCaseInsensitiveHashtable(); +#endif + } + + /// + /// Tests two strings for equality, the ignoring case. + /// + /// + /// If the platform permits, culture information is ignored completely (ordinal comparison). + /// The aim of this method is to provide a fast comparison that deals with null and ignores different casing. + /// It is not supposed to deal with various, culture-specific habits. + /// Use it to compare against pure ASCII constants, like keywords etc. + /// + /// The one string. + /// The other string. + /// true if the strings are equal, false otherwise. + public static Boolean EqualsIgnoringCase(String a, String b) + { +#if NET_1_0 || NET_1_1 || NETCF_1_0 + return string.Compare(a, b, true, System.Globalization.CultureInfo.InvariantCulture) == 0 +#elif NETSTANDARD1_3 + return CultureInfo.InvariantCulture.CompareInfo.Compare(a, b, CompareOptions.IgnoreCase) == 0; +#else // >= .NET-2.0 + return String.Equals(a, b, StringComparison.OrdinalIgnoreCase); +#endif + } + +#if NETCF + private static string NativeEntryAssemblyLocation + { + get + { + StringBuilder moduleName = null; + + IntPtr moduleHandle = GetModuleHandle(IntPtr.Zero); + + if (moduleHandle != IntPtr.Zero) + { + moduleName = new StringBuilder(255); + if (GetModuleFileName(moduleHandle, moduleName, moduleName.Capacity) == 0) + { + throw new NotSupportedException(NativeError.GetLastError().ToString()); + } + } + else + { + throw new NotSupportedException(NativeError.GetLastError().ToString()); + } + + return moduleName.ToString(); + } + } + + [DllImport("CoreDll.dll", SetLastError=true, CharSet=CharSet.Unicode)] + private static extern IntPtr GetModuleHandle(IntPtr ModuleName); + + [DllImport("CoreDll.dll", SetLastError=true, CharSet=CharSet.Unicode)] + private static extern Int32 GetModuleFileName( + IntPtr hModule, + StringBuilder ModuleName, + Int32 cch); + +#endif + + /// + /// Gets an empty array of types. + /// + /// + /// + /// The Type.EmptyTypes field is not available on + /// the .NET Compact Framework 1.0. + /// + /// public static readonly Type[] EmptyTypes = new Type[0]; - /// - /// The fully qualified type of the SystemInfo class. - /// - /// - /// Used by the internal logger to record the Type of the - /// log message. - /// - private static readonly Type declaringType = typeof(SystemInfo); - - /// - /// Cache the host name for the current machine. - /// - private static string s_hostName; - - /// - /// Cache the application friendly name. - /// - private static string s_appFriendlyName; - - /// - /// Text to output when a null is encountered. - /// - private static string s_nullText; - - /// - /// Text to output when an unsupported feature is requested. - /// - private static string s_notAvailableText; - - /// - /// Start time for the current process. - /// + /// + /// The fully qualified type of the SystemInfo class. + /// + /// + /// Used by the internal logger to record the Type of the + /// log message. + /// + private static readonly Type declaringType = typeof(SystemInfo); + + /// + /// Cache the host name for the current machine + /// + private static string s_hostName; + + /// + /// Cache the application friendly name + /// + private static string s_appFriendlyName; + + /// + /// Text to output when a null is encountered. + /// + private static string s_nullText; + + /// + /// Text to output when an unsupported feature is requested. + /// + private static string s_notAvailableText; + + /// + /// Start time for the current process. + /// private static DateTime s_processStartTimeUtc = DateTime.UtcNow; -#if NETCF_1_0 - /// - /// Generate GUIDs on the .NET Compact Framework. - /// - public class PocketGuid - { - // guid variant types - private enum GuidVariant - { - ReservedNCS = 0x00, - Standard = 0x02, - ReservedMicrosoft = 0x06, - ReservedFuture = 0x07 - } - - // guid version types - private enum GuidVersion - { - TimeBased = 0x01, - Reserved = 0x02, - NameBased = 0x03, - Random = 0x04 - } - - // constants that are used in the class - private class Const - { - // number of bytes in guid - public const int ByteArraySize = 16; - - // multiplex variant info - public const int VariantByte = 8; - public const int VariantByteMask = 0x3f; - public const int VariantByteShift = 6; - - // multiplex version info - public const int VersionByte = 7; - public const int VersionByteMask = 0x0f; - public const int VersionByteShift = 4; - } - - // imports for the crypto api functions - private class WinApi - { - public const uint PROV_RSA_FULL = 1; - public const uint CRYPT_VERIFYCONTEXT = 0xf0000000; - - [DllImport("CoreDll.dll")] - public static extern bool CryptAcquireContext( - ref IntPtr phProv, string pszContainer, string pszProvider, - uint dwProvType, uint dwFlags); - - [DllImport("CoreDll.dll")] - public static extern bool CryptReleaseContext( - IntPtr hProv, uint dwFlags); - - [DllImport("CoreDll.dll")] - public static extern bool CryptGenRandom( - IntPtr hProv, int dwLen, byte[] pbBuffer); - } - - // all static methods - private PocketGuid() - { - } - - /// - /// Return a new System.Guid object. - /// - public static Guid NewGuid() - { - IntPtr hCryptProv = IntPtr.Zero; - Guid guid = Guid.Empty; - - try - { - // holds random bits for guid - byte[] bits = new byte[Const.ByteArraySize]; - - // get crypto provider handle - if (!WinApi.CryptAcquireContext(ref hCryptProv, null, null, - WinApi.PROV_RSA_FULL, WinApi.CRYPT_VERIFYCONTEXT)) - { - throw new SystemException( - "Failed to acquire cryptography handle."); - } - - // generate a 128 bit (16 byte) cryptographically random number - if (!WinApi.CryptGenRandom(hCryptProv, bits.Length, bits)) - { - throw new SystemException( - "Failed to generate cryptography random bytes."); - } - - // set the variant - bits[Const.VariantByte] &= Const.VariantByteMask; - bits[Const.VariantByte] |= - ((int)GuidVariant.Standard << Const.VariantByteShift); - - // set the version - bits[Const.VersionByte] &= Const.VersionByteMask; - bits[Const.VersionByte] |= - ((int)GuidVersion.Random << Const.VersionByteShift); - - // create the new System.Guid object - guid = new Guid(bits); - } - finally - { - // release the crypto provider handle - if (hCryptProv != IntPtr.Zero) - WinApi.CryptReleaseContext(hCryptProv, 0); - } - - return guid; - } - } -#endif - } -} +#if NETCF_1_0 + /// + /// Generate GUIDs on the .NET Compact Framework. + /// + public class PocketGuid + { + // guid variant types + private enum GuidVariant + { + ReservedNCS = 0x00, + Standard = 0x02, + ReservedMicrosoft = 0x06, + ReservedFuture = 0x07 + } + + // guid version types + private enum GuidVersion + { + TimeBased = 0x01, + Reserved = 0x02, + NameBased = 0x03, + Random = 0x04 + } + + // constants that are used in the class + private class Const + { + // number of bytes in guid + public const int ByteArraySize = 16; + + // multiplex variant info + public const int VariantByte = 8; + public const int VariantByteMask = 0x3f; + public const int VariantByteShift = 6; + + // multiplex version info + public const int VersionByte = 7; + public const int VersionByteMask = 0x0f; + public const int VersionByteShift = 4; + } + + // imports for the crypto api functions + private class WinApi + { + public const uint PROV_RSA_FULL = 1; + public const uint CRYPT_VERIFYCONTEXT = 0xf0000000; + + [DllImport("CoreDll.dll")] + public static extern bool CryptAcquireContext( + ref IntPtr phProv, string pszContainer, string pszProvider, + uint dwProvType, uint dwFlags); + + [DllImport("CoreDll.dll")] + public static extern bool CryptReleaseContext( + IntPtr hProv, uint dwFlags); + + [DllImport("CoreDll.dll")] + public static extern bool CryptGenRandom( + IntPtr hProv, int dwLen, byte[] pbBuffer); + } + + // all static methods + private PocketGuid() + { + } + + /// + /// Return a new System.Guid object. + /// + public static Guid NewGuid() + { + IntPtr hCryptProv = IntPtr.Zero; + Guid guid = Guid.Empty; + + try + { + // holds random bits for guid + byte[] bits = new byte[Const.ByteArraySize]; + + // get crypto provider handle + if (!WinApi.CryptAcquireContext(ref hCryptProv, null, null, + WinApi.PROV_RSA_FULL, WinApi.CRYPT_VERIFYCONTEXT)) + { + throw new SystemException( + "Failed to acquire cryptography handle."); + } + + // generate a 128 bit (16 byte) cryptographically random number + if (!WinApi.CryptGenRandom(hCryptProv, bits.Length, bits)) + { + throw new SystemException( + "Failed to generate cryptography random bytes."); + } + + // set the variant + bits[Const.VariantByte] &= Const.VariantByteMask; + bits[Const.VariantByte] |= + ((int)GuidVariant.Standard << Const.VariantByteShift); + + // set the version + bits[Const.VersionByte] &= Const.VersionByteMask; + bits[Const.VersionByte] |= + ((int)GuidVersion.Random << Const.VersionByteShift); + + // create the new System.Guid object + guid = new Guid(bits); + } + finally + { + // release the crypto provider handle + if (hCryptProv != IntPtr.Zero) + WinApi.CryptReleaseContext(hCryptProv, 0); + } + + return guid; + } + } +#endif + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/SystemStringFormat.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/SystemStringFormat.cs index a4d90bc8170..ce808995278 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/SystemStringFormat.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/SystemStringFormat.cs @@ -1,229 +1,226 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.Util -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; - using System.Text; - using System.Text.RegularExpressions; - using System.Xml; +using System; +using System.Text; +using System.Xml; +using System.Text.RegularExpressions; - /// - /// Utility class that represents a format string. - /// - /// - /// - /// Utility class that represents a format string. - /// - /// - /// Nicko Cadell. - public sealed class SystemStringFormat - { - private readonly IFormatProvider m_provider; - private readonly string m_format; +namespace log4net.Util +{ + /// + /// Utility class that represents a format string. + /// + /// + /// + /// Utility class that represents a format string. + /// + /// + /// Nicko Cadell + public sealed class SystemStringFormat + { + private readonly IFormatProvider m_provider; + private readonly string m_format; private readonly object[] m_args; /// - /// Initializes a new instance of the class. - /// Initialise the . - /// - /// An that supplies culture-specific formatting information. - /// A containing zero or more format items. - /// An array containing zero or more objects to format. - public SystemStringFormat(IFormatProvider provider, string format, params object[] args) - { - this.m_provider = provider; - this.m_format = format; - this.m_args = args; + /// Initialise the + /// + /// An that supplies culture-specific formatting information. + /// A containing zero or more format items. + /// An array containing zero or more objects to format. + public SystemStringFormat(IFormatProvider provider, string format, params object[] args) + { + this.m_provider = provider; + this.m_format = format; + this.m_args = args; } - /// - /// Format the string and arguments. - /// - /// the formatted string. - public override string ToString() - { - return StringFormat(this.m_provider, this.m_format, this.m_args); + /// + /// Format the string and arguments + /// + /// the formatted string + public override string ToString() + { + return StringFormat(this.m_provider, this.m_format, this.m_args); + } + + /// + /// Replaces the format item in a specified with the text equivalent + /// of the value of a corresponding instance in a specified array. + /// A specified parameter supplies culture-specific formatting information. + /// + /// An that supplies culture-specific formatting information. + /// A containing zero or more format items. + /// An array containing zero or more objects to format. + /// + /// A copy of format in which the format items have been replaced by the + /// equivalent of the corresponding instances of in args. + /// + /// + /// + /// This method does not throw exceptions. If an exception thrown while formatting the result the + /// exception and arguments are returned in the result string. + /// + /// + private static string StringFormat(IFormatProvider provider, string format, params object[] args) + { + try + { + // The format is missing, log null value + if (format == null) + { + return null; + } + + // The args are missing - should not happen unless we are called explicitly with a null array + if (args == null) + { + return format; + } + + // Try to format the string + return String.Format(provider, format, args); + } + catch(Exception ex) + { + LogLog.Warn(declaringType, "Exception while rendering format [" + format + "]", ex); + return StringFormatError(ex, format, args); + } +#if !NET_2_0 && !MONO_2_0 && !MONO_3_5 && !MONO_4_0 && !NETSTANDARD + catch + { + log4net.Util.LogLog.Warn(declaringType, "Exception while rendering format ["+format+"]"); + return StringFormatError(null, format, args); + } +#endif } - /// - /// Replaces the format item in a specified with the text equivalent - /// of the value of a corresponding instance in a specified array. - /// A specified parameter supplies culture-specific formatting information. - /// - /// An that supplies culture-specific formatting information. - /// A containing zero or more format items. - /// An array containing zero or more objects to format. - /// - /// A copy of format in which the format items have been replaced by the - /// equivalent of the corresponding instances of in args. - /// - /// - /// - /// This method does not throw exceptions. If an exception thrown while formatting the result the - /// exception and arguments are returned in the result string. - /// - /// - private static string StringFormat(IFormatProvider provider, string format, params object[] args) - { - try - { - // The format is missing, log null value - if (format == null) - { - return null; - } - - // The args are missing - should not happen unless we are called explicitly with a null array - if (args == null) - { - return format; - } - - // Try to format the string - return string.Format(provider, format, args); - } - catch (Exception ex) - { - log4net.Util.LogLog.Warn(declaringType, "Exception while rendering format [" + format + "]", ex); - return StringFormatError(ex, format, args); - } -#if !NET_2_0 && !MONO_2_0 && !MONO_3_5 && !MONO_4_0 && !NETSTANDARD1_3 - catch - { - log4net.Util.LogLog.Warn(declaringType, "Exception while rendering format ["+format+"]"); - return StringFormatError(null, format, args); - } -#endif - } - - /// - /// Process an error during StringFormat. - /// - private static string StringFormatError(Exception formatException, string format, object[] args) - { - try - { - StringBuilder buf = new StringBuilder(""); - - if (formatException != null) - { - buf.Append("Exception during StringFormat: ").Append(formatException.Message); - } - else - { - buf.Append("Exception during StringFormat"); - } + /// + /// Process an error during StringFormat + /// + private static string StringFormatError(Exception formatException, string format, object[] args) + { + try + { + StringBuilder buf = new StringBuilder(""); - buf.Append(" ").Append(format).Append(""); - buf.Append(""); - RenderArray(args, buf); - buf.Append(""); - buf.Append(""); - - return buf.ToString(); - } - catch (Exception ex) - { - log4net.Util.LogLog.Error(declaringType, "INTERNAL ERROR during StringFormat error handling", ex); - return "Exception during StringFormat. See Internal Log."; - } -#if !NET_2_0 && !MONO_2_0 && !MONO_3_5 && !MONO_4_0 && !NETSTANDARD1_3 - catch - { - log4net.Util.LogLog.Error(declaringType, "INTERNAL ERROR during StringFormat error handling"); - return "Exception during StringFormat. See Internal Log."; - } -#endif - } - - /// - /// Dump the contents of an array into a string builder. - /// - private static void RenderArray(Array array, StringBuilder buffer) - { - if (array == null) - { - buffer.Append(SystemInfo.NullText); - } - else - { - if (array.Rank != 1) - { - buffer.Append(array.ToString()); - } - else - { - buffer.Append("{"); - int len = array.Length; - - if (len > 0) - { - RenderObject(array.GetValue(0), buffer); - for (int i = 1; i < len; i++) - { - buffer.Append(", "); - RenderObject(array.GetValue(i), buffer); - } - } + if (formatException != null) + { + buf.Append("Exception during StringFormat: ").Append(formatException.Message); + } + else + { + buf.Append("Exception during StringFormat"); + } + buf.Append(" ").Append(format).Append(""); + buf.Append(""); + RenderArray(args, buf); + buf.Append(""); + buf.Append(""); - buffer.Append("}"); - } - } - } - - /// - /// Dump an object to a string. - /// - private static void RenderObject(object obj, StringBuilder buffer) - { - if (obj == null) - { - buffer.Append(SystemInfo.NullText); - } - else - { - try - { - buffer.Append(obj); - } - catch (Exception ex) - { - buffer.Append(""); - } -#if !NET_2_0 && !MONO_2_0 && !MONO_3_5 && !MONO_4_0 && !NETSTANDARD1_3 - catch - { - buffer.Append(""); - } -#endif - } + return buf.ToString(); + } + catch(Exception ex) + { + LogLog.Error(declaringType, "INTERNAL ERROR during StringFormat error handling", ex); + return "Exception during StringFormat. See Internal Log."; + } +#if !NET_2_0 && !MONO_2_0 && !MONO_3_5 && !MONO_4_0 && !NETSTANDARD + catch + { + log4net.Util.LogLog.Error(declaringType, "INTERNAL ERROR during StringFormat error handling"); + return "Exception during StringFormat. See Internal Log."; + } +#endif } - /// - /// The fully qualified type of the SystemStringFormat class. - /// - /// - /// Used by the internal logger to record the Type of the - /// log message. - /// + /// + /// Dump the contents of an array into a string builder + /// + private static void RenderArray(Array array, StringBuilder buffer) + { + if (array == null) + { + buffer.Append(SystemInfo.NullText); + } + else + { + if (array.Rank != 1) + { + buffer.Append(array.ToString()); + } + else + { + buffer.Append("{"); + int len = array.Length; + + if (len > 0) + { + RenderObject(array.GetValue(0), buffer); + for (int i = 1; i < len; i++) + { + buffer.Append(", "); + RenderObject(array.GetValue(i), buffer); + } + } + buffer.Append("}"); + } + } + } + + /// + /// Dump an object to a string + /// + private static void RenderObject(Object obj, StringBuilder buffer) + { + if (obj == null) + { + buffer.Append(SystemInfo.NullText); + } + else + { + try + { + buffer.Append(obj); + } + catch(Exception ex) + { + buffer.Append(""); + } +#if !NET_2_0 && !MONO_2_0 && !MONO_3_5 && !MONO_4_0 && !NETSTANDARD + catch + { + buffer.Append(""); + } +#endif + } + } + + /// + /// The fully qualified type of the SystemStringFormat class. + /// + /// + /// Used by the internal logger to record the Type of the + /// log message. + /// private static readonly Type declaringType = typeof(SystemStringFormat); - } -} + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/TextWriterAdapter.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/TextWriterAdapter.cs index 3d04e273abe..a90a70437e4 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/TextWriterAdapter.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/TextWriterAdapter.cs @@ -1,224 +1,220 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.Util -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; - using System.Globalization; - using System.IO; - using System.Text; +using System; +using System.Text; +using System.IO; +using System.Globalization; - /// - /// Adapter that extends and forwards all - /// messages to an instance of . - /// - /// - /// - /// Adapter that extends and forwards all - /// messages to an instance of . - /// - /// - /// Nicko Cadell. - public abstract class TextWriterAdapter : TextWriter +namespace log4net.Util +{ + /// + /// Adapter that extends and forwards all + /// messages to an instance of . + /// + /// + /// + /// Adapter that extends and forwards all + /// messages to an instance of . + /// + /// + /// Nicko Cadell + public abstract class TextWriterAdapter : TextWriter { - /// - /// The writer to forward messages to. - /// + /// + /// The writer to forward messages to + /// private TextWriter m_writer; /// - /// Initializes a new instance of the class. - /// Create an instance of that forwards all - /// messages to a . - /// - /// The to forward to. - /// - /// - /// Create an instance of that forwards all - /// messages to a . - /// - /// - protected TextWriterAdapter(TextWriter writer) - : base(CultureInfo.InvariantCulture) - { - this.m_writer = writer; + /// Create an instance of that forwards all + /// messages to a . + /// + /// The to forward to + /// + /// + /// Create an instance of that forwards all + /// messages to a . + /// + /// + protected TextWriterAdapter(TextWriter writer) : base(CultureInfo.InvariantCulture) + { + this.m_writer = writer; + } + + /// + /// Gets or sets the underlying . + /// + /// + /// The underlying . + /// + /// + /// + /// Gets or sets the underlying . + /// + /// + protected TextWriter Writer + { + get { return this.m_writer; } + set { this.m_writer = value; } + } + + /// + /// The Encoding in which the output is written + /// + /// + /// The + /// + /// + /// + /// The Encoding in which the output is written + /// + /// + public override Encoding Encoding + { + get { return this.m_writer.Encoding; } + } + + /// + /// Gets an object that controls formatting + /// + /// + /// The format provider + /// + /// + /// + /// Gets an object that controls formatting + /// + /// + public override IFormatProvider FormatProvider + { + get { return this.m_writer.FormatProvider; } } - /// - /// Gets or sets the underlying . - /// - /// - /// The underlying . - /// - /// - /// - /// Gets or sets the underlying . - /// - /// - protected TextWriter Writer - { - get { return this.m_writer; } - set { this.m_writer = value; } + /// + /// Gets or sets the line terminator string used by the TextWriter + /// + /// + /// The line terminator to use + /// + /// + /// + /// Gets or sets the line terminator string used by the TextWriter + /// + /// + public override String NewLine + { + get { return this.m_writer.NewLine; } + set { this.m_writer.NewLine = value; } } - /// - /// Gets the Encoding in which the output is written. - /// - /// - /// The . - /// - /// - /// - /// The Encoding in which the output is written. - /// - /// - public override Encoding Encoding - { - get { return this.m_writer.Encoding; } - } - - /// - /// Gets an object that controls formatting. - /// - /// - /// The format provider. - /// - /// - /// - /// Gets an object that controls formatting. - /// - /// - public override IFormatProvider FormatProvider - { - get { return this.m_writer.FormatProvider; } - } - - /// - /// Gets or sets the line terminator string used by the TextWriter. - /// - /// - /// The line terminator to use. - /// - /// - /// - /// Gets or sets the line terminator string used by the TextWriter. - /// - /// - public override string NewLine - { - get { return this.m_writer.NewLine; } - set { this.m_writer.NewLine = value; } + /// + /// Closes the writer and releases any system resources associated with the writer + /// + /// + /// + /// + /// +#if !NETSTANDARD1_3 + override +#else + virtual +#endif + public void Close() + { + this.m_writer.Close(); } - /// - /// Closes the writer and releases any system resources associated with the writer. - /// - /// - /// - /// - /// -#if NETSTANDARD1_3 - virtual public void Close() - { - m_writer.Dispose(); - } -#else - public override void Close() - { - this.m_writer.Close(); - } -#endif - - /// - /// Dispose this writer. - /// - /// flag indicating if we are being disposed. - /// - /// - /// Dispose this writer. - /// - /// - protected override void Dispose(bool disposing) - { - if (disposing) - { - ((IDisposable)this.m_writer).Dispose(); - } - } - - /// - /// Flushes any buffered output. - /// - /// - /// - /// Clears all buffers for the writer and causes any buffered data to be written - /// to the underlying device. - /// - /// - public override void Flush() - { - this.m_writer.Flush(); - } - - /// - /// Writes a character to the wrapped TextWriter. - /// - /// the value to write to the TextWriter. - /// - /// - /// Writes a character to the wrapped TextWriter. - /// - /// - public override void Write(char value) - { - this.m_writer.Write(value); - } - - /// - /// Writes a character buffer to the wrapped TextWriter. - /// - /// the data buffer. - /// the start index. - /// the number of characters to write. - /// - /// - /// Writes a character buffer to the wrapped TextWriter. - /// - /// - public override void Write(char[] buffer, int index, int count) - { - this.m_writer.Write(buffer, index, count); - } - - /// - /// Writes a string to the wrapped TextWriter. - /// - /// the value to write to the TextWriter. - /// - /// - /// Writes a string to the wrapped TextWriter. - /// - /// - public override void Write(string value) - { - this.m_writer.Write(value); + /// + /// Dispose this writer + /// + /// flag indicating if we are being disposed + /// + /// + /// Dispose this writer + /// + /// + protected override void Dispose(bool disposing) + { + if (disposing) + { + ((IDisposable)this.m_writer).Dispose(); + } + } + + /// + /// Flushes any buffered output + /// + /// + /// + /// Clears all buffers for the writer and causes any buffered data to be written + /// to the underlying device + /// + /// + public override void Flush() + { + this.m_writer.Flush(); + } + + /// + /// Writes a character to the wrapped TextWriter + /// + /// the value to write to the TextWriter + /// + /// + /// Writes a character to the wrapped TextWriter + /// + /// + public override void Write(char value) + { + this.m_writer.Write(value); + } + + /// + /// Writes a character buffer to the wrapped TextWriter + /// + /// the data buffer + /// the start index + /// the number of characters to write + /// + /// + /// Writes a character buffer to the wrapped TextWriter + /// + /// + public override void Write(char[] buffer, int index, int count) + { + this.m_writer.Write(buffer, index, count); + } + + /// + /// Writes a string to the wrapped TextWriter + /// + /// the value to write to the TextWriter + /// + /// + /// Writes a string to the wrapped TextWriter + /// + /// + public override void Write(String value) + { + this.m_writer.Write(value); } - } -} + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/ThreadContextProperties.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/ThreadContextProperties.cs index ebd18d32f84..f971f661c03 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/ThreadContextProperties.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/ThreadContextProperties.cs @@ -1,186 +1,181 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -#if NETCF -using System.Collections; -#endif - -namespace log4net.Util -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; +using System; +#if NETCF +using System.Collections; +#endif - /// - /// Implementation of Properties collection for the . - /// - /// - /// - /// Class implements a collection of properties that is specific to each thread. - /// The class is not synchronized as each thread has its own . - /// - /// - /// Nicko Cadell. - public sealed class ThreadContextProperties : ContextPropertiesBase +namespace log4net.Util +{ + /// + /// Implementation of Properties collection for the + /// + /// + /// + /// Class implements a collection of properties that is specific to each thread. + /// The class is not synchronized as each thread has its own . + /// + /// + /// Nicko Cadell + public sealed class ThreadContextProperties : ContextPropertiesBase { -#if NETCF - /// - /// The thread local data slot to use to store a PropertiesDictionary. - /// - private readonly static LocalDataStoreSlot s_threadLocalSlot = System.Threading.Thread.AllocateDataSlot(); -#else - /// - /// Each thread will automatically have its instance. - /// - [ThreadStatic] +#if NETCF + /// + /// The thread local data slot to use to store a PropertiesDictionary. + /// + private readonly static LocalDataStoreSlot s_threadLocalSlot = System.Threading.Thread.AllocateDataSlot(); +#else + /// + /// Each thread will automatically have its instance. + /// + [ThreadStatic] private static PropertiesDictionary _dictionary; -#endif +#endif /// - /// Initializes a new instance of the class. - /// Internal constructor. - /// - /// - /// - /// Initializes a new instance of the class. - /// - /// - internal ThreadContextProperties() - { + /// Internal constructor + /// + /// + /// + /// Initializes a new instance of the class. + /// + /// + internal ThreadContextProperties() + { } - /// - /// Gets or sets the value of a property. - /// - /// - /// The value for the property with the specified key. - /// - /// - /// - /// Gets or sets the value of a property. - /// - /// - public override object this[string key] - { - get - { -#if NETCF - PropertiesDictionary _dictionary = GetProperties(false); -#endif - if (_dictionary != null) - { - return _dictionary[key]; - } - - return null; - } - - set - { - this.GetProperties(true)[key] = value; - } + /// + /// Gets or sets the value of a property + /// + /// + /// The value for the property with the specified key + /// + /// + /// + /// Gets or sets the value of a property + /// + /// + public override object this[string key] + { + get + { +#if NETCF + PropertiesDictionary _dictionary = GetProperties(false); +#endif + if (_dictionary != null) + { + return _dictionary[key]; + } + return null; + } + set + { + this.GetProperties(true)[key] = value; + } } - /// - /// Remove a property. - /// - /// the key for the entry to remove. - /// - /// - /// Remove a property. - /// - /// - public void Remove(string key) - { -#if NETCF - PropertiesDictionary _dictionary = GetProperties(false); -#endif - if (_dictionary != null) - { - _dictionary.Remove(key); - } - } - - /// - /// Get the keys stored in the properties. - /// - /// - /// Gets the keys stored in the properties. - /// - /// a set of the defined keys. - public string[] GetKeys() - { -#if NETCF - PropertiesDictionary _dictionary = GetProperties(false); -#endif - if (_dictionary != null) - { - return _dictionary.GetKeys(); - } + /// + /// Remove a property + /// + /// the key for the entry to remove + /// + /// + /// Remove a property + /// + /// + public void Remove(string key) + { +#if NETCF + PropertiesDictionary _dictionary = GetProperties(false); +#endif + if (_dictionary != null) + { + _dictionary.Remove(key); + } + } - return null; - } - - /// - /// Clear all properties. - /// - /// - /// - /// Clear all properties. - /// - /// - public void Clear() - { -#if NETCF - PropertiesDictionary _dictionary = GetProperties(false); -#endif - if (_dictionary != null) - { - _dictionary.Clear(); - } + /// + /// Get the keys stored in the properties. + /// + /// + /// Gets the keys stored in the properties. + /// + /// a set of the defined keys + public string[] GetKeys() + { +#if NETCF + PropertiesDictionary _dictionary = GetProperties(false); +#endif + if (_dictionary != null) + { + return _dictionary.GetKeys(); + } + return null; } - /// - /// Get the PropertiesDictionary for this thread. - /// - /// create the dictionary if it does not exist, otherwise return null if does not exist. - /// the properties for this thread. - /// - /// - /// The collection returned is only to be used on the calling thread. If the - /// caller needs to share the collection between different threads then the - /// caller must clone the collection before doing so. - /// - /// - internal PropertiesDictionary GetProperties(bool create) - { -#if NETCF - PropertiesDictionary _dictionary = (PropertiesDictionary)System.Threading.Thread.GetData(s_threadLocalSlot); -#endif - if (_dictionary == null && create) - { - _dictionary = new PropertiesDictionary(); -#if NETCF - System.Threading.Thread.SetData(s_threadLocalSlot, _dictionary); -#endif - } + /// + /// Clear all properties + /// + /// + /// + /// Clear all properties + /// + /// + public void Clear() + { +#if NETCF + PropertiesDictionary _dictionary = GetProperties(false); +#endif + if (_dictionary != null) + { + _dictionary.Clear(); + } + } - return _dictionary; + /// + /// Get the PropertiesDictionary for this thread. + /// + /// create the dictionary if it does not exist, otherwise return null if does not exist + /// the properties for this thread + /// + /// + /// The collection returned is only to be used on the calling thread. If the + /// caller needs to share the collection between different threads then the + /// caller must clone the collection before doing so. + /// + /// + internal PropertiesDictionary GetProperties(bool create) + { +#if NETCF + PropertiesDictionary _dictionary = (PropertiesDictionary)System.Threading.Thread.GetData(s_threadLocalSlot); +#endif + if (_dictionary == null && create) + { + _dictionary = new PropertiesDictionary(); +#if NETCF + System.Threading.Thread.SetData(s_threadLocalSlot, _dictionary); +#endif + } + return _dictionary; } - } + } } + diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/ThreadContextStack.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/ThreadContextStack.cs index 1909a792872..524ac2a4285 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/ThreadContextStack.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/ThreadContextStack.cs @@ -1,400 +1,392 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// - -#if !NETCF_1_0 -using System.Collections; +using System; -#endif - -using log4net.Core; - -namespace log4net.Util -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; +#if !NETCF_1_0 +using System.Collections; +#endif - /// - /// Implementation of Stack for the . - /// - /// - /// - /// Implementation of Stack for the . - /// - /// - /// Nicko Cadell. - public sealed class ThreadContextStack : IFixingRequired +using log4net.Core; + +namespace log4net.Util +{ + /// + /// Implementation of Stack for the + /// + /// + /// + /// Implementation of Stack for the + /// + /// + /// Nicko Cadell + public sealed class ThreadContextStack : IFixingRequired { - /// - /// The stack store. - /// + /// + /// The stack store. + /// private Stack m_stack = new Stack(); /// - /// Initializes a new instance of the class. - /// Internal constructor. - /// - /// - /// - /// Initializes a new instance of the class. - /// - /// - internal ThreadContextStack() - { + /// Internal constructor + /// + /// + /// + /// Initializes a new instance of the class. + /// + /// + internal ThreadContextStack() + { + } + + /// + /// The number of messages in the stack + /// + /// + /// The current number of messages in the stack + /// + /// + /// + /// The current number of messages in the stack. That is + /// the number of times has been called + /// minus the number of times has been called. + /// + /// + public int Count + { + get { return this.m_stack.Count; } + } + + /// + /// Clears all the contextual information held in this stack. + /// + /// + /// + /// Clears all the contextual information held in this stack. + /// Only call this if you think that this tread is being reused after + /// a previous call execution which may not have completed correctly. + /// You do not need to use this method if you always guarantee to call + /// the method of the + /// returned from even in exceptional circumstances, + /// for example by using the using(log4net.ThreadContext.Stacks["NDC"].Push("Stack_Message")) + /// syntax. + /// + /// + public void Clear() + { + this.m_stack.Clear(); + } + + /// + /// Removes the top context from this stack. + /// + /// The message in the context that was removed from the top of this stack. + /// + /// + /// Remove the top context from this stack, and return + /// it to the caller. If this stack is empty then an + /// empty string (not ) is returned. + /// + /// + public string Pop() + { + Stack stack = this.m_stack; + if (stack.Count > 0) + { + return ((StackFrame)(stack.Pop())).Message; + } + return string.Empty; } - /// - /// Gets the number of messages in the stack. - /// - /// - /// The current number of messages in the stack. - /// - /// - /// - /// The current number of messages in the stack. That is - /// the number of times has been called - /// minus the number of times has been called. - /// - /// - public int Count - { - get { return this.m_stack.Count; } + /// + /// Pushes a new context message into this stack. + /// + /// The new context message. + /// + /// An that can be used to clean up the context stack. + /// + /// + /// + /// Pushes a new context onto this stack. An + /// is returned that can be used to clean up this stack. This + /// can be easily combined with the using keyword to scope the + /// context. + /// + /// + /// Simple example of using the Push method with the using keyword. + /// + /// using(log4net.ThreadContext.Stacks["NDC"].Push("Stack_Message")) + /// { + /// log.Warn("This should have an ThreadContext Stack message"); + /// } + /// + /// + public IDisposable Push(string message) + { + Stack stack = this.m_stack; + stack.Push(new StackFrame(message, (stack.Count>0) ? (StackFrame)stack.Peek() : null)); + + return new AutoPopStackFrame(stack, stack.Count - 1); } - /// - /// Clears all the contextual information held in this stack. - /// - /// - /// - /// Clears all the contextual information held in this stack. - /// Only call this if you think that this tread is being reused after - /// a previous call execution which may not have completed correctly. - /// You do not need to use this method if you always guarantee to call - /// the method of the - /// returned from even in exceptional circumstances, - /// for example by using the using(log4net.ThreadContext.Stacks["NDC"].Push("Stack_Message")) - /// syntax. - /// - /// - public void Clear() - { - this.m_stack.Clear(); - } - - /// - /// Removes the top context from this stack. - /// - /// The message in the context that was removed from the top of this stack. - /// - /// - /// Remove the top context from this stack, and return - /// it to the caller. If this stack is empty then an - /// empty string (not ) is returned. - /// - /// - public string Pop() - { - Stack stack = this.m_stack; - if (stack.Count > 0) - { - return ((StackFrame)stack.Pop()).Message; - } + /// + /// Gets the current context information for this stack. + /// + /// The current context information. + internal string GetFullMessage() + { + Stack stack = this.m_stack; + if (stack.Count > 0) + { + return ((StackFrame)(stack.Peek())).FullMessage; + } + return null; + } - return string.Empty; - } - - /// - /// Pushes a new context message into this stack. - /// - /// The new context message. - /// - /// An that can be used to clean up the context stack. - /// - /// - /// - /// Pushes a new context onto this stack. An - /// is returned that can be used to clean up this stack. This - /// can be easily combined with the using keyword to scope the - /// context. - /// - /// - /// Simple example of using the Push method with the using keyword. - /// - /// using(log4net.ThreadContext.Stacks["NDC"].Push("Stack_Message")) - /// { - /// log.Warn("This should have an ThreadContext Stack message"); - /// } - /// - /// - public IDisposable Push(string message) - { - Stack stack = this.m_stack; - stack.Push(new StackFrame(message, (stack.Count > 0) ? (StackFrame)stack.Peek() : null)); - - return new AutoPopStackFrame(stack, stack.Count - 1); + /// + /// Gets and sets the internal stack used by this + /// + /// The internal storage stack + /// + /// + /// This property is provided only to support backward compatability + /// of the . Tytpically the internal stack should not + /// be modified. + /// + /// + internal Stack InternalStack + { + get { return this.m_stack; } + set { this.m_stack = value; } } - /// - /// Gets the current context information for this stack. - /// - /// The current context information. - internal string GetFullMessage() - { - Stack stack = this.m_stack; - if (stack.Count > 0) - { - return ((StackFrame)stack.Peek()).FullMessage; - } + /// + /// Gets the current context information for this stack. + /// + /// Gets the current context information + /// + /// + /// Gets the current context information for this stack. + /// + /// + public override string ToString() + { + return this.GetFullMessage(); + } - return null; - } - - /// - /// Gets or sets and sets the internal stack used by this . - /// - /// The internal storage stack. - /// - /// - /// This property is provided only to support backward compatability - /// of the . Tytpically the internal stack should not - /// be modified. - /// - /// - internal Stack InternalStack - { - get { return this.m_stack; } - set { this.m_stack = value; } + /// + /// Get a portable version of this object + /// + /// the portable instance of this object + /// + /// + /// Get a cross thread portable version of this object + /// + /// + object IFixingRequired.GetFixedObject() + { + return this.GetFullMessage(); } - /// - /// Gets the current context information for this stack. - /// - /// Gets the current context information. - /// - /// - /// Gets the current context information for this stack. - /// - /// - public override string ToString() - { - return this.GetFullMessage(); - } - - /// - /// Get a portable version of this object. - /// - /// the portable instance of this object. - /// - /// - /// Get a cross thread portable version of this object. - /// - /// - object IFixingRequired.GetFixedObject() - { - return this.GetFullMessage(); - } - - /// - /// Inner class used to represent a single context frame in the stack. - /// - /// - /// - /// Inner class used to represent a single context frame in the stack. - /// - /// - private sealed class StackFrame + /// + /// Inner class used to represent a single context frame in the stack. + /// + /// + /// + /// Inner class used to represent a single context frame in the stack. + /// + /// + private sealed class StackFrame { - private readonly string m_message; - private readonly StackFrame m_parent; + private readonly string m_message; + private readonly StackFrame m_parent; private string m_fullMessage = null; /// - /// Initializes a new instance of the class. - /// Constructor. - /// - /// The message for this context. - /// The parent context in the chain. - /// - /// - /// Initializes a new instance of the class - /// with the specified message and parent context. - /// - /// - internal StackFrame(string message, StackFrame parent) - { - this.m_message = message; - this.m_parent = parent; - - if (parent == null) - { - this.m_fullMessage = message; - } + /// Constructor + /// + /// The message for this context. + /// The parent context in the chain. + /// + /// + /// Initializes a new instance of the class + /// with the specified message and parent context. + /// + /// + internal StackFrame(string message, StackFrame parent) + { + this.m_message = message; + this.m_parent = parent; + + if (parent == null) + { + this.m_fullMessage = message; + } } - /// - /// Gets get the message. - /// - /// The message. - /// - /// - /// Get the message. - /// - /// - internal string Message - { - get { return this.m_message; } - } - - /// - /// Gets the full text of the context down to the root level. - /// - /// - /// The full text of the context down to the root level. - /// - /// - /// - /// Gets the full text of the context down to the root level. - /// - /// - internal string FullMessage - { - get - { - if (this.m_fullMessage == null && this.m_parent != null) - { - this.m_fullMessage = string.Concat(this.m_parent.FullMessage, " ", this.m_message); - } + /// + /// Get the message. + /// + /// The message. + /// + /// + /// Get the message. + /// + /// + internal string Message + { + get { return this.m_message; } + } - return this.m_fullMessage; - } + /// + /// Gets the full text of the context down to the root level. + /// + /// + /// The full text of the context down to the root level. + /// + /// + /// + /// Gets the full text of the context down to the root level. + /// + /// + internal string FullMessage + { + get + { + if (this.m_fullMessage == null && this.m_parent != null) + { + this.m_fullMessage = string.Concat(this.m_parent.FullMessage, " ", this.m_message); + } + return this.m_fullMessage; + } } - } - - /// - /// Struct returned from the method. - /// - /// - /// - /// This struct implements the and is designed to be used - /// with the pattern to remove the stack frame at the end of the scope. - /// - /// - private struct AutoPopStackFrame : IDisposable + } + + /// + /// Struct returned from the method. + /// + /// + /// + /// This struct implements the and is designed to be used + /// with the pattern to remove the stack frame at the end of the scope. + /// + /// + private struct AutoPopStackFrame : IDisposable { - /// - /// The ThreadContextStack internal stack. - /// - private Stack m_frameStack; - - /// - /// The depth to trim the stack to when this instance is disposed. - /// + /// + /// The ThreadContextStack internal stack + /// + private Stack m_frameStack; + + /// + /// The depth to trim the stack to when this instance is disposed + /// private int m_frameDepth; /// - /// Initializes a new instance of the struct. - /// Constructor. - /// - /// The internal stack used by the ThreadContextStack. - /// The depth to return the stack to when this object is disposed. - /// - /// - /// Initializes a new instance of the class with - /// the specified stack and return depth. - /// - /// - internal AutoPopStackFrame(Stack frameStack, int frameDepth) - { - this.m_frameStack = frameStack; - this.m_frameDepth = frameDepth; + /// Constructor + /// + /// The internal stack used by the ThreadContextStack. + /// The depth to return the stack to when this object is disposed. + /// + /// + /// Initializes a new instance of the class with + /// the specified stack and return depth. + /// + /// + internal AutoPopStackFrame(Stack frameStack, int frameDepth) + { + this.m_frameStack = frameStack; + this.m_frameDepth = frameDepth; } - /// - /// Returns the stack to the correct depth. - /// - /// - /// - /// Returns the stack to the correct depth. - /// - /// - public void Dispose() - { - if (this.m_frameDepth >= 0 && this.m_frameStack != null) - { - while (this.m_frameStack.Count > this.m_frameDepth) - { - this.m_frameStack.Pop(); - } - } + /// + /// Returns the stack to the correct depth. + /// + /// + /// + /// Returns the stack to the correct depth. + /// + /// + public void Dispose() + { + if (this.m_frameDepth >= 0 && this.m_frameStack != null) + { + while(this.m_frameStack.Count > this.m_frameDepth) + { + this.m_frameStack.Pop(); + } + } } - } - -#if NETCF_1_0 - /// - /// Subclass of to - /// provide missing methods. - /// - /// - /// - /// The Compact Framework version of the - /// class is missing the Clear and Clone methods. - /// This subclass adds implementations of those missing methods. - /// - /// - public class Stack : System.Collections.Stack - { - /// - /// Clears the stack of all elements. - /// - /// - /// - /// Clears the stack of all elements. - /// - /// - public void Clear() - { - while(Count > 0) - { - Pop(); - } - } - - /// - /// Makes a shallow copy of the stack's elements. - /// - /// A new stack that has a shallow copy of the stack's elements. - /// - /// - /// Makes a shallow copy of the stack's elements. - /// - /// - public Stack Clone() - { - Stack res = new Stack(); - object[] items = ToArray(); - foreach(object item in items) - { - res.Push(item); - } - return res; - } - } -#endif - } -} + } + +#if NETCF_1_0 + /// + /// Subclass of to + /// provide missing methods. + /// + /// + /// + /// The Compact Framework version of the + /// class is missing the Clear and Clone methods. + /// This subclass adds implementations of those missing methods. + /// + /// + public class Stack : System.Collections.Stack + { + /// + /// Clears the stack of all elements. + /// + /// + /// + /// Clears the stack of all elements. + /// + /// + public void Clear() + { + while(Count > 0) + { + Pop(); + } + } + + /// + /// Makes a shallow copy of the stack's elements. + /// + /// A new stack that has a shallow copy of the stack's elements. + /// + /// + /// Makes a shallow copy of the stack's elements. + /// + /// + public Stack Clone() + { + Stack res = new Stack(); + object[] items = ToArray(); + foreach(object item in items) + { + res.Push(item); + } + return res; + } + } +#endif + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/ThreadContextStacks.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/ThreadContextStacks.cs index 6c6c445c8b7..530995b27ba 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/ThreadContextStacks.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/ThreadContextStacks.cs @@ -1,113 +1,113 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.Util -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; - using System.Collections; +using System; +using System.Collections; - /// - /// Implementation of Stacks collection for the . - /// - /// - /// - /// Implementation of Stacks collection for the . - /// - /// - /// Nicko Cadell. - public sealed class ThreadContextStacks - { +namespace log4net.Util +{ + /// + /// Implementation of Stacks collection for the + /// + /// + /// + /// Implementation of Stacks collection for the + /// + /// + /// Nicko Cadell + public sealed class ThreadContextStacks + { private readonly ContextPropertiesBase m_properties; /// - /// Initializes a new instance of the class. - /// Internal constructor. - /// - /// - /// - /// Initializes a new instance of the class. - /// - /// - internal ThreadContextStacks(ContextPropertiesBase properties) - { - this.m_properties = properties; + /// Internal constructor + /// + /// + /// + /// Initializes a new instance of the class. + /// + /// + internal ThreadContextStacks(ContextPropertiesBase properties) + { + this.m_properties = properties; } - /// - /// Gets the named thread context stack. - /// - /// - /// The named stack. - /// - /// - /// - /// Gets the named thread context stack. - /// - /// - public ThreadContextStack this[string key] - { - get - { - ThreadContextStack stack = null; - - object propertyValue = this.m_properties[key]; - if (propertyValue == null) - { - // Stack does not exist, create - stack = new ThreadContextStack(); - this.m_properties[key] = stack; - } - else - { - // Look for existing stack - stack = propertyValue as ThreadContextStack; - if (stack == null) - { - // Property is not set to a stack! - string propertyValueString = SystemInfo.NullText; - - try - { - propertyValueString = propertyValue.ToString(); - } - catch - { - } - - LogLog.Error(declaringType, "ThreadContextStacks: Request for stack named [" + key + "] failed because a property with the same name exists which is a [" + propertyValue.GetType().Name + "] with value [" + propertyValueString + "]"); - - stack = new ThreadContextStack(); - } - } - - return stack; - } + /// + /// Gets the named thread context stack + /// + /// + /// The named stack + /// + /// + /// + /// Gets the named thread context stack + /// + /// + public ThreadContextStack this[string key] + { + get + { + ThreadContextStack stack = null; + + object propertyValue = this.m_properties[key]; + if (propertyValue == null) + { + // Stack does not exist, create + stack = new ThreadContextStack(); + this.m_properties[key] = stack; + } + else + { + // Look for existing stack + stack = propertyValue as ThreadContextStack; + if (stack == null) + { + // Property is not set to a stack! + string propertyValueString = SystemInfo.NullText; + + try + { + propertyValueString = propertyValue.ToString(); + } + catch + { + } + + LogLog.Error(declaringType, "ThreadContextStacks: Request for stack named ["+key+"] failed because a property with the same name exists which is a ["+propertyValue.GetType().Name+"] with value ["+propertyValueString+"]"); + + stack = new ThreadContextStack(); + } + } + + return stack; + } } - /// - /// The fully qualified type of the ThreadContextStacks class. - /// - /// - /// Used by the internal logger to record the Type of the - /// log message. - /// + /// + /// The fully qualified type of the ThreadContextStacks class. + /// + /// + /// Used by the internal logger to record the Type of the + /// log message. + /// private static readonly Type declaringType = typeof(ThreadContextStacks); - } + } } + diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/Transform.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/Transform.cs index acd93e41879..7817a2a8ca2 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/Transform.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/Transform.cs @@ -1,187 +1,186 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.Util -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; - using System.Text; - using System.Text.RegularExpressions; - using System.Xml; +using System; +using System.Text; +using System.Xml; +using System.Text.RegularExpressions; - /// - /// Utility class for transforming strings. - /// - /// - /// - /// Utility class for transforming strings. - /// - /// - /// Nicko Cadell. - /// Gert Driesen. - public sealed class Transform +namespace log4net.Util +{ + /// + /// Utility class for transforming strings. + /// + /// + /// + /// Utility class for transforming strings. + /// + /// + /// Nicko Cadell + /// Gert Driesen + public sealed class Transform { - /// - /// Initializes a new instance of the class. - /// - /// - /// - /// Uses a private access modifier to prevent instantiation of this class. - /// - /// - private Transform() - { + /// + /// Initializes a new instance of the class. + /// + /// + /// + /// Uses a private access modifier to prevent instantiation of this class. + /// + /// + private Transform() + { } - /// - /// Write a string to an . - /// - /// the writer to write to. - /// the string to write. - /// The string to replace non XML compliant chars with. - /// - /// - /// The test is escaped either using XML escape entities - /// or using CDATA sections. - /// - /// - public static void WriteEscapedXmlString(XmlWriter writer, string textData, string invalidCharReplacement) - { - string stringData = MaskXmlInvalidCharacters(textData, invalidCharReplacement); + /// + /// Write a string to an + /// + /// the writer to write to + /// the string to write + /// The string to replace non XML compliant chars with + /// + /// + /// The test is escaped either using XML escape entities + /// or using CDATA sections. + /// + /// + public static void WriteEscapedXmlString(XmlWriter writer, string textData, string invalidCharReplacement) + { + string stringData = MaskXmlInvalidCharacters(textData, invalidCharReplacement); + // Write either escaped text or CDATA sections - // Write either escaped text or CDATA sections - int weightCData = 12 * (1 + CountSubstrings(stringData, CDATA_END)); - int weightStringEscapes = (3 * (CountSubstrings(stringData, "<") + CountSubstrings(stringData, ">"))) + (4 * CountSubstrings(stringData, "&")); - - if (weightStringEscapes <= weightCData) - { - // Write string using string escapes - writer.WriteString(stringData); - } - else - { - // Write string using CDATA section - int end = stringData.IndexOf(CDATA_END); - - if (end < 0) - { - writer.WriteCData(stringData); - } - else - { - int start = 0; - while (end > -1) - { - writer.WriteCData(stringData.Substring(start, end - start)); - if (end == stringData.Length - 3) - { - start = stringData.Length; - writer.WriteString(CDATA_END); - break; - } - else - { - writer.WriteString(CDATA_UNESCAPABLE_TOKEN); - start = end + 2; - end = stringData.IndexOf(CDATA_END, start); - } - } - - if (start < stringData.Length) - { - writer.WriteCData(stringData.Substring(start)); - } - } - } - } - - /// - /// Replace invalid XML characters in text string. - /// - /// the XML text input string. - /// the string to use in place of invalid characters. - /// A string that does not contain invalid XML characters. - /// - /// - /// Certain Unicode code points are not allowed in the XML InfoSet, for - /// details see: http://www.w3.org/TR/REC-xml/#charsets. - /// - /// - /// This method replaces any illegal characters in the input string - /// with the mask string specified. - /// - /// - public static string MaskXmlInvalidCharacters(string textData, string mask) - { - return INVALIDCHARS.Replace(textData, mask); + int weightCData = 12 * (1 + CountSubstrings(stringData, CDATA_END)); + int weightStringEscapes = 3*(CountSubstrings(stringData, "<") + CountSubstrings(stringData, ">")) + 4*CountSubstrings(stringData, "&"); + + if (weightStringEscapes <= weightCData) + { + // Write string using string escapes + writer.WriteString(stringData); + } + else + { + // Write string using CDATA section + + int end = stringData.IndexOf(CDATA_END); + + if (end < 0) + { + writer.WriteCData(stringData); + } + else + { + int start = 0; + while (end > -1) + { + writer.WriteCData(stringData.Substring(start, end - start)); + if (end == stringData.Length - 3) + { + start = stringData.Length; + writer.WriteString(CDATA_END); + break; + } + else + { + writer.WriteString(CDATA_UNESCAPABLE_TOKEN); + start = end + 2; + end = stringData.IndexOf(CDATA_END, start); + } + } + + if (start < stringData.Length) + { + writer.WriteCData(stringData.Substring(start)); + } + } + } + } + + /// + /// Replace invalid XML characters in text string + /// + /// the XML text input string + /// the string to use in place of invalid characters + /// A string that does not contain invalid XML characters. + /// + /// + /// Certain Unicode code points are not allowed in the XML InfoSet, for + /// details see: http://www.w3.org/TR/REC-xml/#charsets. + /// + /// + /// This method replaces any illegal characters in the input string + /// with the mask string specified. + /// + /// + public static string MaskXmlInvalidCharacters(string textData, string mask) + { + return INVALIDCHARS.Replace(textData, mask); } - /// - /// Count the number of times that the substring occurs in the text. - /// - /// the text to search. - /// the substring to find. - /// the number of times the substring occurs in the text. - /// - /// - /// The substring is assumed to be non repeating within itself. - /// - /// - private static int CountSubstrings(string text, string substring) - { - int count = 0; - int offset = 0; - int length = text.Length; - int substringLength = substring.Length; - - if (length == 0) - { - return 0; - } + /// + /// Count the number of times that the substring occurs in the text + /// + /// the text to search + /// the substring to find + /// the number of times the substring occurs in the text + /// + /// + /// The substring is assumed to be non repeating within itself. + /// + /// + private static int CountSubstrings(string text, string substring) + { + int count = 0; + int offset = 0; + int length = text.Length; + int substringLength = substring.Length; - if (substringLength == 0) - { - return 0; - } - - while (offset < length) - { - int index = text.IndexOf(substring, offset); - - if (index == -1) - { - break; - } - - count++; - offset = index + substringLength; - } + if (length == 0) + { + return 0; + } + if (substringLength == 0) + { + return 0; + } - return count; + while(offset < length) + { + int index = text.IndexOf(substring, offset); + + if (index == -1) + { + break; + } + + count++; + offset = index + substringLength; + } + return count; } - private const string CDATA_END = "]]>"; - private const string CDATA_UNESCAPABLE_TOKEN = "]]"; - - /// - /// Characters illegal in XML 1.0. - /// + private const string CDATA_END = "]]>"; + private const string CDATA_UNESCAPABLE_TOKEN = "]]"; + + /// + /// Characters illegal in XML 1.0 + /// private static Regex INVALIDCHARS = new Regex(@"[^\x09\x0A\x0D\x20-\uD7FF\uE000-\uFFFD]", RegexOptions.Compiled); - } -} + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/TypeConverters/BooleanConverter.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/TypeConverters/BooleanConverter.cs index 6d5bb99ee07..1a06c7b47fc 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/TypeConverters/BooleanConverter.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/TypeConverters/BooleanConverter.cs @@ -1,83 +1,82 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.Util.TypeConverters -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; +using System; - /// - /// Type converter for Boolean. - /// - /// - /// - /// Supports conversion from string to bool type. - /// - /// - /// - /// - /// - /// Nicko Cadell. - /// Gert Driesen. - internal class BooleanConverter : IConvertFrom +namespace log4net.Util.TypeConverters +{ + /// + /// Type converter for Boolean. + /// + /// + /// + /// Supports conversion from string to bool type. + /// + /// + /// + /// + /// + /// Nicko Cadell + /// Gert Driesen + internal class BooleanConverter : IConvertFrom { - /// - /// Can the source type be converted to the type supported by this object. - /// - /// the type to convert. - /// true if the conversion is possible. - /// - /// - /// Returns true if the is - /// the type. - /// - /// - public bool CanConvertFrom(Type sourceType) - { - return sourceType == typeof(string); - } - - /// - /// Convert the source object to the type supported by this object. - /// - /// the object to convert. - /// the converted object. - /// - /// - /// Uses the method to convert the - /// argument to a . - /// - /// - /// - /// The object cannot be converted to the - /// target type. To check for this condition use the - /// method. - /// - public object ConvertFrom(object source) - { - string str = source as string; - if (str != null) - { - return bool.Parse(str); - } + /// + /// Can the source type be converted to the type supported by this object + /// + /// the type to convert + /// true if the conversion is possible + /// + /// + /// Returns true if the is + /// the type. + /// + /// + public bool CanConvertFrom(Type sourceType) + { + return (sourceType == typeof(string)); + } - throw ConversionNotSupportedException.Create(typeof(bool), source); + /// + /// Convert the source object to the type supported by this object + /// + /// the object to convert + /// the converted object + /// + /// + /// Uses the method to convert the + /// argument to a . + /// + /// + /// + /// The object cannot be converted to the + /// target type. To check for this condition use the + /// method. + /// + public object ConvertFrom(object source) + { + string str = source as string; + if (str != null) + { + return bool.Parse(str); + } + throw ConversionNotSupportedException.Create(typeof(bool), source); } - } -} + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/TypeConverters/ConversionNotSupportedException.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/TypeConverters/ConversionNotSupportedException.cs index 3e3ac3ba5bb..74f7091dbb4 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/TypeConverters/ConversionNotSupportedException.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/TypeConverters/ConversionNotSupportedException.cs @@ -1,156 +1,147 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -#if !(NETCF || NETSTANDARD1_3) -using System.Runtime.Serialization; +using System; +#if !NETCF && !NETSTANDARD1_3 +using System.Runtime.Serialization; +#endif -#endif - -namespace log4net.Util.TypeConverters -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; - - /// - /// Exception base type for conversion errors. - /// - /// - /// - /// This type extends . It - /// does not add any new functionality but does differentiate the - /// type of exception being thrown. - /// - /// - /// Nicko Cadell. - /// Gert Driesen. -#if !NETCF - [Serializable] -#endif -#if NETSTANDARD1_3 - public class ConversionNotSupportedException : Exception -#else - public class ConversionNotSupportedException : ApplicationException -#endif +namespace log4net.Util.TypeConverters +{ + /// + /// Exception base type for conversion errors. + /// + /// + /// + /// This type extends . It + /// does not add any new functionality but does differentiate the + /// type of exception being thrown. + /// + /// + /// Nicko Cadell + /// Gert Driesen +#if !NETCF + [Serializable] +#endif +#if NETSTANDARD1_3 + public class ConversionNotSupportedException : Exception +#else + public class ConversionNotSupportedException : ApplicationException +#endif { /// - /// Initializes a new instance of the class. - /// Constructor. - /// - /// - /// - /// Initializes a new instance of the class. - /// - /// - public ConversionNotSupportedException() - { + /// Constructor + /// + /// + /// + /// Initializes a new instance of the class. + /// + /// + public ConversionNotSupportedException() + { } /// - /// Initializes a new instance of the class. - /// Constructor. - /// - /// A message to include with the exception. - /// - /// - /// Initializes a new instance of the class - /// with the specified message. - /// - /// - public ConversionNotSupportedException(string message) - : base(message) - { + /// Constructor + /// + /// A message to include with the exception. + /// + /// + /// Initializes a new instance of the class + /// with the specified message. + /// + /// + public ConversionNotSupportedException(String message) : base(message) + { + } + + /// + /// Constructor + /// + /// A message to include with the exception. + /// A nested exception to include. + /// + /// + /// Initializes a new instance of the class + /// with the specified message and inner exception. + /// + /// + public ConversionNotSupportedException(String message, Exception innerException) : base(message, innerException) + { } +#if !NETCF && !NETSTANDARD1_3 /// - /// Initializes a new instance of the class. - /// Constructor. - /// - /// A message to include with the exception. - /// A nested exception to include. - /// - /// - /// Initializes a new instance of the class - /// with the specified message and inner exception. - /// - /// - public ConversionNotSupportedException(string message, Exception innerException) - : base(message, innerException) - { + /// Serialization constructor + /// + /// The that holds the serialized object data about the exception being thrown. + /// The that contains contextual information about the source or destination. + /// + /// + /// Initializes a new instance of the class + /// with serialized data. + /// + /// + protected ConversionNotSupportedException(SerializationInfo info, StreamingContext context) : base(info, context) + { } +#endif -#if !(NETCF || NETSTANDARD1_3) /// - /// Initializes a new instance of the class. - /// Serialization constructor. - /// - /// The that holds the serialized object data about the exception being thrown. - /// The that contains contextual information about the source or destination. - /// - /// - /// Initializes a new instance of the class - /// with serialized data. - /// - /// - protected ConversionNotSupportedException(SerializationInfo info, StreamingContext context) - : base(info, context) - { + /// Creates a new instance of the class. + /// + /// The conversion destination type. + /// The value to convert. + /// An instance of the . + /// + /// + /// Creates a new instance of the class. + /// + /// + public static ConversionNotSupportedException Create(Type destinationType, object sourceValue) + { + return Create(destinationType, sourceValue, null); } -#endif - /// - /// Creates a new instance of the class. - /// - /// The conversion destination type. - /// The value to convert. - /// An instance of the . - /// - /// - /// Creates a new instance of the class. - /// - /// - public static ConversionNotSupportedException Create(Type destinationType, object sourceValue) - { - return Create(destinationType, sourceValue, null); - } - - /// - /// Creates a new instance of the class. - /// - /// The conversion destination type. - /// The value to convert. - /// A nested exception to include. - /// An instance of the . - /// - /// - /// Creates a new instance of the class. - /// - /// - public static ConversionNotSupportedException Create(Type destinationType, object sourceValue, Exception innerException) - { - if (sourceValue == null) - { - return new ConversionNotSupportedException("Cannot convert value [null] to type [" + destinationType + "]", innerException); - } - else - { - return new ConversionNotSupportedException("Cannot convert from type [" + sourceValue.GetType() + "] value [" + sourceValue + "] to type [" + destinationType + "]", innerException); - } + /// + /// Creates a new instance of the class. + /// + /// The conversion destination type. + /// The value to convert. + /// A nested exception to include. + /// An instance of the . + /// + /// + /// Creates a new instance of the class. + /// + /// + public static ConversionNotSupportedException Create(Type destinationType, object sourceValue, Exception innerException) + { + if (sourceValue == null) + { + return new ConversionNotSupportedException("Cannot convert value [null] to type [" + destinationType + "]", innerException); + } + else + { + return new ConversionNotSupportedException("Cannot convert from type [" + sourceValue.GetType() + "] value [" + sourceValue + "] to type [" + destinationType + "]", innerException); + } } - } -} + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/TypeConverters/ConverterRegistry.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/TypeConverters/ConverterRegistry.cs index d87772b18f1..7b56f2e4e0e 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/TypeConverters/ConverterRegistry.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/TypeConverters/ConverterRegistry.cs @@ -1,284 +1,289 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +using System; +using System.Collections; +#if NETSTANDARD1_3 +using System.Reflection; +#endif -#if NETSTANDARD1_3 -using System.Linq; -#endif -using System.Collections; -using System.Reflection; - -namespace log4net.Util.TypeConverters -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; - using System.Globalization; - - /// - /// Register of type converters for specific types. - /// - /// - /// - /// Maintains a registry of type converters used to convert between - /// types. - /// - /// - /// Use the and - /// methods to register new converters. - /// The and methods - /// lookup appropriate converters to use. - /// - /// - /// - /// - /// Nicko Cadell. - /// Gert Driesen. - public sealed class ConverterRegistry +namespace log4net.Util.TypeConverters +{ + /// + /// Register of type converters for specific types. + /// + /// + /// + /// Maintains a registry of type converters used to convert between + /// types. + /// + /// + /// Use the and + /// methods to register new converters. + /// The and methods + /// lookup appropriate converters to use. + /// + /// + /// + /// + /// Nicko Cadell + /// Gert Driesen + public sealed class ConverterRegistry { /// - /// Initializes a new instance of the class. - /// Private constructor. - /// - /// - /// Initializes a new instance of the class. - /// - private ConverterRegistry() - { + /// Private constructor + /// + /// + /// Initializes a new instance of the class. + /// + private ConverterRegistry() + { + } + + /// + /// Static constructor. + /// + /// + /// + /// This constructor defines the intrinsic type converters. + /// + /// + static ConverterRegistry() + { + // Add predefined converters here + AddConverter(typeof(bool), typeof(BooleanConverter)); + AddConverter(typeof(System.Text.Encoding), typeof(EncodingConverter)); + AddConverter(typeof(Type), typeof(TypeConverter)); + AddConverter(typeof(Layout.PatternLayout), typeof(PatternLayoutConverter)); + AddConverter(typeof(PatternString), typeof(PatternStringConverter)); + AddConverter(typeof(System.Net.IPAddress), typeof(IPAddressConverter)); + } + + /// + /// Adds a converter for a specific type. + /// + /// The type being converted to. + /// The type converter to use to convert to the destination type. + /// + /// + /// Adds a converter instance for a specific type. + /// + /// + public static void AddConverter(Type destinationType, object converter) + { + if (destinationType != null && converter != null) + { + lock(s_type2converter) + { + s_type2converter[destinationType] = converter; + } + } + } + + /// + /// Adds a converter for a specific type. + /// + /// The type being converted to. + /// The type of the type converter to use to convert to the destination type. + /// + /// + /// Adds a converter for a specific type. + /// + /// + public static void AddConverter(Type destinationType, Type converterType) + { + AddConverter(destinationType, CreateConverterInstance(converterType)); + } + + /// + /// Gets the type converter to use to convert values to the destination type. + /// + /// The type being converted from. + /// The type being converted to. + /// + /// The type converter instance to use for type conversions or null + /// if no type converter is found. + /// + /// + /// + /// Gets the type converter to use to convert values to the destination type. + /// + /// + public static IConvertTo GetConvertTo(Type sourceType, Type destinationType) + { + // TODO: Support inheriting type converters. + // i.e. getting a type converter for a base of sourceType + + // TODO: Is destinationType required? We don't use it for anything. + + lock(s_type2converter) + { + // Lookup in the static registry + IConvertTo converter = s_type2converter[sourceType] as IConvertTo; + + if (converter == null) + { + // Lookup using attributes + converter = GetConverterFromAttribute(sourceType) as IConvertTo; + + if (converter != null) + { + // Store in registry + s_type2converter[sourceType] = converter; + } + } + + return converter; + } } /// - /// Initializes static members of the class. - /// Static constructor. - /// - /// - /// - /// This constructor defines the intrinsic type converters. - /// - /// - static ConverterRegistry() - { - // Add predefined converters here - AddConverter(typeof(bool), typeof(BooleanConverter)); - AddConverter(typeof(System.Text.Encoding), typeof(EncodingConverter)); - AddConverter(typeof(System.Type), typeof(TypeConverter)); - AddConverter(typeof(log4net.Layout.PatternLayout), typeof(PatternLayoutConverter)); - AddConverter(typeof(log4net.Util.PatternString), typeof(PatternStringConverter)); - AddConverter(typeof(System.Net.IPAddress), typeof(IPAddressConverter)); + /// Gets the type converter to use to convert values to the destination type. + /// + /// The type being converted to. + /// + /// The type converter instance to use for type conversions or null + /// if no type converter is found. + /// + /// + /// + /// Gets the type converter to use to convert values to the destination type. + /// + /// + public static IConvertFrom GetConvertFrom(Type destinationType) + { + // TODO: Support inheriting type converters. + // i.e. getting a type converter for a base of destinationType + + lock(s_type2converter) + { + // Lookup in the static registry + IConvertFrom converter = s_type2converter[destinationType] as IConvertFrom; + + if (converter == null) + { + // Lookup using attributes + converter = GetConverterFromAttribute(destinationType) as IConvertFrom; + + if (converter != null) + { + // Store in registry + s_type2converter[destinationType] = converter; + } + } + + return converter; + } } + + /// + /// Lookups the type converter to use as specified by the attributes on the + /// destination type. + /// + /// The type being converted to. + /// + /// The type converter instance to use for type conversions or null + /// if no type converter is found. + /// + private static object GetConverterFromAttribute(Type destinationType) + { + // Look for an attribute on the destination type + var attributes = destinationType +#if NETSTANDARD1_3 + .GetTypeInfo() +#endif + .GetCustomAttributes(typeof(TypeConverterAttribute), true); + if (attributes is null) + { + // I assume the original null check is perhaps for CF or older .NET versions -- please leave in place + return null; + } - /// - /// Adds a converter for a specific type. - /// - /// The type being converted to. - /// The type converter to use to convert to the destination type. - /// - /// - /// Adds a converter instance for a specific type. - /// - /// - public static void AddConverter(Type destinationType, object converter) - { - if (destinationType != null && converter != null) - { - lock (s_type2converter) - { - s_type2converter[destinationType] = converter; - } - } - } - - /// - /// Adds a converter for a specific type. - /// - /// The type being converted to. - /// The type of the type converter to use to convert to the destination type. - /// - /// - /// Adds a converter for a specific type. - /// - /// - public static void AddConverter(Type destinationType, Type converterType) - { - AddConverter(destinationType, CreateConverterInstance(converterType)); - } - - /// - /// Gets the type converter to use to convert values to the destination type. - /// - /// The type being converted from. - /// The type being converted to. - /// - /// The type converter instance to use for type conversions or null - /// if no type converter is found. - /// - /// - /// - /// Gets the type converter to use to convert values to the destination type. - /// - /// - public static IConvertTo GetConvertTo(Type sourceType, Type destinationType) - { - // TODO: Support inheriting type converters. - // i.e. getting a type converter for a base of sourceType - - // TODO: Is destinationType required? We don't use it for anything. - lock (s_type2converter) - { - // Lookup in the static registry - IConvertTo converter = s_type2converter[sourceType] as IConvertTo; - - if (converter == null) - { - // Lookup using attributes - converter = GetConverterFromAttribute(sourceType) as IConvertTo; - - if (converter != null) - { - // Store in registry - s_type2converter[sourceType] = converter; - } - } - - return converter; - } - } - - /// - /// Gets the type converter to use to convert values to the destination type. - /// - /// The type being converted to. - /// - /// The type converter instance to use for type conversions or null - /// if no type converter is found. - /// - /// - /// - /// Gets the type converter to use to convert values to the destination type. - /// - /// - public static IConvertFrom GetConvertFrom(Type destinationType) - { - // TODO: Support inheriting type converters. - // i.e. getting a type converter for a base of destinationType - lock (s_type2converter) - { - // Lookup in the static registry - IConvertFrom converter = s_type2converter[destinationType] as IConvertFrom; - - if (converter == null) - { - // Lookup using attributes - converter = GetConverterFromAttribute(destinationType) as IConvertFrom; - - if (converter != null) - { - // Store in registry - s_type2converter[destinationType] = converter; - } - } - - return converter; - } - } - - /// - /// Lookups the type converter to use as specified by the attributes on the - /// destination type. - /// - /// The type being converted to. - /// - /// The type converter instance to use for type conversions or null - /// if no type converter is found. - /// - private static object GetConverterFromAttribute(Type destinationType) - { - // Look for an attribute on the destination type - object[] attributes = destinationType.GetCustomAttributes(typeof(TypeConverterAttribute), true); - if (attributes != null && attributes.Length > 0) - { - TypeConverterAttribute tcAttr = attributes[0] as TypeConverterAttribute; - if (tcAttr != null) - { - Type converterType = SystemInfo.GetTypeFromString(destinationType, tcAttr.ConverterTypeName, false, true); - return CreateConverterInstance(converterType); - } - } - - // Not found converter using attributes - return null; - } - - /// - /// Creates the instance of the type converter. - /// - /// The type of the type converter. - /// - /// The type converter instance to use for type conversions or null - /// if no type converter is found. - /// - /// - /// - /// The type specified for the type converter must implement - /// the or interfaces - /// and must have a public default (no argument) constructor. - /// - /// - private static object CreateConverterInstance(Type converterType) - { - if (converterType == null) - { - throw new ArgumentNullException("converterType", "CreateConverterInstance cannot create instance, converterType is null"); - } - - // Check type is a converter - if (typeof(IConvertFrom).IsAssignableFrom(converterType) || typeof(IConvertTo).IsAssignableFrom(converterType)) - { - try - { - // Create the type converter - return Activator.CreateInstance(converterType); - } - catch (Exception ex) - { - LogLog.Error(declaringType, "Cannot CreateConverterInstance of type [" + converterType.FullName + "], Exception in call to Activator.CreateInstance", ex); - } - } - else - { - LogLog.Error(declaringType, "Cannot CreateConverterInstance of type [" + converterType.FullName + "], type does not implement IConvertFrom or IConvertTo"); - } + foreach (var attribute in attributes) + { + var tcAttr = attribute as TypeConverterAttribute; + if (tcAttr != null) + { + var converterType = SystemInfo.GetTypeFromString(destinationType, tcAttr.ConverterTypeName, false, true); + return CreateConverterInstance(converterType); + } + } - return null; + // Not found converter using attributes + return null; } - /// - /// The fully qualified type of the ConverterRegistry class. - /// - /// - /// Used by the internal logger to record the Type of the - /// log message. - /// - private static readonly Type declaringType = typeof(ConverterRegistry); - - /// - /// Mapping from to type converter. - /// + /// + /// Creates the instance of the type converter. + /// + /// The type of the type converter. + /// + /// The type converter instance to use for type conversions or null + /// if no type converter is found. + /// + /// + /// + /// The type specified for the type converter must implement + /// the or interfaces + /// and must have a public default (no argument) constructor. + /// + /// + private static object CreateConverterInstance(Type converterType) + { + if (converterType == null) + { + throw new ArgumentNullException("converterType", "CreateConverterInstance cannot create instance, converterType is null"); + } + + // Check type is a converter + if (typeof(IConvertFrom).IsAssignableFrom(converterType) || typeof(IConvertTo).IsAssignableFrom(converterType)) + { + try + { + // Create the type converter + return Activator.CreateInstance(converterType); + } + catch(Exception ex) + { + LogLog.Error(declaringType, "Cannot CreateConverterInstance of type ["+converterType.FullName+"], Exception in call to Activator.CreateInstance", ex); + } + } + else + { + LogLog.Error(declaringType, "Cannot CreateConverterInstance of type ["+converterType.FullName+"], type does not implement IConvertFrom or IConvertTo"); + } + return null; + } + + /// + /// The fully qualified type of the ConverterRegistry class. + /// + /// + /// Used by the internal logger to record the Type of the + /// log message. + /// + private static readonly Type declaringType = typeof(ConverterRegistry); + + /// + /// Mapping from to type converter. + /// private static Hashtable s_type2converter = new Hashtable(); - } -} + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/TypeConverters/EncodingConverter.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/TypeConverters/EncodingConverter.cs index c1767ce8be9..eee45603c6e 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/TypeConverters/EncodingConverter.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/TypeConverters/EncodingConverter.cs @@ -1,84 +1,83 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.Util.TypeConverters -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; - using System.Text; +using System; +using System.Text; - /// - /// Supports conversion from string to type. - /// - /// - /// - /// Supports conversion from string to type. - /// - /// - /// - /// - /// - /// Nicko Cadell. - /// Gert Driesen. - internal class EncodingConverter : IConvertFrom +namespace log4net.Util.TypeConverters +{ + /// + /// Supports conversion from string to type. + /// + /// + /// + /// Supports conversion from string to type. + /// + /// + /// + /// + /// + /// Nicko Cadell + /// Gert Driesen + internal class EncodingConverter : IConvertFrom { - /// - /// Can the source type be converted to the type supported by this object. - /// - /// the type to convert. - /// true if the conversion is possible. - /// - /// - /// Returns true if the is - /// the type. - /// - /// - public bool CanConvertFrom(Type sourceType) - { - return sourceType == typeof(string); - } - - /// - /// Overrides the ConvertFrom method of IConvertFrom. - /// - /// the object to convert to an encoding. - /// the encoding. - /// - /// - /// Uses the method to - /// convert the argument to an . - /// - /// - /// - /// The object cannot be converted to the - /// target type. To check for this condition use the - /// method. - /// - public object ConvertFrom(object source) - { - string str = source as string; - if (str != null) - { - return Encoding.GetEncoding(str); - } + /// + /// Can the source type be converted to the type supported by this object + /// + /// the type to convert + /// true if the conversion is possible + /// + /// + /// Returns true if the is + /// the type. + /// + /// + public bool CanConvertFrom(Type sourceType) + { + return (sourceType == typeof(string)); + } - throw ConversionNotSupportedException.Create(typeof(Encoding), source); + /// + /// Overrides the ConvertFrom method of IConvertFrom. + /// + /// the object to convert to an encoding + /// the encoding + /// + /// + /// Uses the method to + /// convert the argument to an . + /// + /// + /// + /// The object cannot be converted to the + /// target type. To check for this condition use the + /// method. + /// + public object ConvertFrom(object source) + { + string str = source as string; + if (str != null) + { + return Encoding.GetEncoding(str); + } + throw ConversionNotSupportedException.Create(typeof(Encoding), source); } - } -} + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/TypeConverters/IConvertFrom.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/TypeConverters/IConvertFrom.cs index b1d01f89c44..4e0824ae223 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/TypeConverters/IConvertFrom.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/TypeConverters/IConvertFrom.cs @@ -1,64 +1,64 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.Util.TypeConverters -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; +using System; - /// - /// Interface supported by type converters. - /// - /// - /// - /// This interface supports conversion from arbitrary types - /// to a single target type. See . - /// - /// - /// Nicko Cadell. - /// Gert Driesen. - public interface IConvertFrom - { - /// - /// Can the source type be converted to the type supported by this object. - /// - /// the type to convert. - /// true if the conversion is possible. - /// - /// - /// Test if the can be converted to the - /// type supported by this converter. - /// - /// - bool CanConvertFrom(Type sourceType); - - /// - /// Convert the source object to the type supported by this object. - /// - /// the object to convert. - /// the converted object. - /// - /// - /// Converts the to the type supported - /// by this converter. - /// - /// - object ConvertFrom(object source); - } -} +namespace log4net.Util.TypeConverters +{ + /// + /// Interface supported by type converters + /// + /// + /// + /// This interface supports conversion from arbitrary types + /// to a single target type. See . + /// + /// + /// Nicko Cadell + /// Gert Driesen + public interface IConvertFrom + { + /// + /// Can the source type be converted to the type supported by this object + /// + /// the type to convert + /// true if the conversion is possible + /// + /// + /// Test if the can be converted to the + /// type supported by this converter. + /// + /// + bool CanConvertFrom(Type sourceType); + + /// + /// Convert the source object to the type supported by this object + /// + /// the object to convert + /// the converted object + /// + /// + /// Converts the to the type supported + /// by this converter. + /// + /// + object ConvertFrom(object source); + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/TypeConverters/IConvertTo.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/TypeConverters/IConvertTo.cs index 1c3f8d453f6..9389abdb673 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/TypeConverters/IConvertTo.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/TypeConverters/IConvertTo.cs @@ -1,64 +1,64 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.Util.TypeConverters -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; +using System; - /// - /// Interface supported by type converters. - /// - /// - /// - /// This interface supports conversion from a single type to arbitrary types. - /// See . - /// - /// - /// Nicko Cadell. - public interface IConvertTo - { - /// - /// Returns whether this converter can convert the object to the specified type. - /// - /// A Type that represents the type you want to convert to. - /// true if the conversion is possible. - /// - /// - /// Test if the type supported by this converter can be converted to the - /// . - /// - /// - bool CanConvertTo(Type targetType); - - /// - /// Converts the given value object to the specified type, using the arguments. - /// - /// the object to convert. - /// The Type to convert the value parameter to. - /// the converted object. - /// - /// - /// Converts the (which must be of the type supported - /// by this converter) to the specified.. - /// - /// - object ConvertTo(object source, Type targetType); - } -} +namespace log4net.Util.TypeConverters +{ + /// + /// Interface supported by type converters + /// + /// + /// + /// This interface supports conversion from a single type to arbitrary types. + /// See . + /// + /// + /// Nicko Cadell + public interface IConvertTo + { + /// + /// Returns whether this converter can convert the object to the specified type + /// + /// A Type that represents the type you want to convert to + /// true if the conversion is possible + /// + /// + /// Test if the type supported by this converter can be converted to the + /// . + /// + /// + bool CanConvertTo(Type targetType); + + /// + /// Converts the given value object to the specified type, using the arguments + /// + /// the object to convert + /// The Type to convert the value parameter to + /// the converted object + /// + /// + /// Converts the (which must be of the type supported + /// by this converter) to the specified.. + /// + /// + object ConvertTo(object source, Type targetType); + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/TypeConverters/IPAddressConverter.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/TypeConverters/IPAddressConverter.cs index 8817ada0b03..7143e8d73e4 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/TypeConverters/IPAddressConverter.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/TypeConverters/IPAddressConverter.cs @@ -1,146 +1,145 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.Util.TypeConverters -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; - using System.Net; +using System; +using System.Net; - /// - /// Supports conversion from string to type. - /// - /// - /// - /// Supports conversion from string to type. - /// - /// - /// - /// - /// Nicko Cadell. - internal class IPAddressConverter : IConvertFrom +namespace log4net.Util.TypeConverters +{ + /// + /// Supports conversion from string to type. + /// + /// + /// + /// Supports conversion from string to type. + /// + /// + /// + /// + /// Nicko Cadell + internal class IPAddressConverter : IConvertFrom { - /// - /// Can the source type be converted to the type supported by this object. - /// - /// the type to convert. - /// true if the conversion is possible. - /// - /// - /// Returns true if the is - /// the type. - /// - /// - public bool CanConvertFrom(Type sourceType) - { - return sourceType == typeof(string); - } - - /// - /// Overrides the ConvertFrom method of IConvertFrom. - /// - /// the object to convert to an IPAddress. - /// the IPAddress. - /// - /// - /// Uses the method to convert the - /// argument to an . - /// If that fails then the string is resolved as a DNS hostname. - /// - /// - /// - /// The object cannot be converted to the - /// target type. To check for this condition use the - /// method. - /// - public object ConvertFrom(object source) - { - string str = source as string; - if (str != null && str.Length > 0) - { - try - { -#if NET_2_0 || NETCF_2_0 - -#if !NETCF_2_0 - // Try an explicit parse of string representation of an IPAddress (v4 or v6) - IPAddress result; - if (IPAddress.TryParse(str, out result)) - { - return result; - } -#endif - - // Try to resolve via DNS. This is a blocking call. - // GetHostEntry works with either an IPAddress string or a host name - IPHostEntry host = Dns.GetHostEntry(str); - if (host != null && - host.AddressList != null && - host.AddressList.Length > 0 && - host.AddressList[0] != null) - { - return host.AddressList[0]; - } -#else - // Before .NET 2 we need to try to parse the IPAddress from the string first - - // Check if the string only contains IP address valid chars - if (str.Trim(validIpAddressChars).Length == 0) - { - try - { - // try to parse the string as an IP address - return IPAddress.Parse(str); - } - catch(FormatException) - { - // Ignore a FormatException, try to resolve via DNS - } - } - - // Try to resolve via DNS. This is a blocking call. -#if NETSTANDARD1_3 - IPHostEntry host = Dns.GetHostEntryAsync(str).GetAwaiter().GetResult(); -#else - IPHostEntry host = Dns.GetHostByName(str); -#endif - if (host != null && - host.AddressList != null && - host.AddressList.Length > 0 && - host.AddressList[0] != null) - { - return host.AddressList[0]; - } -#endif - } - catch (Exception ex) - { - throw ConversionNotSupportedException.Create(typeof(IPAddress), source, ex); - } - } + /// + /// Can the source type be converted to the type supported by this object + /// + /// the type to convert + /// true if the conversion is possible + /// + /// + /// Returns true if the is + /// the type. + /// + /// + public bool CanConvertFrom(Type sourceType) + { + return (sourceType == typeof(string)); + } + + /// + /// Overrides the ConvertFrom method of IConvertFrom. + /// + /// the object to convert to an IPAddress + /// the IPAddress + /// + /// + /// Uses the method to convert the + /// argument to an . + /// If that fails then the string is resolved as a DNS hostname. + /// + /// + /// + /// The object cannot be converted to the + /// target type. To check for this condition use the + /// method. + /// + public object ConvertFrom(object source) + { + string str = source as string; + if (str != null && str.Length > 0) + { + try + { +#if NET_2_0 || NETCF_2_0 + +#if !NETCF_2_0 + // Try an explicit parse of string representation of an IPAddress (v4 or v6) + IPAddress result; + if (IPAddress.TryParse(str, out result)) + { + return result; + } +#endif + + // Try to resolve via DNS. This is a blocking call. + // GetHostEntry works with either an IPAddress string or a host name + IPHostEntry host = Dns.GetHostEntry(str); + if (host != null && + host.AddressList != null && + host.AddressList.Length > 0 && + host.AddressList[0] != null) + { + return host.AddressList[0]; + } +#else + // Before .NET 2 we need to try to parse the IPAddress from the string first + + // Check if the string only contains IP address valid chars + if (str.Trim(validIpAddressChars).Length == 0) + { + try + { + // try to parse the string as an IP address + return IPAddress.Parse(str); + } + catch(FormatException) + { + // Ignore a FormatException, try to resolve via DNS + } + } - throw ConversionNotSupportedException.Create(typeof(IPAddress), source); + // Try to resolve via DNS. This is a blocking call. +#if NETSTANDARD + IPHostEntry host = Dns.GetHostEntryAsync(str).GetAwaiter().GetResult(); +#else + IPHostEntry host = Dns.GetHostByName(str); +#endif + if (host != null && + host.AddressList != null && + host.AddressList.Length > 0 && + host.AddressList[0] != null) + { + return host.AddressList[0]; + } +#endif + } + catch(Exception ex) + { + throw ConversionNotSupportedException.Create(typeof(IPAddress), source, ex); + } + } + throw ConversionNotSupportedException.Create(typeof(IPAddress), source); } - /// - /// Valid characters in an IPv4 or IPv6 address string. (Does not support subnets). - /// - private static readonly char[] validIpAddressChars = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'A', 'B', 'C', 'D', 'E', 'F', 'x', 'X', '.', ':', '%' }; - } -} + /// + /// Valid characters in an IPv4 or IPv6 address string. (Does not support subnets) + /// + private static readonly char[] validIpAddressChars = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'A', 'B', 'C', 'D', 'E', 'F', 'x', 'X', '.', ':', '%' }; + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/TypeConverters/PatternLayoutConverter.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/TypeConverters/PatternLayoutConverter.cs index d5fb5cb593c..ecaeca7629b 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/TypeConverters/PatternLayoutConverter.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/TypeConverters/PatternLayoutConverter.cs @@ -1,90 +1,89 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.Util.TypeConverters -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; - using System.Text; +using System; +using System.Text; - using log4net.Layout; +using log4net.Layout; - /// - /// Supports conversion from string to type. - /// - /// - /// - /// Supports conversion from string to type. - /// - /// - /// The string is used as the - /// of the . - /// - /// - /// - /// - /// - /// Nicko Cadell. - internal class PatternLayoutConverter : IConvertFrom +namespace log4net.Util.TypeConverters +{ + /// + /// Supports conversion from string to type. + /// + /// + /// + /// Supports conversion from string to type. + /// + /// + /// The string is used as the + /// of the . + /// + /// + /// + /// + /// + /// Nicko Cadell + internal class PatternLayoutConverter : IConvertFrom { - /// - /// Can the source type be converted to the type supported by this object. - /// - /// the type to convert. - /// true if the conversion is possible. - /// - /// - /// Returns true if the is - /// the type. - /// - /// - public bool CanConvertFrom(System.Type sourceType) - { - return sourceType == typeof(string); - } - - /// - /// Overrides the ConvertFrom method of IConvertFrom. - /// - /// the object to convert to a PatternLayout. - /// the PatternLayout. - /// - /// - /// Creates and returns a new using - /// the as the - /// . - /// - /// - /// - /// The object cannot be converted to the - /// target type. To check for this condition use the - /// method. - /// - public object ConvertFrom(object source) - { - string str = source as string; - if (str != null) - { - return new PatternLayout(str); - } + /// + /// Can the source type be converted to the type supported by this object + /// + /// the type to convert + /// true if the conversion is possible + /// + /// + /// Returns true if the is + /// the type. + /// + /// + public bool CanConvertFrom(Type sourceType) + { + return (sourceType == typeof(string)); + } - throw ConversionNotSupportedException.Create(typeof(PatternLayout), source); + /// + /// Overrides the ConvertFrom method of IConvertFrom. + /// + /// the object to convert to a PatternLayout + /// the PatternLayout + /// + /// + /// Creates and returns a new using + /// the as the + /// . + /// + /// + /// + /// The object cannot be converted to the + /// target type. To check for this condition use the + /// method. + /// + public object ConvertFrom(object source) + { + string str = source as string; + if (str != null) + { + return new PatternLayout(str); + } + throw ConversionNotSupportedException.Create(typeof(PatternLayout), source); } - } -} + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/TypeConverters/PatternStringConverter.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/TypeConverters/PatternStringConverter.cs index 79f59b45014..f4b3c8bd22f 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/TypeConverters/PatternStringConverter.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/TypeConverters/PatternStringConverter.cs @@ -1,139 +1,130 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -#if NETSTANDARD1_3 -using System.Reflection; -#endif -using System.Text; +using System; -using log4net.Util; - -namespace log4net.Util.TypeConverters -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; - - /// - /// Convert between string and . - /// - /// - /// - /// Supports conversion from string to type, - /// and from a type to a string. - /// - /// - /// The string is used as the - /// of the . - /// - /// - /// - /// - /// - /// Nicko Cadell. - internal class PatternStringConverter : IConvertTo, IConvertFrom +namespace log4net.Util.TypeConverters +{ + /// + /// Convert between string and + /// + /// + /// + /// Supports conversion from string to type, + /// and from a type to a string. + /// + /// + /// The string is used as the + /// of the . + /// + /// + /// + /// + /// + /// Nicko Cadell + internal class PatternStringConverter : IConvertTo, IConvertFrom { - /// - /// Can the target type be converted to the type supported by this object. - /// - /// A that represents the type you want to convert to. - /// true if the conversion is possible. - /// - /// - /// Returns true if the is - /// assignable from a type. - /// - /// - public bool CanConvertTo(Type targetType) - { - return typeof(string).IsAssignableFrom(targetType); - } - - /// - /// Converts the given value object to the specified type, using the arguments. - /// - /// the object to convert. - /// The Type to convert the value parameter to. - /// the converted object. - /// - /// - /// Uses the method to convert the - /// argument to a . - /// - /// - /// - /// The object cannot be converted to the - /// . To check for this condition use the - /// method. - /// - public object ConvertTo(object source, Type targetType) - { - PatternString patternString = source as PatternString; - if (patternString != null && this.CanConvertTo(targetType)) - { - return patternString.Format(); - } + /// + /// Can the target type be converted to the type supported by this object + /// + /// A that represents the type you want to convert to + /// true if the conversion is possible + /// + /// + /// Returns true if the is + /// assignable from a type. + /// + /// + public bool CanConvertTo(Type targetType) + { + return (typeof(string).IsAssignableFrom(targetType)); + } - throw ConversionNotSupportedException.Create(targetType, source); + /// + /// Converts the given value object to the specified type, using the arguments + /// + /// the object to convert + /// The Type to convert the value parameter to + /// the converted object + /// + /// + /// Uses the method to convert the + /// argument to a . + /// + /// + /// + /// The object cannot be converted to the + /// . To check for this condition use the + /// method. + /// + public object ConvertTo(object source, Type targetType) + { + PatternString patternString = source as PatternString; + if (patternString != null && this.CanConvertTo(targetType)) + { + return patternString.Format(); + } + throw ConversionNotSupportedException.Create(targetType, source); } - /// - /// Can the source type be converted to the type supported by this object. - /// - /// the type to convert. - /// true if the conversion is possible. - /// - /// - /// Returns true if the is - /// the type. - /// - /// - public bool CanConvertFrom(System.Type sourceType) - { - return sourceType == typeof(string); - } - - /// - /// Overrides the ConvertFrom method of IConvertFrom. - /// - /// the object to convert to a PatternString. - /// the PatternString. - /// - /// - /// Creates and returns a new using - /// the as the - /// . - /// - /// - /// - /// The object cannot be converted to the - /// target type. To check for this condition use the - /// method. - /// - public object ConvertFrom(object source) - { - string str = source as string; - if (str != null) - { - return new PatternString(str); - } + /// + /// Can the source type be converted to the type supported by this object + /// + /// the type to convert + /// true if the conversion is possible + /// + /// + /// Returns true if the is + /// the type. + /// + /// + public bool CanConvertFrom(Type sourceType) + { + return (sourceType == typeof(string)); + } - throw ConversionNotSupportedException.Create(typeof(PatternString), source); + /// + /// Overrides the ConvertFrom method of IConvertFrom. + /// + /// the object to convert to a PatternString + /// the PatternString + /// + /// + /// Creates and returns a new using + /// the as the + /// . + /// + /// + /// + /// The object cannot be converted to the + /// target type. To check for this condition use the + /// method. + /// + public object ConvertFrom(object source) + { + string str = source as string; + if (str != null) + { + return new PatternString(str); + } + throw ConversionNotSupportedException.Create(typeof(PatternString), source); } - } -} + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/TypeConverters/TypeConverter.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/TypeConverters/TypeConverter.cs index c889203809a..989a60271cf 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/TypeConverters/TypeConverter.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/TypeConverters/TypeConverter.cs @@ -1,93 +1,90 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -#if NETSTANDARD1_3 -using System.Reflection; -#endif - -namespace log4net.Util.TypeConverters -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; - using System.Text; +using System; +#if NETSTANDARD1_3 +using System.Reflection; +#endif - /// - /// Supports conversion from string to type. - /// - /// - /// - /// Supports conversion from string to type. - /// - /// - /// - /// - /// - /// Nicko Cadell. - internal class TypeConverter : IConvertFrom +namespace log4net.Util.TypeConverters +{ + /// + /// Supports conversion from string to type. + /// + /// + /// + /// Supports conversion from string to type. + /// + /// + /// + /// + /// + /// Nicko Cadell + internal class TypeConverter : IConvertFrom { - /// - /// Can the source type be converted to the type supported by this object. - /// - /// the type to convert. - /// true if the conversion is possible. - /// - /// - /// Returns true if the is - /// the type. - /// - /// - public bool CanConvertFrom(Type sourceType) - { - return sourceType == typeof(string); - } - - /// - /// Overrides the ConvertFrom method of IConvertFrom. - /// - /// the object to convert to a Type. - /// the Type. - /// - /// - /// Uses the method to convert the - /// argument to a . - /// Additional effort is made to locate partially specified types - /// by searching the loaded assemblies. - /// - /// - /// - /// The object cannot be converted to the - /// target type. To check for this condition use the - /// method. - /// - public object ConvertFrom(object source) - { - string str = source as string; - if (str != null) - { -#if NETSTANDARD1_3 // TODO can we use ComponentModel here? - return SystemInfo.GetTypeFromString(GetType().GetTypeInfo().Assembly, str, true, true); -#else - return SystemInfo.GetTypeFromString(str, true, true); -#endif - } + /// + /// Can the source type be converted to the type supported by this object + /// + /// the type to convert + /// true if the conversion is possible + /// + /// + /// Returns true if the is + /// the type. + /// + /// + public bool CanConvertFrom(Type sourceType) + { + return (sourceType == typeof(string)); + } - throw ConversionNotSupportedException.Create(typeof(Type), source); + /// + /// Overrides the ConvertFrom method of IConvertFrom. + /// + /// the object to convert to a Type + /// the Type + /// + /// + /// Uses the method to convert the + /// argument to a . + /// Additional effort is made to locate partially specified types + /// by searching the loaded assemblies. + /// + /// + /// + /// The object cannot be converted to the + /// target type. To check for this condition use the + /// method. + /// + public object ConvertFrom(object source) + { + string str = source as string; + if (str != null) + { +#if NETSTANDARD1_3 // TODO can we use ComponentModel here? + return SystemInfo.GetTypeFromString(GetType().GetTypeInfo().Assembly, str, true, true); +#else + return SystemInfo.GetTypeFromString(str, true, true); +#endif + } + throw ConversionNotSupportedException.Create(typeof(Type), source); } - } -} + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/TypeConverters/TypeConverterAttribute.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/TypeConverters/TypeConverterAttribute.cs index 2682acb88c3..b19d046bc4c 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/TypeConverters/TypeConverterAttribute.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/TypeConverters/TypeConverterAttribute.cs @@ -1,112 +1,109 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -namespace log4net.Util.TypeConverters -{ - // - // Licensed to the Apache Software Foundation (ASF) under one or more - // contributor license agreements. See the NOTICE file distributed with - // this work for additional information regarding copyright ownership. - // The ASF licenses this file to you under the Apache License, Version 2.0 - // (the "License"); you may not use this file except in compliance with - // the License. You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - using System; +using System; - /// - /// Attribute used to associate a type converter. - /// - /// - /// - /// Class and Interface level attribute that specifies a type converter - /// to use with the associated type. - /// - /// - /// To associate a type converter with a target type apply a - /// TypeConverterAttribute to the target type. Specify the - /// type of the type converter on the attribute. - /// - /// - /// Nicko Cadell. - /// Gert Driesen. - [AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.Enum)] - public sealed class TypeConverterAttribute : Attribute +namespace log4net.Util.TypeConverters +{ + /// + /// Attribute used to associate a type converter + /// + /// + /// + /// Class and Interface level attribute that specifies a type converter + /// to use with the associated type. + /// + /// + /// To associate a type converter with a target type apply a + /// TypeConverterAttribute to the target type. Specify the + /// type of the type converter on the attribute. + /// + /// + /// Nicko Cadell + /// Gert Driesen + [AttributeUsage(AttributeTargets.Class|AttributeTargets.Interface|AttributeTargets.Enum)] + public sealed class TypeConverterAttribute : Attribute { - /// - /// The string type name of the type converter. - /// + /// + /// The string type name of the type converter + /// private string m_typeName = null; /// - /// Initializes a new instance of the class. - /// Default constructor. - /// - /// - /// - /// Default constructor. - /// - /// - public TypeConverterAttribute() - { + /// Default constructor + /// + /// + /// + /// Default constructor + /// + /// + public TypeConverterAttribute() + { } /// - /// Initializes a new instance of the class. - /// Create a new type converter attribute for the specified type name. - /// - /// The string type name of the type converter. - /// - /// - /// The type specified must implement the - /// or the interfaces. - /// - /// - public TypeConverterAttribute(string typeName) - { - this.m_typeName = typeName; + /// Create a new type converter attribute for the specified type name + /// + /// The string type name of the type converter + /// + /// + /// The type specified must implement the + /// or the interfaces. + /// + /// + public TypeConverterAttribute(string typeName) + { + this.m_typeName = typeName; } /// - /// Initializes a new instance of the class. - /// Create a new type converter attribute for the specified type. - /// - /// The type of the type converter. - /// - /// - /// The type specified must implement the - /// or the interfaces. - /// - /// - public TypeConverterAttribute(Type converterType) - { - this.m_typeName = log4net.Util.SystemInfo.AssemblyQualifiedName(converterType); + /// Create a new type converter attribute for the specified type + /// + /// The type of the type converter + /// + /// + /// The type specified must implement the + /// or the interfaces. + /// + /// + public TypeConverterAttribute(Type converterType) + { + this.m_typeName = SystemInfo.AssemblyQualifiedName(converterType); } - /// - /// Gets or sets the string type name of the type converter. - /// - /// - /// The string type name of the type converter. - /// - /// - /// - /// The type specified must implement the - /// or the interfaces. - /// - /// - public string ConverterTypeName - { - get { return this.m_typeName; } - set { this.m_typeName = value; } - } - } -} + /// + /// The string type name of the type converter + /// + /// + /// The string type name of the type converter + /// + /// + /// + /// The type specified must implement the + /// or the interfaces. + /// + /// + public string ConverterTypeName + { + get { return this.m_typeName; } + set { this.m_typeName = value ; } + } + } +} diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/Util/WindowsSecurityContext.cs b/DNN Platform/DotNetNuke.Log4net/log4net/Util/WindowsSecurityContext.cs index 7d9a6a341d8..4c7e6da12e0 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/Util/WindowsSecurityContext.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/Util/WindowsSecurityContext.cs @@ -1,215 +1,214 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to you under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -// .NET Compact Framework 1.0 has no support for WindowsIdentity -#if !NETCF -// MONO 1.0 has no support for Win32 Logon APIs -#if !MONO -// SSCLI 1.0 has no support for Win32 Logon APIs -#if !SSCLI -// We don't want framework or platform specific code in the CLI version of log4net -#if !CLI_1_0 - -using System; -using System.Runtime.InteropServices; -using System.Security.Permissions; -using System.Security.Principal; +#if NET_2_0 +// .NET Compact Framework 1.0 has no support for WindowsIdentity +#if !NETCF +// MONO 1.0 has no support for Win32 Logon APIs +#if !MONO +// SSCLI 1.0 has no support for Win32 Logon APIs +#if !SSCLI +// We don't want framework or platform specific code in the CLI version of log4net +#if !CLI_1_0 -using log4net.Core; - -namespace log4net.Util -{ - /// - /// Impersonate a Windows Account. - /// - /// - /// - /// This impersonates a Windows account. - /// - /// - /// How the impersonation is done depends on the value of . - /// This allows the context to either impersonate a set of user credentials specified - /// using username, domain name and password or to revert to the process credentials. - /// - /// - public class WindowsSecurityContext : SecurityContext, IOptionHandler - { - /// - /// The impersonation modes for the . - /// - /// - /// - /// See the property for - /// details. - /// - /// - public enum ImpersonationMode - { - /// - /// Impersonate a user using the credentials supplied - /// - User, - - /// - /// Revert this the thread to the credentials of the process - /// - Process, +using System; +using System.Runtime.InteropServices; +using System.Security.Principal; +using System.Security.Permissions; + +using log4net.Core; + +namespace log4net.Util +{ + /// + /// Impersonate a Windows Account + /// + /// + /// + /// This impersonates a Windows account. + /// + /// + /// How the impersonation is done depends on the value of . + /// This allows the context to either impersonate a set of user credentials specified + /// using username, domain name and password or to revert to the process credentials. + /// + /// + public class WindowsSecurityContext : SecurityContext, IOptionHandler + { + /// + /// The impersonation modes for the + /// + /// + /// + /// See the property for + /// details. + /// + /// + public enum ImpersonationMode + { + /// + /// Impersonate a user using the credentials supplied + /// + User, + + /// + /// Revert this the thread to the credentials of the process + /// + Process } - private ImpersonationMode m_impersonationMode = ImpersonationMode.User; - private string m_userName; - private string m_domainName = Environment.MachineName; - private string m_password; + private ImpersonationMode m_impersonationMode = ImpersonationMode.User; + private string m_userName; + private string m_domainName = Environment.MachineName; + private string m_password; private WindowsIdentity m_identity; /// - /// Initializes a new instance of the class. - /// Default constructor. - /// - /// - /// - /// Default constructor. - /// - /// - public WindowsSecurityContext() - { + /// Default constructor + /// + /// + /// + /// Default constructor + /// + /// + public WindowsSecurityContext() + { } - /// - /// Gets or sets the impersonation mode for this security context. - /// - /// - /// The impersonation mode for this security context. - /// - /// - /// - /// Impersonate either a user with user credentials or - /// revert this thread to the credentials of the process. - /// The value is one of the - /// enum. - /// - /// - /// The default value is . - /// - /// - /// When the mode is set to - /// the user's credentials are established using the - /// , and - /// values. - /// - /// - /// When the mode is set to - /// no other properties need to be set. If the calling thread is - /// impersonating then it will be reverted back to the process credentials. - /// - /// - public ImpersonationMode Credentials - { - get { return this.m_impersonationMode; } - set { this.m_impersonationMode = value; } - } - - /// - /// Gets or sets the Windows username for this security context. - /// - /// - /// The Windows username for this security context. - /// - /// - /// - /// This property must be set if - /// is set to (the default setting). - /// - /// - public string UserName - { - get { return this.m_userName; } - set { this.m_userName = value; } - } - - /// - /// Gets or sets the Windows domain name for this security context. - /// - /// - /// The Windows domain name for this security context. - /// - /// - /// - /// The default value for is the local machine name - /// taken from the property. - /// - /// - /// This property must be set if - /// is set to (the default setting). - /// - /// - public string DomainName - { - get { return this.m_domainName; } - set { this.m_domainName = value; } - } - - /// - /// Sets the password for the Windows account specified by the and properties. - /// - /// - /// The password for the Windows account specified by the and properties. - /// - /// - /// - /// This property must be set if - /// is set to (the default setting). - /// - /// - public string Password - { - set { this.m_password = value; } + /// + /// Gets or sets the impersonation mode for this security context + /// + /// + /// The impersonation mode for this security context + /// + /// + /// + /// Impersonate either a user with user credentials or + /// revert this thread to the credentials of the process. + /// The value is one of the + /// enum. + /// + /// + /// The default value is + /// + /// + /// When the mode is set to + /// the user's credentials are established using the + /// , and + /// values. + /// + /// + /// When the mode is set to + /// no other properties need to be set. If the calling thread is + /// impersonating then it will be reverted back to the process credentials. + /// + /// + public ImpersonationMode Credentials + { + get { return this.m_impersonationMode; } + set { this.m_impersonationMode = value; } } - /// - /// Initialize the SecurityContext based on the options set. - /// - /// - /// - /// This is part of the delayed object - /// activation scheme. The method must - /// be called on this object after the configuration properties have - /// been set. Until is called this - /// object is in an undefined state and must not be used. - /// - /// - /// If any of the configuration properties are modified then - /// must be called again. - /// - /// - /// The security context will try to Logon the specified user account and - /// capture a primary token for impersonation. - /// - /// - /// The required , - /// or properties were not specified. - public void ActivateOptions() - { - if (this.m_impersonationMode == ImpersonationMode.User) - { + /// + /// Gets or sets the Windows username for this security context + /// + /// + /// The Windows username for this security context + /// + /// + /// + /// This property must be set if + /// is set to (the default setting). + /// + /// + public string UserName + { + get { return this.m_userName; } + set { this.m_userName = value; } + } + + /// + /// Gets or sets the Windows domain name for this security context + /// + /// + /// The Windows domain name for this security context + /// + /// + /// + /// The default value for is the local machine name + /// taken from the property. + /// + /// + /// This property must be set if + /// is set to (the default setting). + /// + /// + public string DomainName + { + get { return this.m_domainName; } + set { this.m_domainName = value; } + } + + /// + /// Sets the password for the Windows account specified by the and properties. + /// + /// + /// The password for the Windows account specified by the and properties. + /// + /// + /// + /// This property must be set if + /// is set to (the default setting). + /// + /// + public string Password + { + set { this.m_password = value; } + } + + /// + /// Initialize the SecurityContext based on the options set. + /// + /// + /// + /// This is part of the delayed object + /// activation scheme. The method must + /// be called on this object after the configuration properties have + /// been set. Until is called this + /// object is in an undefined state and must not be used. + /// + /// + /// If any of the configuration properties are modified then + /// must be called again. + /// + /// + /// The security context will try to Logon the specified user account and + /// capture a primary token for impersonation. + /// + /// + /// The required , + /// or properties were not specified. + public void ActivateOptions() + { + if (this.m_impersonationMode == ImpersonationMode.User) + { if (this.m_userName == null) { throw new ArgumentNullException("m_userName"); @@ -225,158 +224,154 @@ public void ActivateOptions() throw new ArgumentNullException("m_password"); } - this.m_identity = LogonUser(this.m_userName, this.m_domainName, this.m_password); - } + this.m_identity = LogonUser(this.m_userName, this.m_domainName, this.m_password); + } } - /// - /// Impersonate the Windows account specified by the and properties. - /// - /// caller provided state. - /// - /// An instance that will revoke the impersonation of this SecurityContext. - /// - /// - /// - /// Depending on the property either - /// impersonate a user using credentials supplied or revert - /// to the process credentials. - /// - /// - public override IDisposable Impersonate(object state) - { - if (this.m_impersonationMode == ImpersonationMode.User) - { - if (this.m_identity != null) - { - return new DisposableImpersonationContext(this.m_identity.Impersonate()); - } - } - else if (this.m_impersonationMode == ImpersonationMode.Process) - { - // Impersonate(0) will revert to the process credentials - return new DisposableImpersonationContext(WindowsIdentity.Impersonate(IntPtr.Zero)); - } - - return null; + /// + /// Impersonate the Windows account specified by the and properties. + /// + /// caller provided state + /// + /// An instance that will revoke the impersonation of this SecurityContext + /// + /// + /// + /// Depending on the property either + /// impersonate a user using credentials supplied or revert + /// to the process credentials. + /// + /// + public override IDisposable Impersonate(object state) + { + if (this.m_impersonationMode == ImpersonationMode.User) + { + if (this.m_identity != null) + { + return new DisposableImpersonationContext(this.m_identity.Impersonate()); + } + } + else if (this.m_impersonationMode == ImpersonationMode.Process) + { + // Impersonate(0) will revert to the process credentials + return new DisposableImpersonationContext(WindowsIdentity.Impersonate(IntPtr.Zero)); + } + return null; } - /// - /// Create a given the userName, domainName and password. - /// - /// the user name. - /// the domain name. - /// the password. - /// the for the account specified. - /// - /// - /// Uses the Windows API call LogonUser to get a principal token for the account. This - /// token is used to initialize the WindowsIdentity. - /// - /// -#if NET_4_0 || MONO_4_0 - [System.Security.SecuritySafeCritical] -#endif - [System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Demand, UnmanagedCode = true)] - private static WindowsIdentity LogonUser(string userName, string domainName, string password) - { - const int LOGON32_PROVIDER_DEFAULT = 0; + /// + /// Create a given the userName, domainName and password. + /// + /// the user name + /// the domain name + /// the password + /// the for the account specified + /// + /// + /// Uses the Windows API call LogonUser to get a principal token for the account. This + /// token is used to initialize the WindowsIdentity. + /// + /// +#if NET_4_0 || MONO_4_0 + [System.Security.SecuritySafeCritical] +#endif + [SecurityPermission(SecurityAction.Demand, UnmanagedCode = true)] + private static WindowsIdentity LogonUser(string userName, string domainName, string password) + { + const int LOGON32_PROVIDER_DEFAULT = 0; + //This parameter causes LogonUser to create a primary token. + const int LOGON32_LOGON_INTERACTIVE = 2; + + // Call LogonUser to obtain a handle to an access token. + IntPtr tokenHandle = IntPtr.Zero; + if(!LogonUser(userName, domainName, password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, ref tokenHandle)) + { + NativeError error = NativeError.GetLastError(); + throw new Exception("Failed to LogonUser ["+userName+"] in Domain ["+domainName+"]. Error: "+ error.ToString()); + } + + const int SecurityImpersonation = 2; + IntPtr dupeTokenHandle = IntPtr.Zero; + if(!DuplicateToken(tokenHandle, SecurityImpersonation, ref dupeTokenHandle)) + { + NativeError error = NativeError.GetLastError(); + if (tokenHandle != IntPtr.Zero) + { + CloseHandle(tokenHandle); + } + throw new Exception("Failed to DuplicateToken after LogonUser. Error: " + error.ToString()); + } - // This parameter causes LogonUser to create a primary token. - const int LOGON32_LOGON_INTERACTIVE = 2; - - // Call LogonUser to obtain a handle to an access token. - IntPtr tokenHandle = IntPtr.Zero; - if (!LogonUser(userName, domainName, password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, ref tokenHandle)) - { - NativeError error = NativeError.GetLastError(); - throw new Exception("Failed to LogonUser [" + userName + "] in Domain [" + domainName + "]. Error: " + error.ToString()); - } - - const int SecurityImpersonation = 2; - IntPtr dupeTokenHandle = IntPtr.Zero; - if (!DuplicateToken(tokenHandle, SecurityImpersonation, ref dupeTokenHandle)) - { - NativeError error = NativeError.GetLastError(); - if (tokenHandle != IntPtr.Zero) - { - CloseHandle(tokenHandle); - } + WindowsIdentity identity = new WindowsIdentity(dupeTokenHandle); - throw new Exception("Failed to DuplicateToken after LogonUser. Error: " + error.ToString()); - } - - WindowsIdentity identity = new WindowsIdentity(dupeTokenHandle); - - // Free the tokens. - if (dupeTokenHandle != IntPtr.Zero) - { - CloseHandle(dupeTokenHandle); - } + // Free the tokens. + if (dupeTokenHandle != IntPtr.Zero) + { + CloseHandle(dupeTokenHandle); + } + if (tokenHandle != IntPtr.Zero) + { + CloseHandle(tokenHandle); + } - if (tokenHandle != IntPtr.Zero) - { - CloseHandle(tokenHandle); - } - - return identity; + return identity; } - [DllImport("advapi32.dll", SetLastError = true)] - private static extern bool LogonUser(string lpszUsername, string lpszDomain, string lpszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken); - - [DllImport("kernel32.dll", CharSet = CharSet.Auto)] - private static extern bool CloseHandle(IntPtr handle); - - [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)] + [DllImport("advapi32.dll", SetLastError = true)] + private static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken); + + [DllImport("kernel32.dll", CharSet=CharSet.Auto)] + private static extern bool CloseHandle(IntPtr handle); + + [DllImport("advapi32.dll", CharSet=CharSet.Auto, SetLastError=true)] private static extern bool DuplicateToken(IntPtr ExistingTokenHandle, int SECURITY_IMPERSONATION_LEVEL, ref IntPtr DuplicateTokenHandle); - /// - /// Adds to . - /// - /// - /// - /// Helper class to expose the - /// through the interface. - /// - /// - private sealed class DisposableImpersonationContext : IDisposable - { + /// + /// Adds to + /// + /// + /// + /// Helper class to expose the + /// through the interface. + /// + /// + private sealed class DisposableImpersonationContext : IDisposable + { private readonly WindowsImpersonationContext m_impersonationContext; /// - /// Initializes a new instance of the class. - /// Constructor. - /// - /// the impersonation context being wrapped. - /// - /// - /// Constructor. - /// - /// - public DisposableImpersonationContext(WindowsImpersonationContext impersonationContext) - { - this.m_impersonationContext = impersonationContext; - } - - /// - /// Revert the impersonation. - /// - /// - /// - /// Revert the impersonation. - /// - /// - public void Dispose() - { - this.m_impersonationContext.Undo(); - } + /// Constructor + /// + /// the impersonation context being wrapped + /// + /// + /// Constructor + /// + /// + public DisposableImpersonationContext(WindowsImpersonationContext impersonationContext) + { + this.m_impersonationContext = impersonationContext; + } + + /// + /// Revert the impersonation + /// + /// + /// + /// Revert the impersonation + /// + /// + public void Dispose() + { + this.m_impersonationContext.Undo(); + } } - } -} - -#endif // !CLI_1_0 -#endif // !SSCLI -#endif // !MONO -#endif // !NETCF - + } +} + +#endif // !CLI_1_0 +#endif // !SSCLI +#endif // !MONO +#endif // !NETCF +#endif // NET_2_0 + From 8155908136323457e1d21b74b97e10b0de7acda1 Mon Sep 17 00:00:00 2001 From: Peter Donker Date: Tue, 19 Jul 2022 21:39:43 +0200 Subject: [PATCH 2/2] Update DNN Platform/DotNetNuke.Log4net/log4net/AssemblyInfo.cs Good idea Co-authored-by: Brian Dukes --- DNN Platform/DotNetNuke.Log4net/log4net/AssemblyInfo.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/DNN Platform/DotNetNuke.Log4net/log4net/AssemblyInfo.cs b/DNN Platform/DotNetNuke.Log4net/log4net/AssemblyInfo.cs index d587b76f117..9097b6d84fe 100644 --- a/DNN Platform/DotNetNuke.Log4net/log4net/AssemblyInfo.cs +++ b/DNN Platform/DotNetNuke.Log4net/log4net/AssemblyInfo.cs @@ -125,7 +125,7 @@ [assembly: AssemblyTitle("Apache log4net for Shared Source CLI")] #else [assembly: AssemblyInformationalVersionAttribute("2.0.14.0")] -[assembly: AssemblyTitle("Apache log4net")] +[assembly: AssemblyTitle("DotNetNuke.log4net")] #endif #if DEBUG