Example #1
0
        // Create a new file appender
        public static void ConfigureLog4net(string name, string fileName)
        {
            PatternLayout layout = new PatternLayout("%date{yyyy-MM-dd HH:mm:ss,fff} %-5level [%thread]: %message%newline");

            layout.ActivateOptions();

            LevelMatchFilter filter = new LevelMatchFilter();

            filter.LevelToMatch = Level.All;
            filter.ActivateOptions();

            var appender = new FileAppender();

            appender.Name         = name;
            appender.File         = fileName;
            appender.AppendToFile = false;

            appender.Layout = layout;
            appender.AddFilter(filter);
            appender.ActivateOptions();

            ILoggerRepository repository = LoggerManager.CreateRepository(name);

            BasicConfigurator.Configure(repository, appender);
        }
Example #2
0
        public TracingInterceptor(string filePath)
        {
            PatternLayout layout = new PatternLayout("% date{ MMM / dd / yyyy HH:mm: ss,fff} [%thread] %-5level %logger %ndc – %message%newline");

            LevelMatchFilter filter = new LevelMatchFilter();

            filter.LevelToMatch = Level.All;
            filter.ActivateOptions();

            RollingFileAppender appender = new RollingFileAppender();

            appender.File           = filePath;
            appender.ImmediateFlush = true;
            appender.AppendToFile   = true;
            appender.RollingStyle   = RollingFileAppender.RollingMode.Date;
            appender.DatePattern    = "-yyyy - MM - dd";
            appender.LockingModel   = new FileAppender.MinimalLock();
            appender.Name           = "MyAppender";
            appender.AddFilter(filter);
            appender.Layout = layout;
            appender.ActivateOptions();

            ILoggerRepository repository = LoggerManager.CreateRepository("MyRepository");

            BasicConfigurator.Configure(repository, appender);

            _logger = LogManager.GetLogger("MyRepository", "MyLogger");
        }
Example #3
0
        private ILog InitializeLogger(string connectionString)
        {
            var filter = new LevelMatchFilter();

            filter.LevelToMatch = Level.All;
            filter.ActivateOptions();

            var appender = new PostgreSqlAppender(connectionString);

            appender.AddFilter(filter);
            appender.ActivateOptions();

            string assemblyName = System.Reflection.Assembly.GetExecutingAssembly().GetName().FullName;

            this.repositoryName = String.Format("{0} Repository", assemblyName);

            var repository = LoggerManager.CreateRepository(repositoryName);

            string loggerName = String.Format("{0} Logger", assemblyName);

            BasicConfigurator.Configure(repository, appender);
            ILog logger = LogManager.GetLogger(repositoryName, loggerName);

            return(logger);
        }
Example #4
0
        private static ILog CreateUserManagementLogger()
        {
            string instanceName = "UserManagement";

            PatternLayout layout = new PatternLayout(
                "% date{ MMM / dd / yyyy HH:mm: ss,fff}[%thread] %-5level %logger %ndc – %message%newline");

            LevelMatchFilter filter = new LevelMatchFilter();

            filter.LevelToMatch = Level.All;
            filter.ActivateOptions();

            RollingFileAppender appender = new RollingFileAppender();

            appender.File           = "userManagement.log"; // string.Format("{0}\\{1}", "", "common.log");
            appender.ImmediateFlush = true;
            appender.AppendToFile   = true;
            appender.RollingStyle   = RollingFileAppender.RollingMode.Date;
            appender.DatePattern    = "-yyyy - MM - dd";
            appender.LockingModel   = new FileAppender.MinimalLock();
            appender.Name           = string.Format("{0}Appender", instanceName);
            appender.AddFilter(filter);
            appender.Layout = layout;
            appender.ActivateOptions();

            string            repositoryName = string.Format("{0}Repository", instanceName);
            ILoggerRepository repository     = LoggerManager.CreateRepository(repositoryName);
            string            loggerName     = string.Format("{0}Logger", instanceName);

            BasicConfigurator.Configure(repository, appender);
            return(LogManager.GetLogger(repositoryName, loggerName));
        }
