public void TestFixtureSetUp()
        {
            appender = new AsyncAdoAppender
            {
                CommandType = CommandType.Text,
                ConnectionString = connectionString,
                CommandText = commandText,
                ConnectionType = connectionType
            };

            appender.AddParameter(new AdoNetAppenderParameter { DbType = DbType.DateTime, ParameterName = "@log_date", Layout = new RawUtcTimeStampLayout() });
            appender.AddParameter(new AdoNetAppenderParameter { DbType = DbType.String, Size = 255, ParameterName = "@thread", Layout = new Layout2RawLayoutAdapter(new PatternLayout("%thread")) });
            appender.AddParameter(new AdoNetAppenderParameter { DbType = DbType.String, Size = 40, ParameterName = "@log_level", Layout = new Layout2RawLayoutAdapter(new PatternLayout("%level")) });
            appender.AddParameter(new AdoNetAppenderParameter { DbType = DbType.String, Size = 255, ParameterName = "@logger", Layout = new Layout2RawLayoutAdapter(new PatternLayout("%logger")) });
            appender.AddParameter(new AdoNetAppenderParameter { DbType = DbType.String, Size = 4000, ParameterName = "@message", Layout = new Layout2RawLayoutAdapter(new PatternLayout("%message")) });
            appender.AddParameter(new AdoNetAppenderParameter { DbType = DbType.String, Size = 4000, ParameterName = "@exception", Layout = new Layout2RawLayoutAdapter(new PatternLayout("%exception")) });
            appender.AddParameter(new AdoNetAppenderParameter { DbType = DbType.String, Size = 200, ParameterName = "@application", Layout = new Layout2RawLayoutAdapter(new PatternLayout(ApplicationName)) });

            appender.Threshold = ErrorLevel;
            appender.BufferSize = -1;
            appender.ActivateOptions();

            rep = LogManager.CreateRepository(Guid.NewGuid().ToString());
            BasicConfigurator.Configure(rep, appender);
            LogsDBAccess.RemoveMatchingLogEntries(ErrorLevel, ErrorMessage, ApplicationName);
        }
			public ConfigureAndWatchHandler(ILoggerRepository repository, FileInfo configFile)
			{
				m_repository = repository;
				m_configFile = configFile;

				// Create a new FileSystemWatcher and set its properties.
				m_watcher = new FileSystemWatcher();

				m_watcher.Path = m_configFile.DirectoryName;
				m_watcher.Filter = m_configFile.Name;

				// Set the notification filters
				m_watcher.NotifyFilter = NotifyFilters.CreationTime | NotifyFilters.LastWrite | NotifyFilters.FileName;

				// Add event handlers. OnChanged will do for all event handlers that fire a FileSystemEventArgs
				m_watcher.Changed += new FileSystemEventHandler(ConfigureAndWatchHandler_OnChanged);
				m_watcher.Created += new FileSystemEventHandler(ConfigureAndWatchHandler_OnChanged);
				m_watcher.Deleted += new FileSystemEventHandler(ConfigureAndWatchHandler_OnChanged);
				m_watcher.Renamed += new RenamedEventHandler(ConfigureAndWatchHandler_OnRenamed);

				// Begin watching.
				m_watcher.EnableRaisingEvents = true;

				// Create the timer that will be used to deliver events. Set as disabled
				m_timer = new Timer(new TimerCallback(OnWatchedFileChange), null, Timeout.Infinite, Timeout.Infinite);
			}
예제 #3
0
        /// <summary>
        ///		Registers loggers within the <see cref="AppDomain"/>
        /// and creates the <see cref="ILoggerRepository"/> using 
        /// provided <paramref name="loggerConfiguration"/>.
        /// 
        /// Sample logging welcome message is done using <paramref name="type"/>
        /// </summary>
        /// <param name="loggerConfiguration"></param>
        /// <param name="type"></param>
        public void RegisterLogging(string loggerConfiguration, Type type)
        {
            try
            {
                _repository = LogManager.CreateRepository(NomadConstants.NOMAD_LOGGER_REPOSITORY);
            }
            catch (LogException)
            {
                // the repository is already defined
                // this situation should not happen in real life situation
                // but can occur in syntetic testing
                _logger = LogManager.GetLogger(NomadConstants.NOMAD_LOGGER_REPOSITORY, type);
                return;
            }

            try
            {
                var file = new FileInfo(loggerConfiguration);
                XmlConfigurator.Configure(_repository, file);
            }
            catch (Exception)
            {
                // NOTE: eat the exception here - fallback mechanism if user not specified other ways
                BasicConfigurator.Configure(_repository);
            }

            _logger = LogManager.GetLogger(NomadConstants.NOMAD_LOGGER_REPOSITORY, type);
            _logger.Info("The modules logger is enabled at levels:");

            _logger.Info(string.Format("Debug: {0}", _logger.IsDebugEnabled));
            _logger.Info(string.Format("Info: {0}", _logger.IsInfoEnabled));
            _logger.Info(string.Format("Warn: {0}", _logger.IsWarnEnabled));
            _logger.Info(string.Format("Error: {0}", _logger.IsErrorEnabled));
            _logger.Info(string.Format("Fatal: {0}", _logger.IsFatalEnabled));
        }
        private void ConfigureRepositoryWithLayoutWithMessageProperties(PatternLayout layout)
        {
            LogManager.Shutdown();

            _Rep = LogManager.CreateRepository(Guid.NewGuid().ToString());
            _Appender = new RabbitMQAppender { Layout = layout };
            _Appender.ExchangeProperties.Name = "log4Net.RabbitMQ.Tests";
            _Appender.ExchangeProperties.ExchangeType = "fanout";
            _Appender.ExchangeProperties.Durable = true;

            _Appender.MessageProperties.AppId = Guid.NewGuid().ToString();
            _Appender.MessageProperties.ContentType = new PatternLayout("text/plain");
            _Appender.MessageProperties.Persistent = true;
            _Appender.MessageProperties.Priority = new PatternLayout("%property{priority}");
            _Appender.MessageProperties.Topic = new PatternLayout("%property{topic}");

            // An app could do something like this to customize the message priority and routing key on a message by message 
            // basis.

            ThreadContext.Properties["priority"] = "0";
            ThreadContext.Properties["topic"] = "log4net.RabbitMQ.Tests";

            _Appender.HostName = this.hostName;

            _Appender.ActivateOptions();

            BasicConfigurator.Configure(_Rep, _Appender);
            _Log = LogManager.GetLogger(_Rep.Name, GetType());

            BasicConfigurator.Configure(new ConsoleAppender { Layout = new SimpleLayout() });
        }
예제 #5
0
 public LogManager(ServerCore parent, FileInfo configFile)
 {
     this._logs = new Dictionary<String, Log>();
     this.Parent = parent;
     XmlConfigurator.ConfigureAndWatch(configFile);
     this._repository = log4net.LogManager.GetRepository();
 }
예제 #6
0
		/// <summary>
		/// Create a new <see cref="Logger" /> instance
		/// </summary>
		/// <param name="repository">The <see cref="ILoggerRepository" /> that will own the <see cref="Logger" />.</param>
		/// <param name="name">The name of the <see cref="Logger" />.</param>
		/// <returns>The <see cref="Logger" /> instance for the specified name.</returns>
		/// <remarks>
		/// <para>
		/// Create a new <see cref="Logger" /> instance with the 
		/// specified name.
		/// </para>
		/// <para>
		/// Called by the <see cref="Hierarchy"/> to create
		/// new named <see cref="Logger"/> instances.
		/// </para>
		/// <para>
		/// If the <paramref name="name"/> is <c>null</c> then the root logger
		/// must be returned.
		/// </para>
		/// </remarks>
		public Logger CreateLogger(ILoggerRepository repository, string name) 
		{
			if (name == null)
			{
				return new RootLogger(repository.LevelMap.LookupWithDefault(Level.Debug));
			}
			return new LoggerImpl(name);
		}
예제 #7
0
		private void ReloadLevels(ILoggerRepository repository)
		{
			LevelMap levelMap = repository.LevelMap;

			m_levelDebug = levelMap.LookupWithDefault(Level.Debug);
			m_levelInfo = levelMap.LookupWithDefault(Level.Info);
			m_levelWarn = levelMap.LookupWithDefault(Level.Warn);
			m_levelError = levelMap.LookupWithDefault(Level.Error);
			m_levelFatal = levelMap.LookupWithDefault(Level.Fatal);
		}
		private void ConfigureRepositoryWithLayout(PatternLayout layout)
		{
			LogManager.Shutdown();

			_Rep = LogManager.CreateRepository(Guid.NewGuid().ToString());
			_Appender = new RabbitMQAppender {Layout = layout};
			_Appender.ActivateOptions();

			BasicConfigurator.Configure(_Rep, _Appender);
			_Log = LogManager.GetLogger(_Rep.Name, GetType());

			BasicConfigurator.Configure(new ConsoleAppender { Layout = new SimpleLayout() });
		}
