Ejemplo n.º 1
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="services"></param>
        /// <param name="logAction">logAction</param>
        /// <para>e.g. .Logs or wwwroor/logs or C:/wwwroot/logs</para>
        public static IServiceCollection AddFileLog(this IServiceCollection services, Action <LogOptions> logAction = null)
        {
            bool flag = !services.Any((ServiceDescriptor x) => x.ImplementationType == typeof(LoggerFactory));

            if (flag)
            {
                LogOptions logOptions = new LogOptions();
                if (logAction != null)
                {
                    logAction(logOptions);
                }
                services.Replace(ServiceDescriptor.Transient <IApplicationBuilderFactory, DefaultApplicationBuilderFactory>());
                LoggerSettings.Format           = logOptions.Format;
                LoggerFactory.ServiceCollection = services;
                bool flag2 = string.IsNullOrEmpty(logOptions.LogDirectory);
                if (flag2)
                {
                    logOptions.LogDirectory = ".Logs";
                }
                services.AddHttpContextAccessor();
                services.AddSingleton <ILogAdapter, FileLogAdapter>();
                Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
                Console.OutputEncoding = Encoding.UTF8;
                ServiceDescriptor serviceDescriptor = services.FirstOrDefault((ServiceDescriptor x) => x.ServiceType == typeof(IConfiguration));
                IConfiguration    _config           = ((serviceDescriptor != null) ? serviceDescriptor.ImplementationInstance : null) as IConfiguration;
                bool flag3 = _config == null;
                if (flag3)
                {
                    _config = FileConfigurationExtensions.SetBasePath(EnvironmentVariablesExtensions.AddEnvironmentVariables(new ConfigurationBuilder(), "ASPNETCORE_"), AppContext.BaseDirectory).Build();
                    _config[WebHostDefaults.ContentRootKey] = AppContext.BaseDirectory;
                    services.AddSingleton(_config);
                }
                bool flag4 = string.IsNullOrEmpty(_config[WebHostDefaults.ContentRootKey]);
                if (flag4)
                {
                    _config[WebHostDefaults.ContentRootKey] = AppContext.BaseDirectory;
                }
                ServiceDescriptor   serviceDescriptor2 = services.FirstOrDefault((ServiceDescriptor x) => x.ServiceType == typeof(IHostingEnvironment));
                IHostingEnvironment environment        = (IHostingEnvironment)((serviceDescriptor2 != null) ? serviceDescriptor2.ImplementationInstance : null);
                bool flag5 = environment == null;
                if (flag5)
                {
                    WebHostOptions options = new WebHostOptions(_config, Assembly.GetEntryAssembly().GetName().Name);
                    environment = new HostingEnvironment();
                    HostingEnvironmentExtensions.Initialize(environment, AppContext.BaseDirectory, options);
                    services.TryAddSingleton(environment);
                }
                bool flag6 = string.IsNullOrEmpty(environment.WebRootPath);
                if (flag6)
                {
                    string _contentPath = _config[WebHostDefaults.ContentRootKey];
                    int    binIndex     = _contentPath.LastIndexOf("\\bin\\");
                    bool   flag7        = binIndex > -1;
                    if (flag7)
                    {
                        string contentPath = _contentPath.Substring(0, binIndex);
                        bool   flag8       = contentPath.IndexOf(environment.ApplicationName) > -1;
                        if (flag8)
                        {
                            _config[WebHostDefaults.ContentRootKey] = contentPath;
                            environment.ContentRootPath             = contentPath;
                            environment.WebRootPath = Path.Combine(contentPath, "wwwroot");
                        }
                        else
                        {
                            environment.WebRootPath = _contentPath;
                        }
                    }
                    else
                    {
                        environment.WebRootPath = Path.Combine(_config["ContentRoot"], "wwwroot");
                    }
                }
                bool flag9 = Path.IsPathRooted(logOptions.LogDirectory);
                if (flag9)
                {
                    LoggerSettings.LogDirectory = logOptions.LogDirectory;
                }
                else
                {
                    LoggerSettings.LogDirectory = Path.Combine(_config["ContentRoot"], logOptions.LogDirectory);
                }
                bool flag10 = !Directory.Exists(LoggerSettings.LogDirectory);
                if (flag10)
                {
                    Directory.CreateDirectory(LoggerSettings.LogDirectory);
                }
                string path   = Path.Combine(LoggerSettings.LogDirectory, "_logging.json");
                bool   flag11 = !File.Exists(path);
                if (flag11)
                {
                    File.AppendAllText(path, "{\"Rules\":[{\"CategoryName\":\"Default\",\"LogLevel\":\"Information\",\"LogType\":\"All\",\"TraceCount\":5}]}");
                }
                ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
                JsonConfigurationExtensions.AddJsonFile(FileConfigurationExtensions.SetBasePath(configurationBuilder, environment.ContentRootPath), path, true, true);
                IConfigurationRoot configuration = configurationBuilder.Build();
                services.RemoveAll <ILoggerProviderConfigurationFactory>();
                services.RemoveAll(typeof(ILoggerProviderConfiguration <>));
                TypeInfo type = typeof(ILoggerProviderConfigurationFactory).Assembly.DefinedTypes.SingleOrDefault((TypeInfo t) => t.Name == "LoggingConfiguration");
                services.RemoveAll(type);

                LoggingServiceCollectionExtensions.AddLogging(services, delegate(ILoggingBuilder x)
                {
                    x.AddConfiguration(configuration);
                    //bool flag13 = !x.Services.Any((ServiceDescriptor t) => t.ServiceType == typeof(ILoggerProvider));
                    //if (flag13)
                    //{
                    //    ConsoleLoggerExtensions.AddConsole(x);
                    //}
                    x.Services.RemoveAll <IConfigureOptions <LoggerFilterOptions> >();
                    x.Services.AddSingleton(new LoggerFilterConfigureOptions(configuration));
                });
                services.Replace(ServiceDescriptor.Singleton <ILoggerFactory, LoggerFactory>());
                services.Replace(ServiceDescriptor.Singleton <DiagnosticSource>(new DefaultDiagnosticListener()));
                bool flag12 = services.IsHttpRequest();
                if (flag12)
                {
                    MarkdownFileMiddleware.SaveResourceFiles(environment.WebRootPath);
                }
                DefaultApplicationBuilderFactory.OnCreateBuilder(new Action <IApplicationBuilder, object>(LoggerExtensions.UseFileLog), logOptions);
            }
            return(services);
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="services"></param>
        /// <param name="logAction">logAction</param>
        /// <para>e.g. .Logs or wwwroor/logs or C:/wwwroot/logs</para>
        public static IServiceCollection AddFileLog(this IServiceCollection services, Action <LogOptions> logAction = null)
        {
            if (!services.Any(x => x.ImplementationType == typeof(LOG.LoggerFactory)))
            {
                LogOptions logOptions = new LogOptions();
                logAction?.Invoke(logOptions);
                services.Replace(ServiceDescriptor.Transient <IApplicationBuilderFactory, DefaultApplicationBuilderFactory>());
                //LoggerSettings.Format = logOptions.Format;
                LOG.LoggerFactory.ServiceCollection = services;
                if (string.IsNullOrEmpty(logOptions.LogDirectory))
                {
                    logOptions.LogDirectory = ".Logs";
                }
                services.AddHttpContextAccessor();
                Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
                Console.OutputEncoding = System.Text.Encoding.UTF8;
                var _config = services.FirstOrDefault(x => x.ServiceType == typeof(IConfiguration))?.ImplementationInstance as IConfiguration;
                if (_config == null)
                {
                    _config = new ConfigurationBuilder()
                              .AddEnvironmentVariables("ASPNETCORE_")
                              .SetBasePath(AppContext.BaseDirectory)
                              .Build();
                    _config[WebHostDefaults.ContentRootKey] = AppContext.BaseDirectory;
                    services.AddSingleton(_config);
                }
                if (string.IsNullOrEmpty(_config[WebHostDefaults.ContentRootKey]))
                {
                    _config[WebHostDefaults.ContentRootKey] = AppContext.BaseDirectory;
                }

                IHostingEnvironment environment = (IHostingEnvironment)services.FirstOrDefault(x => x.ServiceType == typeof(IHostingEnvironment))
                                                  ?.ImplementationInstance;
                if (environment == null)
                {
                    WebHostOptions options = new WebHostOptions(_config, Assembly.GetEntryAssembly().GetName().Name);
                    environment = new HostingEnvironment();
                    environment.Initialize(AppContext.BaseDirectory, options);
                    services.TryAddSingleton <IHostingEnvironment>(environment);
                }
                if (string.IsNullOrEmpty(environment.WebRootPath))
                {
                    var _contentPath = _config[WebHostDefaults.ContentRootKey];
                    var binIndex     = _contentPath.LastIndexOf("\\bin\\");
                    if (binIndex > -1)
                    {
                        var contentPath = _contentPath.Substring(0, binIndex);
                        if (contentPath.IndexOf(environment.ApplicationName) > -1)
                        {
                            _config[WebHostDefaults.ContentRootKey] = contentPath;
                            environment.ContentRootPath             = contentPath;
                            environment.WebRootPath = System.IO.Path.Combine(contentPath, "wwwroot");
                        }
                        else
                        {
                            environment.WebRootPath = _contentPath;
                        }
                    }
                    else
                    {
                        environment.WebRootPath = System.IO.Path.Combine(_config["ContentRoot"], "wwwroot");
                    }
                }

                if (Path.IsPathRooted(logOptions.LogDirectory))
                {
                    LoggerSettings.LogDirectory = logOptions.LogDirectory;
                }
                else
                {
                    LoggerSettings.LogDirectory = Path.Combine(_config["ContentRoot"], logOptions.LogDirectory);
                }
                if (!Directory.Exists(LoggerSettings.LogDirectory))
                {
                    Directory.CreateDirectory(LoggerSettings.LogDirectory);
                }
                var path = Path.Combine(LoggerSettings.LogDirectory, LoggerSettings.LogJsonFileName);
                if (!File.Exists(path))
                {
                    File.AppendAllText(path, LoggerSettings.LoggingJsonContent);
                }
                if (logOptions.LogAdapters.Count == 0)
                {
                    logOptions.UseText();
                }
                ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
                configurationBuilder
                .SetBasePath(environment.ContentRootPath)
                .AddJsonFile(path, true, true);
                var configuration = configurationBuilder.Build();
                services.RemoveAll <ILoggerProviderConfigurationFactory>();
                services.RemoveAll(typeof(ILoggerProviderConfiguration <>));
                var type = typeof(ILoggerProviderConfigurationFactory).Assembly.DefinedTypes
                           .SingleOrDefault(t => t.Name == "LoggingConfiguration");
                services.RemoveAll(type);

                services.AddLogging(x =>
                {
                    x.AddConfiguration(configuration);
                    if (!x.Services.Any(t => t.ServiceType == typeof(ILoggerProvider)))
                    {
                        x.AddConsole();
                    }
                    x.Services.RemoveAll <IConfigureOptions <Logging.LoggerFilterOptions> >();
                    x.Services.AddSingleton <IConfigureOptions <Logging.LoggerFilterOptions> >(new LOG.LoggerFilterConfigureOptions(configuration));
                });
                services.TryAddEnumerable(logOptions.LogAdapters);
                logOptions.LogAdapters.Clear();
                services.Replace(ServiceDescriptor.Singleton <ILoggerFactory, LOG.LoggerFactory>());
                services.Replace(ServiceDescriptor.Singleton <DiagnosticSource>(new DefaultDiagnosticListener()));
                if (services.IsHttpRequest())
                {
                    MarkdownFileMiddleware.SaveResourceFiles(environment.WebRootPath);
                }
                DefaultApplicationBuilderFactory.OnCreateBuilder(UseFileLog, logOptions);
            }
            return(services);
        }