Example #5
0
        private static RollingFileAppender CreateAppender(Level level, PatternLayout layout, string instanceName)
        {
            DenyAllFilter filterD = new DenyAllFilter();

            filterD.ActivateOptions();
            LevelMatchFilter filter = new LevelMatchFilter();

            filter.AcceptOnMatch = true;
            filter.LevelToMatch  = level;
            filter.ActivateOptions();
            RollingFileAppender appender = new RollingFileAppender();

            appender.File              = $"{_mainDirectory}\\logs\\";
            appender.ImmediateFlush    = true;
            appender.Encoding          = Encoding.UTF8;
            appender.StaticLogFileName = false;
            appender.AppendToFile      = true;
            appender.RollingStyle      = RollingFileAppender.RollingMode.Date;
            appender.DatePattern       = $"dd.MM.yyyy\\\\'{level.Name}.log'";
            appender.LockingModel      = new FileAppender.MinimalLock();
            appender.Name              = $"{instanceName}Appender_{level.Name}";
            appender.AddFilter(filter);
            appender.AddFilter(filterD);
            appender.Layout = layout;
            appender.ActivateOptions();
            return(appender);
        }
Example #6
0
        /// <summary>
        ///     Creates the appender.
        /// </summary>
        /// <param name="name">The name.</param>
        /// <param name="file">The file.</param>
        /// <param name="logLevel">The log level.</param>
        /// <returns>
        ///     Returns a <see cref="IAppender" /> representing the appender.
        /// </returns>
        protected override FileAppender CreateAppender(string name, string file, LogLevel logLevel)
        {
            PatternLayout layout = new PatternLayout("%date{yyyy-MM-dd hh:mm:ss tt} - [%level]: %message%newline%exception");

            LevelMatchFilter filter = new LevelMatchFilter();

            filter.LevelToMatch = logLevel.ToLevel();
            filter.ActivateOptions();

            var ext = Path.GetExtension(file);

            var appender = new RollingFileAppender();

            appender.Name              = name;
            appender.File              = !string.IsNullOrEmpty(ext) ? file.Replace(ext, "") : file;
            appender.ImmediateFlush    = true;
            appender.RollingStyle      = RollingFileAppender.RollingMode.Date;
            appender.StaticLogFileName = false;
            appender.DatePattern       = "_yyyy-MM-dd'.log'";
            appender.AppendToFile      = true;
            appender.LockingModel      = new FileAppender.MinimalLock();
            appender.AddFilter(filter);
            appender.Layout = layout;
            appender.ActivateOptions();

            return(appender);
        }
        private void SetLevel()
        {
            filter = new LevelMatchFilter();
            LogLevel level;

            if (!Enum.TryParse(Convert.ToString(ConfigurationManager.AppSettings["MyLogger.Level"]), out level))
            {
                throw new Exception("invalid level type.");
            }
            switch (level)
            {
            case LogLevel.Debug:
            {
                filter.LevelToMatch = Level.Debug;
                break;
            }

            case LogLevel.Error:
            {
                filter.LevelToMatch = Level.Error;
                break;
            }

            case LogLevel.Fatal:
            {
                filter.LevelToMatch = Level.Fatal;
                break;
            }

            case LogLevel.Info:
            {
                filter.LevelToMatch = Level.Info;
                break;
            }

            case LogLevel.Warning:
            {
                filter.LevelToMatch = Level.Warn;
                break;
            }

            case LogLevel.All:
            {
                filter.LevelToMatch = Level.All;
                break;
            }
            }
            filter.ActivateOptions();
        }
Example #8
0
        /// <summary>
        /// 创建日志实例
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        private static ILog CreateLoggerInstance(string name)
        {
            // Pattern Layout
            PatternLayout layout = new PatternLayout("[%logger][%date]%message\r\n");
            // Level Filter
            LevelMatchFilter filter = new LevelMatchFilter();

            filter.LevelToMatch = Level.All;
            filter.ActivateOptions();
            // File Appender
            RollingFileAppender appender = new RollingFileAppender();

            // 目录
            appender.File = $"log{Path.AltDirectorySeparatorChar}{name}.log";
            // 立即写入磁盘
            appender.ImmediateFlush = true;
            // true:追加到文件;false:覆盖文件
            appender.AppendToFile = true;
            // 新的日期或者文件大小达到上限,新建一个文件
            appender.RollingStyle = RollingFileAppender.RollingMode.Once;
            // 文件大小达到上限,新建文件时,文件编号放到文件后缀前面
            appender.PreserveLogFileNameExtension = true;
            // 最小锁定模型以允许多个进程可以写入同一个文件
            appender.LockingModel = new FileAppender.MinimalLock();
            appender.Name         = $"{name}Appender";
            appender.AddFilter(filter);
            appender.Layout = layout;
            appender.ActivateOptions();
            // 设置无限备份=-1 ,最大备份数为30
            appender.MaxSizeRollBackups = 30;
            appender.StaticLogFileName  = true;
            string repositoryName = $"{name}Repository";

            try
            {
                LoggerManager.GetRepository(repositoryName);
            }
            catch
            {
                ILoggerRepository repository = LoggerManager.CreateRepository(repositoryName);
                BasicConfigurator.Configure(repository, appender);
            }
            var logger = LogManager.GetLogger(repositoryName, name);

            return(logger);
        }