예제 #9
0
        public OnionGenerator()
        {
            string name = System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.ToString();
            Guid guid = Guid.NewGuid();
            OnionRepository = LogManager.CreateRepository(name + guid.ToString());
            OnionLog = LogManager.GetLogger(OnionRepository.Name, name);
            BasicConfigurator.Configure(OnionRepository, OnionAppender);

            worker.DoWork += GenerateOnionsLoop;
            worker.RunWorkerCompleted += Stopped;

            GenerateMax = MatchMax = long.MaxValue;
        }
        public void TestFixtureSetUp()
        {
            debugAppender = new DebugAppender();
            debugAppender.ActivateOptions();

            asyncForwardingAppender = new ParallelForwardingAppender();
            asyncForwardingAppender.AddAppender(debugAppender);
            asyncForwardingAppender.ActivateOptions();

            repository = LogManager.CreateRepository(Guid.NewGuid().ToString());
            BasicConfigurator.Configure(repository, asyncForwardingAppender);

            log = LogManager.GetLogger(repository.Name, "TestLogger");
        }
		/// <summary>
		/// Configures the SecurityContextProvider
		/// </summary>
		/// <param name="sourceAssembly">The assembly that this attribute was defined on.</param>
		/// <param name="targetRepository">The repository to configure.</param>
		/// <remarks>
		/// <para>
		/// Creates a provider instance from the <see cref="ProviderType"/> specified.
		/// Sets this as the default security context provider <see cref="SecurityContextProvider.DefaultProvider"/>.
		/// </para>
		/// </remarks>
		override public void Configure(Assembly sourceAssembly, ILoggerRepository targetRepository) {
			if (m_providerType == null) {
				LogLog.Error(declaringType, "Attribute specified on assembly [" + sourceAssembly.FullName + "] with null ProviderType.");
			} else {
				LogLog.Debug(declaringType, "Creating provider of type [" + m_providerType.FullName + "]");

				SecurityContextProvider provider = Activator.CreateInstance(m_providerType) as SecurityContextProvider;

				if (provider == null) {
					LogLog.Error(declaringType, "Failed to create SecurityContextProvider instance of type [" + m_providerType.Name + "].");
				} else {
					SecurityContextProvider.DefaultProvider = provider;
				}
			}
		}
		/// <summary>
		/// Attaches this plugin to a <see cref="ILoggerRepository"/>.
		/// </summary>
		/// <param name="repository">The <see cref="ILoggerRepository"/> that this plugin should be attached to.</param>
		/// <remarks>
		/// <para>
		/// A plugin may only be attached to a single repository.
		/// </para>
		/// <para>
		/// This method is called when the plugin is attached to the repository.
		/// </para>
		/// </remarks>
		override public void Attach(ILoggerRepository repository)
		{
			base.Attach(repository);

			// Create the sink and marshal it
			m_sink = new RemoteLoggingSinkImpl(repository); 

			try
			{
				RemotingServices.Marshal(m_sink, m_sinkUri, typeof(log4net.Appender.RemotingAppender.IRemoteLoggingSink));		
			}
			catch(Exception ex)
			{
				LogLog.Error("RemoteLoggingServerPlugin: Failed to Marshal remoting sink", ex);
			}
		}
예제 #13
0
            private static void ReloadLevels(ILoggerRepository repository)
            {
                LevelMap levelMap = repository.LevelMap;

                _levelTrace = levelMap.LookupWithDefault(Level.Trace);
                _levelDebug = levelMap.LookupWithDefault(Level.Debug);
                _levelInfo = levelMap.LookupWithDefault(Level.Info);
                _levelWarn = levelMap.LookupWithDefault(Level.Warn);
                _levelError = levelMap.LookupWithDefault(Level.Error);
                _levelFatal = levelMap.LookupWithDefault(Level.Fatal);
//                LevelLogError = levelMap.LookupWithDefault(LevelLogError);
//                LevelLogInfo = levelMap.LookupWithDefault(LevelLogInfo);

                //// Register custom logging levels with the default LoggerRepository
//                LogManager.GetRepository().LevelMap.Add(LevelLogInfo);
//                LogManager.GetRepository().LevelMap.Add(LevelLogError);

            }
예제 #14
0
        public LogWriter(ILoggerRepository loggerRepository, object source)
        {
            if (loggerRepository == null)
            {
                throw new ArgumentNullException("loggerRepository");
            }

            this.loggerRepository = loggerRepository;

            if (source != null)
            {
                sourceType = source.GetType();
            }
            else
            {
                sourceType = MethodBase.GetCurrentMethod().DeclaringType;
            }
        }
        public void SetUp()
        {
            fileGuid = Guid.NewGuid();
            if (File.Exists(GetFilePath()))
            {
                File.Delete(GetFilePath());
            }

            appender = new AsyncRollingFileAppender();
            appender.Threshold = ErrorLevel;
            appender.File = GetFilePath();
            appender.Layout = new PatternLayout("%d|%-5level|%logger| %message %exception%n");
            appender.StaticLogFileName = true;
            appender.AppendToFile = true;
            appender.ActivateOptions();

            rep = LogManager.CreateRepository(Guid.NewGuid().ToString());
            BasicConfigurator.Configure(rep, appender);
        }
		public void SetUp()
		{
			_fileFolderPath = TestHelper.MapPathForTest("~/LogTesting/");

			_fileGuid = Guid.NewGuid();
			if (File.Exists(GetFilePath()))
			{
				File.Delete(GetFilePath());
			}

			_appender = new AsynchronousRollingFileAppender();
			_appender.Threshold = _errorLevel;
			_appender.File = GetFilePath();
			_appender.Layout = new PatternLayout("%d|%-5level|%logger| %message %exception%n");
			_appender.StaticLogFileName = true;
			_appender.AppendToFile = true;
			_appender.ActivateOptions();

			_rep = LogManager.CreateRepository(Guid.NewGuid().ToString());
			BasicConfigurator.Configure(_rep, _appender);
		}