Example #9
0
        public ILog GetLog()
        {
            if (this.configurationRoot == null)
            {
                this.configurationRoot = this.GetConfigurationRoot(this.fileFolderPath, this.fileName);
            }

            IConfigurationSection          log4netSection = this.GetLog4NetConfigurationSection(this.configurationRoot);
            IEnumerable <AppenderSkeleton> appenders      = this.GetAppenders(this.configurationRoot, log4netSection);
            IConfigurationSection          loggerSection  = this.GetLoggerSection(log4netSection);

            IConfigurationSection name       = loggerSection.GetSection("name");
            string            repositoryName = String.Format("{0} Repository", name.Value);
            ILoggerRepository repository     = LoggerManager.CreateRepository(repositoryName);
            string            loggerName     = String.Format("{0} Logger", name.Value);

            IConfigurationSection level = loggerSection.GetSection("level");
            string levelName            = "All";

            if (level != null && !String.IsNullOrEmpty(level.Value))
            {
                levelName = level.Value;
            }
            ILoggerRepository loggerRepository = LoggerManager.GetAllRepositories().FirstOrDefault();
            LevelMatchFilter  filter           = new LevelMatchFilter();

            filter.LevelToMatch = loggerRepository.LevelMap[levelName];
            filter.ActivateOptions();

            foreach (var appender in appenders)
            {
                appender.AddFilter(filter);
                appender.ActivateOptions();

                BasicConfigurator.Configure(repository, appender);
            }

            ILog logger = LogManager.GetLogger(repositoryName, loggerName);

            return(logger);
        }
Example #10
0
        //another create version

        public static log4net.Appender.IAppender createAnotherThingy()
        {
            string folderPath   = "C:\\OzzElectricLogs";
            string instanceName = "instanceNameGod";

            //Layout Pattern
            PatternLayout layout = new PatternLayout("% date{ MMM / dd / yyyy HH:mm: ss,fff}[%thread] %-5level %logger %ndc – %message%newline");

            //Level Filter
            LevelMatchFilter filter = new LevelMatchFilter();

            filter.LevelToMatch = Level.All;
            filter.ActivateOptions();

            RollingFileAppender appender = new RollingFileAppender();

            appender.File           = string.Format("{0}\\{1}", folderPath, "common.log");
            appender.ImmediateFlush = true;
            appender.AppendToFile   = true;
            appender.RollingStyle   = RollingFileAppender.RollingMode.Date;
            appender.DatePattern    = "-yyyy-MM-dd";
            appender.LockingModel   = new FileAppender.MinimalLock();
            appender.Name           = string.Format("{0}Appender", instanceName);
            appender.AddFilter(filter);
            appender.ActivateOptions();

            //Populate the log instance
            string            repositoryName = string.Format("{0}Repository", instanceName);
            ILoggerRepository repository     = LoggerManager.CreateRepository(repositoryName);
            string            loggerName     = string.Format("{0}Logger", instanceName);

            BasicConfigurator.Configure(repository, appender);

            ILog loggering = LogManager.GetLogger(repositoryName, loggerName);

            loggering.Debug("test print yo");


            return(appender);
        }
Example #11
0
        /// <summary>
        ///     Creates the appender.
        /// </summary>
        /// <param name="name">The name.</param>
        /// <param name="file">The file.</param>
        /// <param name="logLevel">The log level.</param>
        /// <returns>
        ///     Returns a <see cref="IAppender" /> representing the appender.
        /// </returns>
        protected virtual FileAppender CreateAppender(string name, string file, LogLevel logLevel)
        {
            PatternLayout layout = new PatternLayout("%date{yyyy-MM-dd hh:mm:ss tt} - [%level]: %message%newline%exception");

            LevelMatchFilter filter = new LevelMatchFilter();

            filter.LevelToMatch = logLevel.ToLevel();
            filter.ActivateOptions();

            var appender = new FileAppender();

            appender.Name           = name;
            appender.File           = file;
            appender.ImmediateFlush = true;
            appender.AppendToFile   = _FileMode == FileMode.Append;
            appender.LockingModel   = new FileAppender.MinimalLock();
            appender.AddFilter(filter);
            appender.Layout = layout;
            appender.ActivateOptions();

            return(appender);
        }