예제 #17
0
        public LoggingEvent GetReconstructedLoggingEvent(ILoggerRepository renderingRepo)
        {
            LoggingEvent ret = new LoggingEvent(null, renderingRepo, null, _LoggingEvent.Level, _MessageObject, _LoggedException);

            BindingFlags eFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
            FieldInfo pi;

            LoggingEventData data = _LoggingEvent.GetLoggingEventData(FixFlags.None);
            //reset message so it gets rendered again
            data.Message = null;

            pi = ret.GetType().GetField("m_data", eFlags);
            if (pi != null)
            {
                pi.SetValue(ret, data);
            }

            //reflectivly set the rest of the properties.
            ret.Fix = FixFlags.Exception | FixFlags.Message;
            return ret;
        }
		/// <summary>
		/// Automatically configures the <see cref="ILoggerRepository"/> using settings
		/// stored in the application's configuration file.
		/// </summary>
		/// <remarks>
		/// 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
		/// <c>log4net</c> that contains the configuration data.
		/// </remarks>
		/// <param name="repository">The repository to configure.</param>
		static public void Configure(ILoggerRepository repository) 
		{
			LogLog.Debug("DOMConfigurator: configuring repository [" + repository.Name + "] using .config file section");

			try
			{
				LogLog.Debug("DOMConfigurator: Application config file is [" + SystemInfo.ConfigurationFileLocation + "]");
			}
			catch
			{
				// ignore error
				LogLog.Debug("DOMConfigurator: Application config file location unknown");
			}

#if NETCF
			// No config file reading stuff. Just go straight for the file
			Configure(repository, new FileInfo(SystemInfo.ConfigurationFileLocation));
#else
			try
			{
				ConfigureFromXML(repository, (XmlElement) System.Configuration.ConfigurationSettings.GetConfig("log4net"));
			}
			catch(System.Configuration.ConfigurationException confEx)
			{
				if (confEx.BareMessage.IndexOf("Unrecognized element") >= 0)
				{
					// Looks like the XML file is not valid
					LogLog.Error("DOMConfigurator: 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 = "<section name=\"log4net\" type=\"log4net.Config.Log4NetConfigurationSectionHandler," + Assembly.GetExecutingAssembly().FullName + "\" />";
					LogLog.Error("DOMConfigurator: Failed to parse config file. Is the <configSections> specified as: " + configSectionStr, confEx);
				}
			}
#endif
		}
예제 #19
0
		/// <summary>
		/// Configures the <see cref="ILoggerRepository"/> using the specified XML 
		/// element.
		/// </summary>
		/// <remarks>
		/// Loads the log4net configuration from the XML element
		/// supplied as <paramref name="element"/>.
		/// </remarks>
		/// <param name="repository">The repository to configure.</param>
		/// <param name="element">The element to parse.</param>
		static public void Configure(ILoggerRepository repository, XmlElement element) 
		{
			LogLog.Debug("XmlConfigurator: configuring repository [" + repository.Name + "] using XML element");

			ConfigureFromXml(repository, element);
		}
예제 #20
0
        /// <summary>
        /// 日志收集(报错)
        /// </summary>
        /// <param name="QueueKey">队列名称</param>
        /// <param name="Ex">错误信息</param>
        /// <param name="Url">路径</param>
        /// <param name="Token">Token</param>
        /// <param name="Logger">MQ类接口</param>
        public void LogCollectPush(string QueueKey, Exception Ex, string Url, string Token, ILoggerRepository Logger)
        {
            JsonSerializerSettings settings = new JsonSerializerSettings()
            {
                ReferenceLoopHandling = ReferenceLoopHandling.Ignore
            };
            var LogErrorDetails = new LogErrorDetails()
            {
                CreateTime = DateTime.Now,
                Url        = Url,
                Messsage   = JsonConvert.SerializeObject(Ex, settings),
                Token      = Token,
            };

            LogManager.GetLogger(Logger.Name, Url).Debug(JsonConvert.SerializeObject(LogErrorDetails));
        }
		/// <summary>
		/// Attempt to load configuration from a URI
		/// </summary>
		/// <param name="sourceAssembly">The assembly that this attribute was defined on.</param>
		/// <param name="targetRepository">The repository to configure.</param>
		private void ConfigureFromUri(Assembly sourceAssembly, ILoggerRepository targetRepository)
		{
			// Work out the full path to the config file
			Uri fullPath2ConfigFile = null;
			
			// Select the config file
			if (m_configFile == null || m_configFile.Length == 0)
			{
				if (m_configFileExtension == null || 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 (m_configFileExtension[0] != '.')
					{
						m_configFileExtension = "." + 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 += 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 ["+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), m_configFile);
				}
				else
				{
					fullPath2ConfigFile = new Uri(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
					ConfigureFromFile(targetRepository, new FileInfo(fullPath2ConfigFile.LocalPath));
				}
				else
				{
					if (m_configureAndWatch)
					{
						LogLog.Warn(declaringType, "XmlConfiguratorAttribute: Unable to watch config file loaded from a URI");
					}
					XmlConfigurator.Configure(targetRepository, fullPath2ConfigFile);
				}
			}
		}
예제 #22
0
        /// <summary>
        /// 记录文本
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public static ILog GetLogger(string name, bool isOnlyMessage = false)
        {
            if (string.IsNullOrEmpty(name))
            {
                return(LogManager.GetLogger("Defalut"));
            }

            name = System.Text.RegularExpressions.Regex.Replace(name, @"[^\w]", "\\");
            name = name.Trim('\\').Trim('/');
            string name2 = name.ToUpper()
                           .Replace("\"", "_")
                           .Replace("\r\n", "\\r\\n")
                           .Replace("\n", "\\n")
                           .Replace("\r", "\\r")
                           .Replace("\t", "\\t")
                           .Replace("\\", "_")
                           .Replace("/", "_");
            string            repositoryName = "R_LOG4HELPER_" + name2 + (isOnlyMessage ? "_ISOM_" : "");
            string            newname        = "LOG_" + repositoryName;
            ILoggerRepository repository     = null;

            try
            {
                repository = LogManager.GetRepository(repositoryName);
            }
            catch (Exception) { }


            if (repository != null)
            {
                ILog ilog = LogManager.GetLogger(repositoryName, newname);
                if (ilog != null)
                {
                    return(ilog);
                }
            }
            try
            {
                repository = LogManager.CreateRepository(repositoryName);
            }
            catch (Exception)
            {
                return(null);
            }

            repository.Threshold = Level.All;

            RollingFileAppender rollingFileAppender = new RollingFileAppender();

            rollingFileAppender.AppendToFile   = true;
            rollingFileAppender.DatePattern    = (isOnlyMessage ? "'NoTime-'" : "") + "yyyy-MM-dd'.log'";
            rollingFileAppender.File           = "log\\" + name + "\\";
            rollingFileAppender.ImmediateFlush = true;
            rollingFileAppender.Name           = newname;
            //rollingFileAppender.LockingModel = new FileAppender.InterProcessLock();
            rollingFileAppender.RollingStyle      = RollingFileAppender.RollingMode.Date;
            rollingFileAppender.StaticLogFileName = false;
            if (!isOnlyMessage)
            {
                rollingFileAppender.Layout = new PatternLayout("%date [%thread] %-5level - %message%newline");
            }
            else
            {
                rollingFileAppender.Layout = new PatternLayout("%message%newline");
            }
            rollingFileAppender.ActivateOptions();
            BasicConfigurator.Configure(repository, rollingFileAppender);

            return(log4net.LogManager.GetLogger(repository.Name, newname));
        }
예제 #23
0
 public VoteRepository(ApplicationDbContext applicationDbContext, ILoggerRepository loggerRepository)
 {
     _applicationDbContext = applicationDbContext;
     _loggerRepository     = loggerRepository;
 }
예제 #24
0
		/// <summary>
		/// Configures the specified repository using a <c>log4net</c> element.
		/// </summary>
		/// <param name="repository">The hierarchy to configure.</param>
		/// <param name="element">The element to parse.</param>
		/// <remarks>
		/// <para>
		/// Loads the log4net configuration from the XML element
		/// supplied as <paramref name="element"/>.
		/// </para>
		/// <para>
		/// This method is ultimately called by one of the Configure methods 
		/// to load the configuration from an <see cref="XmlElement"/>.
		/// </para>
		/// </remarks>
		static private void ConfigureFromXml(ILoggerRepository repository, XmlElement element) 
		{
			if (element == null)
			{
				LogLog.Error("XmlConfigurator: ConfigureFromXml called with null 'element' parameter");
			}
			else if (repository == null)
			{
				LogLog.Error("XmlConfigurator: ConfigureFromXml called with null 'repository' parameter");
			}
			else
			{
				LogLog.Debug("XmlConfigurator: Configuring Repository [" + repository.Name + "]");

				IXmlRepositoryConfigurator configurableRepository = repository as IXmlRepositoryConfigurator;
				if (configurableRepository == null)
				{
					LogLog.Warn("XmlConfigurator: 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();
					XmlElement newElement = (XmlElement)newDoc.AppendChild(newDoc.ImportNode(element, true));

					// Pass the configurator the config element
					configurableRepository.Configure(newElement);
				}			
			}
		}
예제 #25
0
 static LoggerFactory()
 {
     Repository = LogManager.GetRepository(typeof(LoggerFactory).Assembly);
 }
예제 #26
0
        static private 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
                        {
                            WebResponse response = configRequest.GetResponse();
                            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);
                        }
                    }
                }
            }
        }
예제 #27
0
        static private 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();
                try
                {
#if (NETCF)
                    // Create a text reader for the file stream
                    XmlTextReader xmlReader = new XmlTextReader(configStream);
#elif NET_2_0
                    // 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 !NET_4_0
                    settings.ProhibitDtd = false;
#else
                    settings.DtdProcessing = DtdProcessing.Parse;
#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 <log4net> element. Configuration Aborted.");
                    }
                    else if (configNodeList.Count > 1)
                    {
                        LogLog.Error(declaringType, "XML configuration contains [" + configNodeList.Count + "] <log4net> elements. Only one is allowed. Configuration Aborted.");
                    }
                    else
                    {
                        InternalConfigureFromXml(repository, configNodeList[0] as XmlElement);
                    }
                }
            }
        }
예제 #28
0
 /// <summary>
 /// Attaches this plugin to a <see cref="ILoggerRepository"/>.
 /// </summary>
 /// <param name="repository">The <see cref="ILoggerRepository"/> that this plugin should be attached to.</param>
 /// <remarks>
 /// <para>
 /// A plugin may only be attached to a single repository.
 /// </para>
 /// <para>
 /// This method is called when the plugin is attached to the repository.
 /// </para>
 /// </remarks>
 public virtual void Attach(ILoggerRepository repository)
 {
     m_repository = repository;
 }
예제 #29
0
 protected static void WriteDictionary(TextWriter writer, ILoggerRepository repository, IDictionary value)
 {
     WriteDictionary(writer, repository, value.GetEnumerator());
 }
예제 #30
0
        /// <summary>
        /// 设置配置
        /// </summary>
        public void SetConfig()
        {
            //不是第一次设置
            if (rep != null)
            {
                rep.ResetConfiguration();
            }
            else//初次创建
            {
                //创建Repository
                try
                {
                    rep = LogManager.GetRepository(logName);
                    //log = LogManager.GetLogger(rep.Name, logName);
                }
                catch
                {
                    rep = LogManager.CreateRepository(logName);
                    log4net.Config.BasicConfigurator.Configure(rep, fileApp);
                    log = LogManager.GetLogger(logName, logName);
                }
            }

            //重设文件输出
            RollingFileAppender fileAppender = new RollingFileAppender();

            fileAppender.Layout = new PatternLayout(strLayoutPattern);

            fileAppender.RollingStyle = (RollingFileAppender.RollingMode)rollingMode;
            if (rollingMode == RollingType.Date)
            {
                fileAppender.StaticLogFileName = false;
                fileAppender.DatePattern       = @"\\\\yyyy-MM-dd\\\\yyyyMMdd'.log'";
                fileAppender.File = filePath;

                if (fileAppender.File != null && fileAppender.File.EndsWith(".log"))
                {
                    fileAppender.File = fileAppender.File.Remove(fileAppender.File.IndexOf(".log"));
                }
            }
            else
            {
                fileAppender.File = filePath;
            }
            fileAppender.LockingModel = new RollingFileAppender.MinimalLock();
            fileAppender.AppendToFile = true;
            fileAppender.Encoding     = Encoding.GetEncoding("GB2312");
            //fileAppender.CountDirection = 1;
            fileAppender.MaxFileSize        = maxFileSize;
            fileAppender.MaxSizeRollBackups = this.MaxSizeRollBackups;

            fileAppender.ActivateOptions();
            fileApp = fileAppender;

            if ((logType & LogType.File) == LogType.File)
            {
                //创建Log文件输出方式
                log4net.Config.BasicConfigurator.Configure(rep, fileApp);
            }
            //控制台输出
            if ((logType & LogType.Console) == LogType.Console)
            {
                PatternLayout   layout   = new PatternLayout(strLayoutPattern);
                ConsoleAppender appender = new ConsoleAppender();
                appender.Layout = layout;
                log4net.Config.BasicConfigurator.Configure(rep, appender);
            }
            //数据库输出
            if ((logType & LogType.DataBase) == LogType.DataBase)
            {
                AdoNetAppender appender = new AdoNetAppender();
                appender.ConnectionString = DBConnectionString;
                appender.CommandText      = DBInsertSql;
                if (DBParameter != null)
                {
                    for (int i = 0; i < DBParameter.Length; i++)
                    {
                        appender.AddParameter(DBParameter[i]);
                    }
                }
                log4net.Config.BasicConfigurator.Configure(rep, appender);
            }
            //Debug输出
            if ((logType & LogType.Debug) == LogType.Debug)
            {
                DebugAppender appender = new DebugAppender();
                appender.Layout = new PatternLayout(strLayoutPattern);
                log4net.Config.BasicConfigurator.Configure(rep, appender);
            }

            log = LogManager.GetLogger(rep.Name, logName);
        }