Example #12
0
        static async Task Main(string[] args)
        {
            var builder = new ContainerBuilder();

            builder.RegisterType <Server>().PropertiesAutowired().EnableClassInterceptors().SingleInstance();

            builder.RegisterType <FtsIndexService>().PropertiesAutowired().SingleInstance();
            builder.RegisterType <MangaKeywordSearchService>().PropertiesAutowired().SingleInstance();
            builder.RegisterType <TagKeywordSearchService>().PropertiesAutowired().SingleInstance();
            builder.RegisterType <MangaReadHistorySearchService>().PropertiesAutowired().SingleInstance();
            builder.RegisterType <FavoriteMangaSearchService>().PropertiesAutowired().SingleInstance();
            builder.RegisterType <Scheduler>().PropertiesAutowired().SingleInstance();
            builder.RegisterType <MessageManager>().PropertiesAutowired().SingleInstance();
            builder.RegisterType <MangaManager>().PropertiesAutowired().SingleInstance();
            builder.RegisterType <LibraryManager>().PropertiesAutowired().SingleInstance();
            builder.RegisterType <UserManager>().PropertiesAutowired().SingleInstance();
            builder.RegisterType <ConfigLoader>().PropertiesAutowired().SingleInstance();
            builder.Register(context =>
            {
                var planManager = new PlanManager(context.Resolve <ILog>())
                {
                    CronTriggerHandler       = context.Resolve <ITriggerHandler <CronTrigger> >(),
                    DisposableTriggerHandler = context.Resolve <ITriggerHandler <DisposableTrigger> >(),
                    MessageManager           = context.Resolve <MessageManager>(),
                    ScanPlanHandler          = context.Resolve <IPlanHandler <ScanPlan> >(),
                    DownloadPlanHandler      = context.Resolve <IPlanHandler <DownloadPlan> >()
                };
                planManager.TaskCompletedTriggerHandler = new TaskCompletedTriggerHandler {
                    PlanManager = planManager
                };
                planManager.Recover();
                return(planManager);
            }).As <PlanManager>().SingleInstance();

            builder.Register(context =>
            {
                var configLoader = context.Resolve <ConfigLoader>();
                var level        = configLoader.Config.LogConfig.Level switch
                {
                    "All" => Level.All,
                    "Info" => Level.Info,
                    "Debug" => Level.Debug,
                    "Warn" => Level.Warn,
                    "Error" => Level.Error,
                    "Fatal" => Level.Fatal,
                    "Off" => Level.Off,
                    _ => Level.All
                };
                var layout = new PatternLayout("%date{yyyy-MM-dd HH:mm:ss} [%-5level]–%message %newline");

                var fileFilter = new LevelMatchFilter {
                    LevelToMatch = level
                };
                fileFilter.ActivateOptions();

                var fileAppender = new RollingFileAppender
                {
                    File               = configLoader.Config.LogConfig.Path,
                    ImmediateFlush     = true,
                    AppendToFile       = true,
                    RollingStyle       = RollingFileAppender.RollingMode.Date,
                    DatePattern        = "yyyyMMdd'.log'",
                    LockingModel       = new FileAppender.InterProcessLock(),
                    Name               = "Otokoneko File Appender",
                    MaxSizeRollBackups = configLoader.Config.LogConfig.MaxSizeRollBackups,
                    Encoding           = Encoding.UTF8,
                    StaticLogFileName  = false,
                    Layout             = layout
                };
                fileAppender.AddFilter(fileFilter);
                fileAppender.ActivateOptions();

                var consoleAppender = new ConsoleAppender()
                {
                    Layout = layout,
                    Name   = "Otokoneko Console Appender",
                };

                var repository        = LoggerManager.CreateRepository("Otokoneko Repository");
                repository.Configured = true;
                BasicConfigurator.Configure(repository, fileAppender, consoleAppender);
                return(LogManager.GetLogger("Otokoneko Repository", "Otokoneko Logger"));
            }).As <ILog>().SingleInstance();

            builder.RegisterType <FileTreeNodeToMangaConverter>().PropertiesAutowired().SingleInstance();

            builder.RegisterType <PluginParameterProvider>().PropertiesAutowired().SingleInstance();
            builder.RegisterType <PluginLoader>().PropertiesAutowired().SingleInstance();
            builder.RegisterType <PluginManager>().PropertiesAutowired().SingleInstance();

            builder.RegisterType <DownloadPlanHandler>().PropertiesAutowired().As <IPlanHandler <DownloadPlan> >();
            builder.RegisterType <ScanPlanHandler>().PropertiesAutowired().As <IPlanHandler <ScanPlan> >();

            builder.RegisterType <TaskCompletedTriggerHandler>().PropertiesAutowired(PropertyWiringOptions.AllowCircularDependencies).As <ITriggerHandler <TaskCompletedTrigger> >();
            builder.RegisterType <DisposableTriggerHandler>().PropertiesAutowired().As <ITriggerHandler <DisposableTrigger> >();
            builder.RegisterType <CronTriggerHandler>().PropertiesAutowired().As <ITriggerHandler <CronTrigger> >();

            builder.RegisterType <DownloadMangaTaskHandler>().PropertiesAutowired().As <ITaskHandler <DownloadMangaScheduleTask> >();
            builder.RegisterType <DownloadChapterTaskHandler>().PropertiesAutowired().As <ITaskHandler <DownloadChapterScheduleTask> >();
            builder.RegisterType <DownloadImageTaskHandler>().PropertiesAutowired().As <ITaskHandler <DownloadImageScheduleTask> >();
            builder.RegisterType <ScanLibraryTaskHandler>().PropertiesAutowired().As <ITaskHandler <ScanLibraryTask> >();
            builder.RegisterType <ScanMangaTaskHandler>().PropertiesAutowired().As <ITaskHandler <ScanMangaTask> >();

            builder.Register(c => MessagePackSerializerOptions.Standard.WithCompression(MessagePackCompression.Lz4Block))
            .As <MessagePackSerializerOptions>()
            .SingleInstance();

            builder.Register((c, p) =>
            {
                var config = new ConnectionConfig()
                {
                    DbType                = DbType.Sqlite,
                    ConnectionString      = p.TypedAs <string>(),
                    IsAutoCloseConnection = true,
                    InitKeyType           = InitKeyType.Attribute
                };
                return(new SqlSugarClient(config));
            })
            .As <SqlSugarClient>()
            .As <ISqlSugarClient>();

            var container = builder.Build();

            Logger = container.Resolve <ILog>();

            Directory.CreateDirectory(@"./certificate");
            Directory.CreateDirectory(@"./data");
            Directory.CreateDirectory(@"./data/thumbnail");
            Directory.CreateDirectory(@"./data/library");
            Directory.CreateDirectory(@"./plugins");

            Console.CancelKeyPress += ConsoleOnCancelKeyPress;

            var server = container.Resolve <Server>();

            server.GenerateClientConfig();

            var userManager = container.Resolve <UserManager>();
            await userManager.CreateRootUser();

            await server.Run();
        }