예제 #31
0
 /// <summary>
 /// 日志收集(返回结果记录)
 /// </summary>
 /// <param name="QueueKey">队列名称</param>
 /// <param name="sUrl">Url</param>
 /// <param name="sHeaders">头</param>
 /// <param name="sActionArguments">参数</param>
 /// <param name="sResult">结果</param>
 /// <param name="Logger">MQ类接口</param>
 public void LogCollectPush(string QueueKey, string sUrl, string sHeaders, string sActionArguments, string sResult, ILoggerRepository Logger)
 {
     LogManager.GetLogger(Logger.Name, sUrl).Info(JsonConvert.SerializeObject(new
     {
         CreateTime      = DateTime.Now,
         Url             = sUrl,
         Headers         = sHeaders,
         ActionArguments = sActionArguments,
         Result          = sResult,
     }));
 }
예제 #32
0
 /// <summary>
 /// 日志收集(计时)
 /// </summary>
 /// <param name="QueueKey">队列名称</param>
 /// <param name="sUrl">Url</param>
 /// <param name="sIP">IP</param>
 /// <param name="sMessage">消息</param>
 /// <param name="Logger">MQ类接口</param>
 public void LogCollectPush(string QueueKey, string sUrl, string sIP, string sMessage, ILoggerRepository Logger)
 {
     LogManager.GetLogger(Logger.Name, sUrl).Info(JsonConvert.SerializeObject(new
     {
         CreateTime = DateTime.Now,
         Url        = sUrl,
         IP         = sIP,
         Message    = sMessage
     }));
 }
예제 #33
0
		/// <summary>
		/// Configures the <see cref="ILoggerRepository"/> using the specified configuration 
		/// URI.
		/// </summary>
		/// <param name="repository">The repository to configure.</param>
		/// <param name="configUri">A URI to load the XML configuration from.</param>
		/// <remarks>
		/// <para>
		/// The configuration data must be valid XML. It must contain
		/// at least one element called <c>log4net</c> that holds
		/// the configuration data.
		/// </para>
		/// <para>
		/// The <see cref="System.Net.WebRequest"/> must support the URI scheme specified.
		/// </para>
		/// </remarks>
		static public void Configure(ILoggerRepository repository, Uri configUri)
		{
			LogLog.Debug("XmlConfigurator: configuring repository [" + repository.Name + "] using URI ["+configUri+"]");

			if (configUri == null)
			{
				LogLog.Error("XmlConfigurator: Configure called with null 'configUri' parameter");
			}
			else
			{
				if (configUri.IsFile)
				{
					// If URI is local file then call Configure with FileInfo
					Configure(repository, new FileInfo(configUri.LocalPath));
				}
				else
				{
					// NETCF dose not support WebClient
					WebRequest configRequest = null;

					try
					{
						configRequest = WebRequest.Create(configUri);
					}
					catch(Exception ex)
					{
						LogLog.Error("XmlConfigurator: Failed to create WebRequest for URI ["+configUri+"]", ex);
					}

					if (configRequest != null)
					{
#if !NETCF
						// authentication may be required, set client to use default credentials
						try
						{
							configRequest.Credentials = CredentialCache.DefaultCredentials;
						}
						catch
						{
							// ignore security exception
						}
#endif
						try
						{
							WebResponse response = configRequest.GetResponse();
							if (response != null)
							{
								try
								{
									// Open stream on config URI
									using(Stream configStream = response.GetResponseStream())
									{
										Configure(repository, configStream);
									}
								}
								finally
								{
									response.Close();
								}
							}
						}
						catch(Exception ex)
						{
							LogLog.Error("XmlConfigurator: Failed to request config from URI ["+configUri+"]", ex);
						}
					}
				}
			}
		}
 public static IEnumerable <LogLog> ListConfigurationMessages(ILoggerRepository repositoryAssembly)
 {
     return(repositoryAssembly.ConfigurationMessages.Cast <LogLog>());
 }