Example #13
0
        public static ILog GetLoggerInstance(string fileName, string filepath)
        {
            var logFileDirectoryPath = filepath;
            var logFilesDirectory    = new DirectoryInfo(logFileDirectoryPath);

            if (!logFilesDirectory.Exists)
            {
                logFilesDirectory.Create();
            }

            var logfilePath = logFileDirectoryPath + "\\" + fileName + ".txt";

            PatternLayout    layout = new PatternLayout("%date %level - %message%newline");
            LevelMatchFilter filter = new LevelMatchFilter
            {
                LevelToMatch = Level.All
            };

            filter.ActivateOptions();


            string            repositoryName = string.Format("{0}Repository", fileName);
            ILoggerRepository repository;


            var repos      = LoggerManager.GetAllRepositories();
            var repoExists = false;

            foreach (var operationRepo in repos)
            {
                if (repositoryName == operationRepo.Name)
                {
                    repoExists = true;
                    break;
                }
            }
            RollingFileAppender appender = new RollingFileAppender();;

            if (!repoExists)
            {
                repository = LoggerManager.CreateRepository(repositoryName);

                appender = new RollingFileAppender
                {
                    File           = string.Concat(logFileDirectoryPath, fileName, ".txt"),
                    ImmediateFlush = true,
                    AppendToFile   = true,
                    RollingStyle   = RollingFileAppender.RollingMode.Date,
                    DatePattern    = "-yyyy-MM-dd",
                    LockingModel   = new FileAppender.MinimalLock(),
                    Name           = string.Format("{0}Appender", fileName)
                };
                appender.AddFilter(filter);
                appender.Layout = layout;
                appender.ActivateOptions();
            }
            else
            {
                repository = LoggerManager.GetRepository(repositoryName);
            }


            string loggerName = string.Format("{0}Logger", fileName);

            BasicConfigurator.Configure(repository, appender);
            //BasicConfigurator.Configure()
            ILog logger = LogManager.GetLogger(repositoryName, loggerName);

            return(logger);
        }