예제 #35
0
		/// <summary>
		/// Configures the <see cref="ILoggerRepository"/> using the file specified, 
		/// monitors the file for changes and reloads the configuration if a change 
		/// is detected.
		/// </summary>
		/// <param name="repository">The repository to configure.</param>
		/// <param name="configFile">The XML file to load the configuration from.</param>
		/// <remarks>
		/// <para>
		/// The configuration file must be valid XML. It must contain
		/// at least one element called <c>log4net</c> that holds
		/// the configuration data.
		/// </para>
		/// <para>
		/// The configuration file will be monitored using a <see cref="FileSystemWatcher"/>
		/// and depends on the behavior of that class.
		/// </para>
		/// <para>
		/// For more information on how to configure log4net using
		/// a separate configuration file, see <see cref="Configure(FileInfo)"/>.
		/// </para>
		/// </remarks>
		/// <seealso cref="Configure(FileInfo)"/>
		static public void ConfigureAndWatch(ILoggerRepository repository, FileInfo configFile)
		{
			LogLog.Debug("XmlConfigurator: configuring repository [" + repository.Name + "] using file [" + configFile + "] watching for file updates");

			if (configFile == null)
			{
				LogLog.Error("XmlConfigurator: ConfigureAndWatch called with null 'configFile' parameter");
			}
			else
			{
				// Configure log4net now
				Configure(repository, configFile);

				try
				{
					// Create a watch handler that will reload the
					// configuration whenever the config file is modified.
					ConfigureAndWatchHandler.StartWatching(repository, configFile);
				}
				catch(Exception ex)
				{
					LogLog.Error("XmlConfigurator: Failed to initialize configuration file watcher for file ["+configFile.FullName+"]", ex);
				}
			}
		}
        /// <summary>
        /// Attempt to load configuration from the local file system
        /// </summary>
        /// <param name="sourceAssembly">The assembly that this attribute was defined on.</param>
        /// <param name="targetRepository">The repository to configure.</param>
        private void ConfigureFromFile(Assembly sourceAssembly, ILoggerRepository targetRepository)
        {
            // Work out the full path to the config file
            string fullPath2ConfigFile = null;

            // Select the config file
            if (m_configFile == null || m_configFile.Length == 0)
            {
                if (m_configFileExtension == null || m_configFileExtension.Length == 0)
                {
                    // Use the default .config file for the AppDomain
                    try
                    {
                        fullPath2ConfigFile = SystemInfo.ConfigurationFileLocation;
                    }
                    catch (Exception ex)
                    {
                        LogLog.Error("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 (m_configFileExtension[0] != '.')
                    {
                        m_configFileExtension = "." + m_configFileExtension;
                    }

                    string applicationBaseDirectory = null;
                    try
                    {
                        applicationBaseDirectory = SystemInfo.ApplicationBaseDirectory;
                    }
                    catch (Exception ex)
                    {
                        LogLog.Error("XmlConfiguratorAttribute: 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) + m_configFileExtension);
                    }
                }
            }
            else
            {
                string applicationBaseDirectory = null;
                try
                {
                    applicationBaseDirectory = SystemInfo.ApplicationBaseDirectory;
                }
                catch (Exception ex)
                {
                    LogLog.Warn("XmlConfiguratorAttribute: Exception getting ApplicationBaseDirectory. ConfigFile property path [" + m_configFile + "] will be treated as an absolute path.", ex);
                }

                if (applicationBaseDirectory != null)
                {
                    // Just the base dir + the config file
                    fullPath2ConfigFile = Path.Combine(applicationBaseDirectory, m_configFile);
                }
                else
                {
                    fullPath2ConfigFile = m_configFile;
                }
            }

            if (fullPath2ConfigFile != null)
            {
                ConfigureFromFile(targetRepository, new FileInfo(fullPath2ConfigFile));
            }
        }
예제 #37
0
 static public void ConfigureAndWatch(ILoggerRepository repository, FileInfo configFile)
 {
     XmlConfigurator.ConfigureAndWatch(repository, configFile);
 }
예제 #38
0
		/// <summary>
		/// Gets a list of <see cref="ILoggerRepository"/> objects
		/// </summary>
		/// <returns>an array of all known <see cref="ILoggerRepository"/> objects</returns>
		/// <remarks>
		/// <para>
		/// Gets an array of all of the repositories created by this selector.
		/// </para>
		/// </remarks>
		public ILoggerRepository[] GetAllRepositories()
		{
			lock(this)
			{
				ICollection reps = m_name2repositoryMap.Values;
				ILoggerRepository[] all = new ILoggerRepository[reps.Count];
				reps.CopyTo(all, 0);
				return all;
			}
		}
예제 #39
0
        static void ConfigureLogging()
        {
            ILoggerRepository logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly());

            XmlConfigurator.Configure(logRepository, new FileInfo("log4net.config"));
        }
예제 #40
0
        private static void SendMailError(AdvException currError)
        {
            if (HttpContext.Current != null && HttpContext.Current.Request.Url.AbsoluteUri.Contains("localhost"))
            {
                return;
            }

            lock (Sync)
            {
                var data = LogTempDataService.GetLogTempData();
                if (data.MailErrorLastSend.DayOfYear < DateTime.Now.DayOfYear)
                {
                    data.MailErrorCurrentCount = 0;
                }
                if (data.MailErrorCurrentCount < MaxMailsSendPerDay)
                {
                    if (File.Exists(EmailNotificationTemplate))
                    {
                        var template = new StringBuilder(File.ReadAllText(EmailNotificationTemplate));

                        template.Replace("CommonInfo_Header", Resource.Admin_MasterPageAdmin_BugTracker_CommonInfo);
                        var outHtml = new StringBuilder();
                        outHtml.Append("<div class=\'tab-content\'>");
                        outHtml.Append("<table>");
                        outHtml.Append("<tr><td colspan='2'><hr/></td></td></tr>");
                        outHtml.AppendFormat("<tr><td><b>{0}</b></td><td>{1}</td></tr>", "Message", currError.ExceptionData.ManualMessage.IsNullOrEmpty() ? "none" : currError.ExceptionData.ManualMessage);
                        outHtml.Append("<tr><td colspan='2'><hr/></td></td></tr>");
                        outHtml.AppendFormat("<tr><td><b>{0}</b></td><td>{1}</td></tr>", "ExceptionMessage", currError.ExceptionData.ExceptionMessage);
                        outHtml.Append("<tr><td colspan='2'><hr/></td></td></tr>");
                        outHtml.AppendFormat("<tr><td><b>{0}</b></td><td>{1}</td></tr>", "ExceptionStackTrace", currError.ExceptionData.ExceptionStackTrace.IsNullOrEmpty() ? "none" : currError.ExceptionData.ExceptionStackTrace);
                        outHtml.Append("<tr><td colspan='2'><hr/></td></td></tr>");
                        outHtml.AppendFormat("<tr><td><b>{0}</b></td><td>{1}</td></tr>", "InnerExceptionMessage", currError.ExceptionData.InnerExceptionMessage.IsNullOrEmpty() ? "none" : currError.ExceptionData.InnerExceptionMessage);
                        outHtml.Append("<tr><td colspan='2'><hr/></td></td></tr>");
                        outHtml.AppendFormat("<tr><td><b>{0}</b></td><td>{1}</td></tr>", "InnerExceptionStackTrace", currError.ExceptionData.InnerExceptionStackTrace.IsNullOrEmpty() ? "none" : currError.ExceptionData.InnerExceptionStackTrace);
                        outHtml.Append("<tr><td colspan='2'><hr/></td></td></tr>");
                        foreach (var key in currError.ExceptionData.Parameters.Keys)
                        {
                            outHtml.AppendFormat("<tr><td><b>{0}</b></td><td>{1}</td></tr>", key, currError.ExceptionData.Parameters[key]);
                        }
                        outHtml.Append("<tr><td colspan='2'><hr/></td></td></tr>");

                        outHtml.Append("</table>");
                        outHtml.Append("</div>");
                        template.Replace("CommonInfo_Body", outHtml.ToString());


                        template.Replace("Request_Header", Resource.Admin_MasterPageAdmin_BugTracker_Request);
                        outHtml = new StringBuilder();
                        outHtml.Append("<div class=\'tab-content\'>");
                        if (currError.RequestData != null)
                        {
                            outHtml.Append("<table>");

                            foreach (var key in currError.RequestData.ColectionData.Keys)
                            {
                                outHtml.AppendFormat("<tr><td><b>{0}</b></td><td>{1}</td></tr>", key, currError.RequestData.ColectionData[key]);
                            }
                            outHtml.Append("</table>");
                        }
                        outHtml.Append("</div>");
                        template.Replace("Request_Body", outHtml.ToString());


                        template.Replace("Browser_Header", Resource.Admin_MasterPageAdmin_BugTracker_Browser);
                        outHtml = new StringBuilder();
                        outHtml.Append("<div class=\'tab-content\'>");
                        if (currError.BrowserData != null)
                        {
                            outHtml.Append("<table>");
                            foreach (var key in currError.BrowserData.ColectionData.Keys)
                            {
                                outHtml.AppendFormat("<tr><td><b>{0}</b></td><td>{1}</td></tr>", key, currError.BrowserData.ColectionData[key]);
                            }
                            outHtml.Append("</table>");
                        }
                        outHtml.Append("</div>");
                        template.Replace("Browser_Body", outHtml.ToString());


                        template.Replace("Session_Header", Resource.Admin_MasterPageAdmin_BugTracker_Session);
                        outHtml = new StringBuilder();
                        outHtml.Append("<div class=\'tab-content\'>");
                        if (currError.SessionData != null)
                        {
                            outHtml.Append("<table>");
                            foreach (var key in currError.SessionData.ColectionData.Keys)
                            {
                                outHtml.AppendFormat("<tr><td><b>{0}</b></td><td>{1}</td></tr>", key, currError.SessionData.ColectionData[key]);
                            }
                            outHtml.Append("</table>");
                        }
                        outHtml.Append("</div>");
                        template.Replace("Session_Body", outHtml.ToString());

                        ILoggerRepository rep = LogManager.GetRepository();
                        foreach (IAppender appender in rep.GetAppenders())
                        {
                            if (appender is SmtpAppender)
                            {
                                // Loop exception here. SettingsMain.SiteUrl - Лезет в базу.
                                // ((SmtpAppender)appender).Subject = SettingsMain.SiteUrl + " " + SettingsGeneral.SiteVersion;

                                ((SmtpAppender)appender).Subject = SettingsGeneral.AbsoluteUrl + " " + SettingsGeneral.SiteVersion;
                                var emailLog1 = LogManager.GetLogger("EmailErr");
                                emailLog1.Error(template.ToString());
                            }
                        }
                    }

                    data.MailErrorCurrentCount++;
                    data.MailErrorLastSend = DateTime.Now;
                }
                LogTempDataService.UpdateLogTempData(data);
            }
        }
예제 #41
0
        //public static void Info<T>(T model)
        //{
        //    try
        //    {
        //        ILog i = GetSQLLogger(typeof(T));
        //        if (i != null)
        //            i.Info(model);
        //    }
        //    catch { }
        //}
        //public static void Info<T>(T model, string tablename)
        //{
        //    try
        //    {
        //        ILog i = GetSQLLogger(tablename, typeof(T));
        //        if (i != null)
        //            i.Info(model);
        //    }
        //    catch { }
        //}


        /// <summary>
        /// 记录文本
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public static ILog GetLogger(string name)
        {
            if (string.IsNullOrEmpty(name))
            {
                return(LogManager.GetLogger("Defalut"));
            }

            name = System.Text.RegularExpressions.Regex.Replace(name, @"[^\w]", "\\");
            string name2 = name.ToUpper()
                           .Replace("\"", "_")
                           .Replace("\r\n", "\\r\\n")
                           .Replace("\n", "\\n")
                           .Replace("\r", "\\r")
                           .Replace("\t", "\\t")
                           .Replace("\\", "_")
                           .Replace("/", "_");
            string            repositoryName = "R_" + name2;
            string            newname        = "LOG_" + repositoryName;
            ILoggerRepository repository     = null;

            try
            {
                repository = LogManager.GetRepository(repositoryName);
            }
            catch (Exception) { }

            if (repository != null)
            {
                return(LogManager.GetLogger(repositoryName, newname));
            }

            try
            {
                repository = LogManager.CreateRepository(repositoryName);
            }
            catch (Exception)
            {
                repository = LogManager.GetRepository(repositoryName);
            }

            repository.Threshold = Level.All;

            RollingFileAppender rollingFileAppender = new RollingFileAppender();

            rollingFileAppender.AppendToFile      = true;
            rollingFileAppender.DatePattern       = "yyyy-MM-dd'.log'";
            rollingFileAppender.File              = "log\\" + name + "\\";
            rollingFileAppender.ImmediateFlush    = true;
            rollingFileAppender.Name              = newname;
            rollingFileAppender.RollingStyle      = RollingFileAppender.RollingMode.Date;
            rollingFileAppender.StaticLogFileName = false;

            var lockmodel = new FileAppender.InterProcessLock();

            lockmodel.CurrentAppender = rollingFileAppender;
            lockmodel.ActivateOptions();
            rollingFileAppender.LockingModel = lockmodel;

            PatternLayout patternLayout = new PatternLayout();

            patternLayout.ConversionPattern = "%date [%thread] %-5level - %message%newline";
            patternLayout.ActivateOptions();
            rollingFileAppender.Layout = patternLayout;

            rollingFileAppender.LockingModel.ActivateOptions();
            rollingFileAppender.ActivateOptions();
            BasicConfigurator.Configure(repository, rollingFileAppender);

            return(log4net.LogManager.GetLogger(repository.Name, newname));
        }
예제 #42
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="repository">The repository to log to.</param>
 /// <remarks>
 /// <para>
 /// Initializes a new instance of the <see cref="RemoteLoggingSinkImpl"/> for the
 /// specified <see cref="ILoggerRepository"/>.
 /// </para>
 /// </remarks>
 public RemoteLoggingSinkImpl(ILoggerRepository repository)
 {
     m_repository = repository;
 }
예제 #43
0
 static public void Configure(ILoggerRepository repository, XmlElement element)
 {
     XmlConfigurator.Configure(repository, element);
 }
예제 #44
0
 static public void Configure(ILoggerRepository repository)
 {
     XmlConfigurator.Configure(repository);
 }
예제 #45
0
        private static IdWorker idworker; //定义全局ID生成类(雪花算法)


        #region 入口Main方法

        static void Main(string[] args)
        {
            //ReadSql sql = new ReadSql("E:\\2021\\", "E:\\2021\\", "E:\\2021\\", "E:\\2021\\");
            //sql.ExecuteSql("E:\\PM_APPROVAL_1381443846583488512_sdnclob.txt", "");


            repository = LogManager.CreateRepository("NETCoreRepository");
            XmlConfigurator.Configure(repository, new FileInfo("log4net.config"));
            // BasicConfigurator.Configure(repository); //控制台输出
            log = LogManager.GetLogger(repository.Name, "Program");
            log.Info("DataExchange in runing");
            var builder = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory())
                          .AddJsonFile("system.json", optional: false, reloadOnChange: true);
            var configuration = builder.Build();

            strWatcherPath = configuration["fileWatch:file1"];
            iDirection     = int.Parse(configuration["direction"]);                //得到配置项中的数据传输方向
            int iDays    = int.Parse(configuration["idays"]);                      //get the number of days to sync data from json
            int interval = int.Parse(configuration["interval"]);                   //get the number of interval from json

            writePath   = configuration["writePath"];                              //sql 文件写入路径 跟目录
            readPath    = configuration["readPath"];                               // ftp文件读取目录
            ftpUpload   = configuration["ftpUpload"];                              //ftp上传文件夹
            ftpDownload = configuration["ftpDownload"];                            //ftp下载文件夹
            exc_error   = configuration["exc_error"];                              //执行错误sql文件存放文件夹
            his_tmp     = configuration["his_tmp"];                                //执行过的历史文件存放路径
            string out2in_insert = configuration["out2in:insert"];                 //外网到内网 插入
            string out2in_update = configuration["out2in:update"];                 //外网到内网 更新
            string in2out_insert = configuration["in2out:insert"];                 //内网到外网 插入
            string in2out_update = configuration["in2out:update"];                 //内网到外网 更新

            threshold_times  = Convert.ToInt32(configuration["threshold:times"]);  //获取阈值同步次数
            threshold_minute = Convert.ToInt32(configuration["threshold:minute"]); //获取阈值分钟数
            strSender        = configuration["mail:sender"];                       //发送者
            strReciver       = configuration["mail:reciver"];                      //接收者
            strRec_CC        = configuration["mail:rec_cc"];                       //抄送者
            strPasswd        = configuration["mail:passwd"];                       //发送者密码
            strMailHost      = configuration["mail:host"];                         //邮箱服务地址
            strMailPort      = configuration["mail:port"];                         //邮箱服务端口
            bl_mail_enable   = Convert.ToBoolean(configuration["mail:enable"]);
            strTelNo         = configuration["telNo"];                             //得到故障短信通知联系人手机号码
            idworker         = new IdWorker(1, 1);                                 //实例化获取雪花id类
            log.Info($"Get the listener file path:{strWatcherPath}");              //得到监听路径
            // for(int i=0;i<101;i++)
            // log.Info($"Get snowflake id {GetSonwflake()}");
            // new sys_oracle.ReadSql(readPath).ExecuteSql("F:\\sdnsql\\sqlInsert\\sql_insert_CON_WFJB_1191588251996131328.txt");
            sdnReadSql = new sys_oracle.ReadSql(readPath, writePath, ftpUpload, ftpDownload); //instantiation the ReadSql class.
            sdnReadSql.event_getListByQueNo   += GetInertQueue;                               //bind event executive.
            sdnReadSql.event_getNoExcList     += GetReadList;
            sdnReadSql.event_removeInsertList += RemoveInserQueue;                            //绑定移除插入队列事件
            sdnReadSql.event_removeReaadList  += RemoveReadList;                              //绑定移除读取队列事件
            sdnReadSql.event_addSyncTimes     += addSyncTimes;                                //新增同步次数+1
            sdnReadSql.event_ListItem         += getListItem;                                 //得到读取队列
            sdnReadSql.event_sendMail         += sendMail;                                    //发送邮件通知
            sdnReadSql.event_UpdateSyncStatus += UpdateSyncStatus;                            //更新同步状态
            //  new sys_oracle.GetWriteSQL().WriteInsertSql("CON_QUESTION_USER", "2019/10/31 9:21:37");
            sdnWriteSql = new sys_oracle.GetWriteSQL(iDays, interval, writePath, ftpUpload);
            sdnWriteSql.event_getSnowflakeId += GetSonwflake;   //给定获取雪花算法的执行体
            sdnWriteSql.event_addQueueInsert += addQueueInsert; //新增插入队列
            sdnWriteSql.InTableName_insert    = out2in_insert.Split(',');
            sdnWriteSql.InTableName_update    = out2in_update.Split(',');
            sdnWriteSql.OutTableName_insert   = in2out_insert.Split(',');
            sdnWriteSql.OutTableName_update   = in2out_update.Split(',');

            dealWarnItem = new dealQueueData(writePath, ftpUpload); // instantiation dealQueueData class.
            dealWarnItem.event_getWarnItem += getWarnList;          //bind event executive //得到本端写文件队列中的数据
            dealWarnItem.event_sendMail    += sendMail;             //发送异常信息邮件

            //sendMail($"苏大信科-异常报告{DateTime.Now.ToString("yyyyMMddHHmmss")}", "数据丢失,邮件发送测试");

            //log.Info("");
            // log.Error("error");
            // log.Info("press any key to start!!!");
            log.Info("the sync server is starting ……");
            //Console.ReadKey();
            StarThreads();
            Console.ReadKey();
            //  Console.WriteLine("Hello World!");
        }
예제 #46
0
        // Handle all the automagical stuff
        //
        public ServicesServerBase(string prompt, string[] args)
        {
            // Save raw arguments
            //
            m_Arguments = args;

            // Read command line
            //
            ArgvConfigSource argvConfig = new ArgvConfigSource(args);

            argvConfig.AddSwitch("Startup", "console", "c");
            argvConfig.AddSwitch("Startup", "logfile", "l");
            argvConfig.AddSwitch("Startup", "inifile", "i");
            argvConfig.AddSwitch("Startup", "prompt", "p");
            argvConfig.AddSwitch("Startup", "logconfig", "g");

            // Automagically create the ini file name
            //
            string fileName  = Path.GetFileNameWithoutExtension(Assembly.GetEntryAssembly().Location);
            string iniFile   = fileName + ".ini";
            string logConfig = null;

            IConfig startupConfig = argvConfig.Configs["Startup"];

            if (startupConfig != null)
            {
                // Check if a file name was given on the command line
                //
                iniFile = startupConfig.GetString("inifile", iniFile);
                //
                // Check if a prompt was given on the command line
                prompt = startupConfig.GetString("prompt", prompt);
                //
                // Check for a Log4Net config file on the command line
                logConfig = startupConfig.GetString("logconfig", logConfig);
            }

            // Find out of the file name is a URI and remote load it
            // if it's possible. Load it as a local file otherwise.
            //
            Uri configUri;

            try
            {
                if (Uri.TryCreate(iniFile, UriKind.Absolute, out configUri) &&
                    configUri.Scheme == Uri.UriSchemeHttp)
                {
                    XmlReader r = XmlReader.Create(iniFile);
                    m_Config = new XmlConfigSource(r);
                }
                else
                {
                    m_Config = new IniConfigSource(iniFile);
                }
            }
            catch (Exception)
            {
                System.Console.WriteLine("Error reading from config source {0}",
                                         iniFile);
                Thread.CurrentThread.Abort();
            }

            // Merge the configuration from the command line into the
            // loaded file
            //
            m_Config.Merge(argvConfig);

            // Refresh the startupConfig post merge
            //
            if (m_Config.Configs["Startup"] != null)
            {
                startupConfig = m_Config.Configs["Startup"];
            }

            prompt = startupConfig.GetString("Prompt", prompt);

            // Allow derived classes to load config before the console is
            // opened.
            //
            ReadConfig();

            // Create main console
            //
            string consoleType = "local";

            if (startupConfig != null)
            {
                consoleType = startupConfig.GetString("console", consoleType);
            }

            if (consoleType == "basic")
            {
                MainConsole.Instance = new CommandConsole(prompt);
            }
            else if (consoleType == "rest")
            {
                MainConsole.Instance = new RemoteConsole(prompt);
                ((RemoteConsole)MainConsole.Instance).ReadConfig(Config);
            }
            else
            {
                MainConsole.Instance = new LocalConsole(prompt);
            }

            // Configure the appenders for log4net
            //
            OpenSimAppender consoleAppender = null;
            FileAppender    fileAppender    = null;

            if (logConfig != null)
            {
                FileInfo cfg = new FileInfo(logConfig);
                XmlConfigurator.Configure(cfg);
            }
            else
            {
                XmlConfigurator.Configure();
            }

            ILoggerRepository repository = LogManager.GetRepository();

            IAppender[] appenders = repository.GetAppenders();

            foreach (IAppender appender in appenders)
            {
                if (appender.Name == "Console")
                {
                    consoleAppender = (OpenSimAppender)appender;
                }
                if (appender.Name == "LogFileAppender")
                {
                    fileAppender = (FileAppender)appender;
                }
            }

            if (consoleAppender == null)
            {
                System.Console.WriteLine("No console appender found. Server can't start");
                Thread.CurrentThread.Abort();
            }
            else
            {
                consoleAppender.Console = (ConsoleBase)MainConsole.Instance;

                if (null == consoleAppender.Threshold)
                {
                    consoleAppender.Threshold = Level.All;
                }
            }

            // Set log file
            //
            if (fileAppender != null)
            {
                if (startupConfig != null)
                {
                    string cfgFileName = startupConfig.GetString("logfile", null);
                    if (cfgFileName != null)
                    {
                        fileAppender.File = cfgFileName;
                        fileAppender.ActivateOptions();
                    }
                }
            }

            if (startupConfig.GetString("PIDFile", String.Empty) != String.Empty)
            {
                CreatePIDFile(startupConfig.GetString("PIDFile"));
            }

            // Register the quit command
            //
            MainConsole.Instance.Commands.AddCommand("base", false, "quit",
                                                     "quit",
                                                     "Quit the application", HandleQuit);

            MainConsole.Instance.Commands.AddCommand("base", false, "shutdown",
                                                     "shutdown",
                                                     "Quit the application", HandleQuit);

            // Register a command to read other commands from a file
            MainConsole.Instance.Commands.AddCommand("base", false, "command-script",
                                                     "command-script <script>",
                                                     "Run a command script from file", HandleScript);


            // Allow derived classes to perform initialization that
            // needs to be done after the console has opened
            //
            Initialise();
        }
		/// <summary>
		/// Configure the specified repository using a <see cref="FileInfo"/>
		/// </summary>
		/// <param name="targetRepository">The repository to configure.</param>
		/// <param name="configFile">the FileInfo pointing to the config file</param>
		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 (m_configureAndWatch)
			{
				XmlConfigurator.ConfigureAndWatch(targetRepository, configFile);
			}
			else
			{
				XmlConfigurator.Configure(targetRepository, configFile);
			}
#endif
		}
예제 #48
0
 public CustomersController(ICustomerRepository customerRepository, ILoggerRepository logger)
 {
     _customerRepository = customerRepository;
     _logger             = logger;
 }
예제 #49
0
		/// <summary>
		/// Automatically configures the <see cref="ILoggerRepository"/> using settings
		/// stored in the application's configuration file.
		/// </summary>
		/// <remarks>
		/// <para>
		/// 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
		/// <c>log4net</c> that contains the configuration data.
		/// </para>
		/// <para>
		/// To use this method to configure log4net you must specify 
		/// the <see cref="Log4NetConfigurationSectionHandler"/> section
		/// handler for the <c>log4net</c> configuration section. See the
		/// <see cref="Log4NetConfigurationSectionHandler"/> for an example.
		/// </para>
		/// </remarks>
		/// <param name="repository">The repository to configure.</param>
#else
		/// <summary>
		/// Automatically configures the <see cref="ILoggerRepository"/> using settings
		/// stored in the application's configuration file.
		/// </summary>
		/// <remarks>
		/// <para>
		/// 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
		/// <c>log4net</c> that contains the configuration data.
		/// </para>
		/// </remarks>
		/// <param name="repository">The repository to configure.</param>
#endif
		static public void Configure(ILoggerRepository repository) 
		{
			LogLog.Debug("XmlConfigurator: configuring repository [" + repository.Name + "] using .config file section");

			try
			{
				LogLog.Debug("XmlConfigurator: Application config file is [" + SystemInfo.ConfigurationFileLocation + "]");
			}
			catch
			{
				// ignore error
				LogLog.Debug("XmlConfigurator: Application config file location unknown");
			}

#if NETCF
			// 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("XmlConfigurator: Failed to find configuration section 'log4net' in the application's .config file. Check your .config file for the <log4net> and <configSections> elements. The configuration section should look like: <section name=\"log4net\" type=\"log4net.Config.Log4NetConfigurationSectionHandler,log4net\" />");
				}
				else
				{
					// Configure using the xml loaded from the config file
					ConfigureFromXml(repository, configElement);
				}
			}
			catch(System.Configuration.ConfigurationException confEx)
			{
				if (confEx.BareMessage.IndexOf("Unrecognized element") >= 0)
				{
					// Looks like the XML file is not valid
					LogLog.Error("XmlConfigurator: 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 = "<section name=\"log4net\" type=\"log4net.Config.Log4NetConfigurationSectionHandler," + Assembly.GetExecutingAssembly().FullName + "\" />";
					LogLog.Error("XmlConfigurator: Failed to parse config file. Is the <configSections> specified as: " + configSectionStr, confEx);
				}
			}
#endif
		}
예제 #50
0
        /// <summary>
        /// 为程序集创建新的 ILoggerRepository
        /// </summary>
        /// <param name="repositoryAssembly"></param>
        /// <param name="repositoryType">要创建的 ILoggerRepository 的具体类型, must implement <see cref="ILoggerRepository"/>.</param>
        /// <param name="repositoryName"></param>
        /// <param name="readAssemblyAttributes">是否读取程序集的特性</param>
        /// <returns></returns>
        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 = m_defaultRepositoryType;
            }

            lock (this)
            {
                // Lookup in map
                ILoggerRepository rep = 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
                        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 = m_name2repositoryMap[actualRepositoryName] as ILoggerRepository;
                    if (rep == null)
                    {
                        // Create the repository
                        rep = CreateRepository(actualRepositoryName, actualRepositoryType);

                        if (readAssemblyAttributes)
                        {
                            try
                            {
                                // Look for aliasing attributes
                                LoadAliases(repositoryAssembly, rep);

                                // Look for plugins defined on the assembly
                                //LoadPlugins(repositoryAssembly, rep);

                                // Configure the repository using the assembly attributes
                                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
                                //LoadPlugins(repositoryAssembly, rep);
                            }
                            catch (Exception ex)
                            {
                                LogLog.Error(declaringType, "Failed to configure repository [" + actualRepositoryName + "] from assembly attributes.", ex);
                            }
                        }
                    }
                    m_assembly2repositoryMap[repositoryAssembly] = rep;
                }
                return(rep);
            }
        }
예제 #51
0
		/// <summary>
		/// Configures the <see cref="ILoggerRepository"/> using the specified configuration 
		/// file.
		/// </summary>
		/// <param name="repository">The repository to configure.</param>
		/// <param name="configFile">The XML file to load the configuration from.</param>
		/// <remarks>
		/// <para>
		/// The configuration file must be valid XML. It must contain
		/// at least one element called <c>log4net</c> that holds
		/// the configuration data.
		/// </para>
		/// <para>
		/// The log4net configuration file can possible be specified in the application's
		/// configuration file (either <c>MyAppName.exe.config</c> for a
		/// normal application on <c>Web.config</c> for an ASP.NET application).
		/// </para>
		/// <para>
		/// The first element matching <c>&lt;configuration&gt;</c> will be read as the 
		/// configuration. If this file is also a .NET .config file then you must specify 
		/// a configuration section for the <c>log4net</c> element otherwise .NET will 
		/// complain. Set the type for the section handler to <see cref="System.Configuration.IgnoreSectionHandler"/>, for example:
		/// <code lang="XML" escaped="true">
		/// <configSections>
		///		<section name="log4net" type="System.Configuration.IgnoreSectionHandler" />
		///	</configSections>
		/// </code>
		/// </para>
		/// <example>
		/// The following example configures log4net using a configuration file, of which the 
		/// location is stored in the application's configuration file :
		/// </example>
		/// <code lang="C#">
		/// using log4net.Config;
		/// using System.IO;
		/// using System.Configuration;
		/// 
		/// ...
		/// 
		/// XmlConfigurator.Configure(new FileInfo(ConfigurationSettings.AppSettings["log4net-config-file"]));
		/// </code>
		/// <para>
		/// In the <c>.config</c> file, the path to the log4net can be specified like this :
		/// </para>
		/// <code lang="XML" escaped="true">
		/// <configuration>
		///		<appSettings>
		///			<add key="log4net-config-file" value="log.config"/>
		///		</appSettings>
		///	</configuration>
		/// </code>
		/// </remarks>
#else
		/// <summary>
		/// Configures the <see cref="ILoggerRepository"/> using the specified configuration 
		/// file.
		/// </summary>
		/// <param name="repository">The repository to configure.</param>
		/// <param name="configFile">The XML file to load the configuration from.</param>
		/// <remarks>
		/// <para>
		/// The configuration file must be valid XML. It must contain
		/// at least one element called <c>log4net</c> that holds
		/// the configuration data.
		/// </para>
		/// <example>
		/// The following example configures log4net using a configuration file, of which the 
		/// location is stored in the application's configuration file :
		/// </example>
		/// <code lang="C#">
		/// using log4net.Config;
		/// using System.IO;
		/// using System.Configuration;
		/// 
		/// ...
		/// 
		/// XmlConfigurator.Configure(new FileInfo(ConfigurationSettings.AppSettings["log4net-config-file"]));
		/// </code>
		/// <para>
		/// In the <c>.config</c> file, the path to the log4net can be specified like this :
		/// </para>
		/// <code lang="XML" escaped="true">
		/// <configuration>
		///		<appSettings>
		///			<add key="log4net-config-file" value="log.config"/>
		///		</appSettings>
		///	</configuration>
		/// </code>
		/// </remarks>
#endif
		static public void Configure(ILoggerRepository repository, FileInfo configFile)
		{
			LogLog.Debug("XmlConfigurator: configuring repository [" + repository.Name + "] using file [" + configFile + "]");

			if (configFile == null)
			{
				LogLog.Error("XmlConfigurator: 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("XmlConfigurator: 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
							Configure(repository, fs);
						}
						finally
						{
							// Force the file closed whatever happens
							fs.Close();
						}
					}
				}
				else
				{
					LogLog.Debug("XmlConfigurator: config file [" + configFile.FullName + "] not found. Configuration unchanged.");
				}
			}
		}
예제 #52
0
 protected virtual void OnLoggerRepositoryCreatedEvent(ILoggerRepository repository)
 {
     m_loggerRepositoryCreatedEvent?.Invoke(this, new LoggerRepositoryCreationEventArgs(repository));
 }
예제 #53
0
		/// <summary>
		/// Configures the <see cref="ILoggerRepository"/> using the specified configuration 
		/// file.
		/// </summary>
		/// <param name="repository">The repository to configure.</param>
		/// <param name="configStream">The stream to load the XML configuration from.</param>
		/// <remarks>
		/// <para>
		/// The configuration data must be valid XML. It must contain
		/// at least one element called <c>log4net</c> that holds
		/// the configuration data.
		/// </para>
		/// <para>
		/// Note that this method will NOT close the stream parameter.
		/// </para>
		/// </remarks>
		static public void Configure(ILoggerRepository repository, Stream configStream)
		{
			LogLog.Debug("XmlConfigurator: configuring repository [" + repository.Name + "] using stream");

			if (configStream == null)
			{
				LogLog.Error("XmlConfigurator: Configure called with null 'configStream' parameter");
			}
			else
			{
				// Load the config file into a document
				XmlDocument doc = new XmlDocument();
				try
				{
#if (NETCF)
					// Create a text reader for the file stream
					XmlTextReader xmlReader = new XmlTextReader(configStream);
#elif NET_2_0
					// Allow the DTD to specify entity includes
					XmlReaderSettings settings = new XmlReaderSettings();
#if NET_4_0
                    settings.DtdProcessing = DtdProcessing.Parse;
#else
                    settings.ProhibitDtd = false;
#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("XmlConfigurator: Error while loading XML configuration", ex);

					// The document is invalid
					doc = null;
				}

				if (doc != null)
				{
					LogLog.Debug("XmlConfigurator: loading XML configuration");

					// Configure using the 'log4net' element
					XmlNodeList configNodeList = doc.GetElementsByTagName("log4net");
					if (configNodeList.Count == 0)
					{
						LogLog.Debug("XmlConfigurator: XML configuration does not contain a <log4net> element. Configuration Aborted.");
					}
					else if (configNodeList.Count > 1)
					{
						LogLog.Error("XmlConfigurator: XML configuration contains [" + configNodeList.Count + "] <log4net> elements. Only one is allowed. Configuration Aborted.");
					}
					else
					{
						ConfigureFromXml(repository, configNodeList[0] as XmlElement);
					}
				}
			}
		}
예제 #54
0
        /// <summary>
        /// 使用程序集中的信息 配置 ILoggerRepository
        /// </summary>
        /// <param name="assembly"></param>
        /// <param name="repository"></param>
        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
            object[] configAttributes = Attribute.GetCustomAttributes(assembly, typeof(ConfiguratorAttribute), false);
            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.

                // 如果时默认库,就读取 AppSettings 下的默认配置文件,覆盖掉之前设置的

                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;
                    Boolean.TryParse(SystemInfo.GetAppSetting("log4net.Config.Watch"), out watchRepositoryConfigFile);

                    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);
                            }
                        }
                    }
                }
            }
        }
예제 #55
0
			/// <summary>
			/// Watch a specified config file used to configure a repository
			/// </summary>
			/// <param name="repository">The repository to configure.</param>
			/// <param name="configFile">The configuration file to watch.</param>
			/// <remarks>
			/// <para>
			/// Watch a specified config file used to configure a repository
			/// </para>
			/// </remarks>
			internal static void StartWatching(ILoggerRepository repository, FileInfo configFile)
			{
				new ConfigureAndWatchHandler(repository, configFile);
			}
예제 #56
0
        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 = m_defaultRepositoryType;
            }

            lock (this)
            {
                ILoggerRepository rep = null;

                // First check that the repository does not exist
                rep = 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 = 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
                            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
                        m_name2repositoryMap[repositoryName] = rep;

                        // Notify listeners that the repository has been created
                        OnLoggerRepositoryCreatedEvent(rep);
                    }
                }

                return(rep);
            }
        }
        /// <summary>
        /// Attempt to load configuration from a URI
        /// </summary>
        /// <param name="sourceAssembly">The assembly that this attribute was defined on.</param>
        /// <param name="targetRepository">The repository to configure.</param>
        private void ConfigureFromUri(Assembly sourceAssembly, ILoggerRepository targetRepository)
        {
            // Work out the full path to the config file
            Uri fullPath2ConfigFile = null;

            // Select the config file
            if (m_configFile == null || m_configFile.Length == 0)
            {
                if (m_configFileExtension == null || m_configFileExtension.Length == 0)
                {
                    string systemConfigFilePath = null;
                    try
                    {
                        systemConfigFilePath = SystemInfo.ConfigurationFileLocation;
                    }
                    catch (Exception ex)
                    {
                        LogLog.Error("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 (m_configFileExtension[0] != '.')
                    {
                        m_configFileExtension = "." + m_configFileExtension;
                    }

                    string systemConfigFilePath = null;
                    try
                    {
                        systemConfigFilePath = SystemInfo.ConfigurationFileLocation;
                    }
                    catch (Exception ex)
                    {
                        LogLog.Error("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 += m_configFileExtension;

                        builder.Path        = path;
                        fullPath2ConfigFile = builder.Uri;
                    }
                }
            }
            else
            {
                string applicationBaseDirectory = null;
                try
                {
                    applicationBaseDirectory = SystemInfo.ApplicationBaseDirectory;
                }
                catch (Exception ex)
                {
                    LogLog.Warn("XmlConfiguratorAttribute: Exception getting ApplicationBaseDirectory. ConfigFile property path [" + 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), m_configFile);
                }
                else
                {
                    fullPath2ConfigFile = new Uri(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
                    ConfigureFromFile(targetRepository, new FileInfo(fullPath2ConfigFile.LocalPath));
                }
                else
                {
                    if (m_configureAndWatch)
                    {
                        LogLog.Warn("XmlConfiguratorAttribute: Unable to watch config file loaded from a URI");
                    }
                    XmlConfigurator.Configure(targetRepository, fullPath2ConfigFile);
                }
            }
        }
예제 #58
0
 static public void Configure(ILoggerRepository repository, Stream configStream)
 {
     XmlConfigurator.Configure(repository, configStream);
 }
예제 #59
0
		/// <summary>
		/// Notify the registered listeners that the repository has been created
		/// </summary>
		/// <param name="repository">The repository that has been created</param>
		/// <remarks>
		/// <para>
		/// Raises the <event cref="LoggerRepositoryCreatedEvent">LoggerRepositoryCreatedEvent</event>
		/// event.
		/// </para>
		/// </remarks>
		protected virtual void OnLoggerRepositoryCreatedEvent(ILoggerRepository repository)
		{
			LoggerRepositoryCreationEventHandler handler = m_loggerRepositoryCreatedEvent;
			if (handler != null)
			{
				handler(this, new LoggerRepositoryCreationEventArgs(repository));
			}
		}
예제 #60
0
        /// <summary>
        /// Constructor Creates MainConsole.Instance to take commands and provide the place to write data
        /// </summary>
        public BotManager()
        {
            InitBotSendAgentUpdates      = true;
            InitBotRequestObjectTextures = true;

            LoginDelay = DefaultLoginDelay;

            Rng            = new Random(Environment.TickCount);
            AssetsReceived = new Dictionary <UUID, bool>();
            RegionsKnown   = new Dictionary <ulong, GridRegion>();

            m_console            = CreateConsole();
            MainConsole.Instance = m_console;

            // Make log4net see the console
            //
            ILoggerRepository repository = LogManager.GetRepository();

            IAppender[]     appenders       = repository.GetAppenders();
            OpenSimAppender consoleAppender = null;

            foreach (IAppender appender in appenders)
            {
                if (appender.Name == "Console")
                {
                    consoleAppender         = (OpenSimAppender)appender;
                    consoleAppender.Console = m_console;
                    break;
                }
            }

            m_console.Commands.AddCommand(
                "Bots", false, "shutdown", "shutdown", "Shutdown bots and exit", HandleShutdown);

            m_console.Commands.AddCommand(
                "Bots", false, "quit", "quit", "Shutdown bots and exit", HandleShutdown);

            m_console.Commands.AddCommand(
                "Bots", false, "connect", "connect [<n>]", "Connect bots",
                "If an <n> is given, then the first <n> disconnected bots by postfix number are connected.\n"
                + "If no <n> is given, then all currently disconnected bots are connected.",
                HandleConnect);

            m_console.Commands.AddCommand(
                "Bots", false, "disconnect", "disconnect [<n>]", "Disconnect bots",
                "Disconnecting bots will interupt any bot connection process, including connection on startup.\n"
                + "If an <n> is given, then the last <n> connected bots by postfix number are disconnected.\n"
                + "If no <n> is given, then all currently connected bots are disconnected.",
                HandleDisconnect);

            m_console.Commands.AddCommand(
                "Bots", false, "add behaviour", "add behaviour <abbreviated-name> [<bot-number>]",
                "Add a behaviour to a bot",
                "If no bot number is specified then behaviour is added to all bots.\n"
                + "Can be performed on connected or disconnected bots.",
                HandleAddBehaviour);

            m_console.Commands.AddCommand(
                "Bots", false, "remove behaviour", "remove behaviour <abbreviated-name> [<bot-number>]",
                "Remove a behaviour from a bot",
                "If no bot number is specified then behaviour is added to all bots.\n"
                + "Can be performed on connected or disconnected bots.",
                HandleRemoveBehaviour);

            m_console.Commands.AddCommand(
                "Bots", false, "sit", "sit", "Sit all bots on the ground.",
                HandleSit);

            m_console.Commands.AddCommand(
                "Bots", false, "stand", "stand", "Stand all bots.",
                HandleStand);

            m_console.Commands.AddCommand(
                "Bots", false, "set bots", "set bots <key> <value>", "Set a setting for all bots.", HandleSetBots);

            m_console.Commands.AddCommand(
                "Bots", false, "show regions", "show regions", "Show regions known to bots", HandleShowRegions);

            m_console.Commands.AddCommand(
                "Bots", false, "show bots", "show bots", "Shows the status of all bots", HandleShowBotsStatus);

            m_console.Commands.AddCommand(
                "Bots", false, "show bot", "show bot <bot-number>",
                "Shows the detailed status and settings of a particular bot.", HandleShowBotStatus);

            m_bots = new List <Bot>();
        }