Exemplo n.º 1
0
 public static SerilogLogger CreateWithDefaultConfiguration(
     Umbraco.Cms.Core.Hosting.IHostingEnvironment hostingEnvironment,
     ILoggingConfiguration loggingConfiguration,
     IConfiguration configuration)
 {
     return(CreateWithDefaultConfiguration(hostingEnvironment, loggingConfiguration, configuration, out _));
 }
Exemplo n.º 2
0
        /*
         * HOW TO REPLACE THE MEDIA UNDERLYING FILESYSTEM
         * ----------------------------------------------
         *
         * Create an implementation of IFileSystem and register it as the underlying filesystem for
         * MediaFileSystem with the following extension on composition.
         *
         * builder.SetMediaFileSystem(factory => FactoryMethodToReturnYourImplementation())
         *
         * WHAT IS SHADOWING
         * -----------------
         *
         * Shadowing is the technology used for Deploy to implement some sort of
         * transaction-management on top of filesystems. The plumbing explained above,
         * compared to creating your own physical filesystem, ensures that your filesystem
         * would participate into such transactions.
         *
         */

        internal static IUmbracoBuilder AddFileSystems(this IUmbracoBuilder builder)
        {
            // register FileSystems, which manages all filesystems
            builder.Services.AddSingleton <FileSystems>();

            // register the scheme for media paths
            builder.Services.AddUnique <IMediaPathScheme, UniqueMediaPathScheme>();

            builder.Services.AddUnique <IViewHelper, ViewHelper>();
            builder.Services.AddUnique <IDefaultViewContentProvider, DefaultViewContentProvider>();

            builder.SetMediaFileSystem(factory =>
            {
                IIOHelper ioHelper = factory.GetRequiredService <IIOHelper>();
                IHostingEnvironment hostingEnvironment = factory.GetRequiredService <IHostingEnvironment>();
                ILogger <PhysicalFileSystem> logger    = factory.GetRequiredService <ILogger <PhysicalFileSystem> >();
                GlobalSettings globalSettings          = factory.GetRequiredService <IOptions <GlobalSettings> >().Value;

                var rootPath = Path.IsPathRooted(globalSettings.UmbracoMediaPhysicalRootPath) ? globalSettings.UmbracoMediaPhysicalRootPath : hostingEnvironment.MapPathWebRoot(globalSettings.UmbracoMediaPhysicalRootPath);
                var rootUrl  = hostingEnvironment.ToAbsolute(globalSettings.UmbracoMediaPath);
                return(new PhysicalFileSystem(ioHelper, hostingEnvironment, logger, rootPath, rootUrl));
            });

            return(builder);
        }
Exemplo n.º 3
0
 public MacroRenderer(
     IProfilingLogger profilingLogger,
     ILogger <MacroRenderer> logger,
     IUmbracoContextAccessor umbracoContextAccessor,
     IOptionsMonitor <ContentSettings> contentSettings,
     ILocalizedTextService textService,
     AppCaches appCaches,
     IMacroService macroService,
     IHostingEnvironment hostingEnvironment,
     ICookieManager cookieManager,
     ISessionManager sessionManager,
     IRequestAccessor requestAccessor,
     PartialViewMacroEngine partialViewMacroEngine,
     IHttpContextAccessor httpContextAccessor)
     : this(
         profilingLogger,
         logger,
         umbracoContextAccessor,
         contentSettings,
         textService,
         appCaches,
         macroService,
         cookieManager,
         sessionManager,
         requestAccessor,
         partialViewMacroEngine,
         httpContextAccessor,
         StaticServiceProvider.Instance.GetRequiredService <IWebHostEnvironment>())
 {
 }
Exemplo n.º 4
0
 public static LoggerConfiguration MinimalConfiguration(
     this LoggerConfiguration logConfig,
     Umbraco.Cms.Core.Hosting.IHostingEnvironment hostingEnvironment,
     ILoggingConfiguration loggingConfiguration,
     IConfiguration configuration)
 {
     return(MinimalConfiguration(logConfig, hostingEnvironment, loggingConfiguration, configuration, out _));
 }
 public static TypeLoader AddTypeLoader(
     this IServiceCollection services,
     Assembly entryAssembly,
     IHostingEnvironment hostingEnvironment,
     ILoggerFactory loggerFactory,
     AppCaches appCaches,
     IConfiguration configuration,
     IProfiler profiler) =>
 services.AddTypeLoader(entryAssembly, loggerFactory, configuration);
Exemplo n.º 6
0
 public IconService(
     IOptionsMonitor <GlobalSettings> globalSettings,
     IHostingEnvironment hostingEnvironment,
     AppCaches appCaches)
     : this(globalSettings,
            hostingEnvironment,
            appCaches,
            StaticServiceProvider.Instance.GetRequiredService <IWebHostEnvironment>())
 {
 }
Exemplo n.º 7
0
        public void Is_Client_Side_Request(string url, bool assert)
        {
            IHostingEnvironment hostingEnvironment = CreateHostingEnvironment();
            var umbracoRequestPaths = new UmbracoRequestPaths(Options.Create(_globalSettings), hostingEnvironment);

            var uri    = new Uri("http://test.com" + url);
            var result = umbracoRequestPaths.IsClientSideRequest(uri.AbsolutePath);

            Assert.AreEqual(assert, result);
        }
Exemplo n.º 8
0
        public void Is_Client_Side_Request_InvalidPath_ReturnFalse()
        {
            IHostingEnvironment hostingEnvironment = CreateHostingEnvironment();
            var umbracoRequestPaths = new UmbracoRequestPaths(Options.Create(_globalSettings), hostingEnvironment);

            // This URL is invalid. Default to false when the extension cannot be determined
            var uri    = new Uri("http://test.com/installing-modules+foobar+\"yipee\"");
            var result = umbracoRequestPaths.IsClientSideRequest(uri.AbsolutePath);

            Assert.AreEqual(false, result);
        }
Exemplo n.º 9
0
        public static SerilogLogger CreateWithDefaultConfiguration(
            Umbraco.Cms.Core.Hosting.IHostingEnvironment hostingEnvironment,
            ILoggingConfiguration loggingConfiguration,
            IConfiguration configuration,
            out UmbracoFileConfiguration umbracoFileConfig)
        {
            var serilogConfig = new LoggerConfiguration()
                                .MinimalConfiguration(hostingEnvironment, loggingConfiguration, configuration, out umbracoFileConfig)
                                .ReadFrom.Configuration(configuration);

            return(new SerilogLogger(serilogConfig));
        }
Exemplo n.º 10
0
    public IconService(
        IOptionsMonitor <GlobalSettings> globalSettings,
        IHostingEnvironment hostingEnvironment,
        AppCaches appCaches,
        IWebHostEnvironment webHostEnvironment)
    {
        _globalSettings     = globalSettings.CurrentValue;
        _hostingEnvironment = hostingEnvironment;
        _webHostEnvironment = webHostEnvironment;
        _cache = appCaches.RuntimeCache;

        globalSettings.OnChange(x => _globalSettings = x);
    }
Exemplo n.º 11
0
        /// <summary>
        /// Called to create the <see cref="TypeLoader"/> to assign to the <see cref="IUmbracoBuilder"/>
        /// </summary>
        /// <param name="services"></param>
        /// <param name="entryAssembly"></param>
        /// <param name="hostingEnvironment"></param>
        /// <param name="loggerFactory"></param>
        /// <param name="appCaches"></param>
        /// <param name="configuration"></param>
        /// <param name="profiler"></param>
        /// <returns></returns>
        /// <remarks>
        /// This should never be called in a web project. It is used internally by Umbraco but could be used in unit tests.
        /// If called in a web project it will have no affect except to create and return a new TypeLoader but this will not
        /// be the instance in DI.
        /// </remarks>
        public static TypeLoader AddTypeLoader(
            this IServiceCollection services,
            Assembly entryAssembly,
            IHostingEnvironment hostingEnvironment,
            ILoggerFactory loggerFactory,
            AppCaches appCaches,
            IConfiguration configuration,
            IProfiler profiler)
        {
            TypeFinderSettings typeFinderSettings = configuration.GetSection(Cms.Core.Constants.Configuration.ConfigTypeFinder).Get <TypeFinderSettings>() ?? new TypeFinderSettings();

            var assemblyProvider = new DefaultUmbracoAssemblyProvider(
                entryAssembly,
                loggerFactory,
                typeFinderSettings.AdditionalEntryAssemblies);

            RuntimeHashPaths runtimeHashPaths = new RuntimeHashPaths().AddAssemblies(assemblyProvider);

            var runtimeHash = new RuntimeHash(
                new ProfilingLogger(
                    loggerFactory.CreateLogger <RuntimeHash>(),
                    profiler),
                runtimeHashPaths);

            var typeFinderConfig = new TypeFinderConfig(Options.Create(typeFinderSettings));

            var typeFinder = new TypeFinder(
                loggerFactory.CreateLogger <TypeFinder>(),
                assemblyProvider,
                typeFinderConfig
                );

            var typeLoader = new TypeLoader(
                typeFinder,
                runtimeHash,
                appCaches.RuntimeCache,
                new DirectoryInfo(hostingEnvironment.LocalTempPath),
                loggerFactory.CreateLogger <TypeLoader>(),
                profiler
                );

            // This will add it ONCE and not again which is what we want since we don't actually want people to call this method
            // in the web project.
            services.TryAddSingleton <ITypeFinder>(typeFinder);
            services.TryAddSingleton <TypeLoader>(typeLoader);

            return(typeLoader);
        }
Exemplo n.º 12
0
        /// <summary>
        /// Outputs a .txt format log at /App_Data/Logs/
        /// </summary>
        /// <param name="logConfig">A Serilog LoggerConfiguration</param>
        /// <param name="loggingConfiguration"></param>
        /// <param name="minimumLevel">The log level you wish the JSON file to collect - default is Verbose (highest)</param>
        /// <param name="retainedFileCount">The number of days to keep log files. Default is set to null which means all logs are kept</param>
        public static LoggerConfiguration OutputDefaultTextFile(
            this LoggerConfiguration logConfig,
            Umbraco.Cms.Core.Hosting.IHostingEnvironment hostingEnvironment,
            LogEventLevel minimumLevel = LogEventLevel.Verbose)
        {
            //Main .txt logfile - in similar format to older Log4Net output
            //Ends with ..txt as Date is inserted before file extension substring
            logConfig.WriteTo.File(Path.Combine(hostingEnvironment.MapPathContentRoot(Cms.Core.Constants.SystemDirectories.LogFiles), $"UmbracoTraceLog.{Environment.MachineName}..txt"),
                                   shared: true,
                                   rollingInterval: RollingInterval.Day,
                                   restrictedToMinimumLevel: minimumLevel,
                                   retainedFileCountLimit: null, //Setting to null means we keep all files - default is 31 days
                                   outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss,fff} [P{ProcessId}/D{AppDomainId}/T{ThreadId}] {Log4NetLevel}  {SourceContext} - {Message:lj}{NewLine}{Exception}");

            return(logConfig);
        }
Exemplo n.º 13
0
        /// <summary>
        /// Outputs a CLEF format JSON log at /App_Data/Logs/
        /// </summary>
        /// <param name="logConfig">A Serilog LoggerConfiguration</param>
        /// <param name="loggingConfiguration">The logging configuration</param>
        /// <param name="minimumLevel">The log level you wish the JSON file to collect - default is Verbose (highest)</param>
        /// <param name="retainedFileCount">The number of days to keep log files. Default is set to null which means all logs are kept</param>
        public static LoggerConfiguration OutputDefaultJsonFile(
            this LoggerConfiguration logConfig,
            Umbraco.Cms.Core.Hosting.IHostingEnvironment hostingEnvironment,
            ILoggingConfiguration loggingConfiguration, LogEventLevel minimumLevel = LogEventLevel.Verbose, int?retainedFileCount = null)
        {
            // .clef format (Compact log event format, that can be imported into local SEQ & will make searching/filtering logs easier)
            // Ends with ..txt as Date is inserted before file extension substring
            logConfig.WriteTo.File(new CompactJsonFormatter(),
                                   Path.Combine(hostingEnvironment.MapPathContentRoot(Cms.Core.Constants.SystemDirectories.LogFiles), $"UmbracoTraceLog.{Environment.MachineName}..json"),
                                   shared: true,
                                   rollingInterval: RollingInterval.Day,      // Create a new JSON file every day
                                   retainedFileCountLimit: retainedFileCount, // Setting to null means we keep all files - default is 31 days
                                   restrictedToMinimumLevel: minimumLevel);

            return(logConfig);
        }
        /// <summary>
        /// Registers the default required middleware to run Umbraco.
        /// </summary>
        public void RegisterDefaultRequiredMiddleware()
        {
            UseUmbracoCoreMiddleware();

            AppBuilder.UseStatusCodePages();

            // Important we handle image manipulations before the static files, otherwise the querystring is just ignored.
            AppBuilder.UseImageSharp();

            // Get media file provider and request path/URL
            var mediaFileManager = AppBuilder.ApplicationServices.GetRequiredService <MediaFileManager>();

            if (mediaFileManager.FileSystem.TryCreateFileProvider(out IFileProvider mediaFileProvider))
            {
                GlobalSettings      globalSettings     = AppBuilder.ApplicationServices.GetRequiredService <IOptions <GlobalSettings> >().Value;
                IHostingEnvironment hostingEnvironment = AppBuilder.ApplicationServices.GetService <IHostingEnvironment>();
                string mediaRequestPath = hostingEnvironment.ToAbsolute(globalSettings.UmbracoMediaPath);

                // Configure custom file provider for media
                IWebHostEnvironment webHostEnvironment = AppBuilder.ApplicationServices.GetService <IWebHostEnvironment>();
                webHostEnvironment.WebRootFileProvider = webHostEnvironment.WebRootFileProvider.ConcatComposite(new PrependBasePathFileProvider(mediaRequestPath, mediaFileProvider));
            }

            AppBuilder.UseStaticFiles();

            AppBuilder.UseUmbracoPluginsStaticFiles();

            // UseRouting adds endpoint routing middleware, this means that middlewares registered after this one
            // will execute after endpoint routing. The ordering of everything is quite important here, see
            // https://docs.microsoft.com/en-us/aspnet/core/fundamentals/routing?view=aspnetcore-5.0
            // where we need to have UseAuthentication and UseAuthorization proceeding this call but before
            // endpoints are defined.
            AppBuilder.UseRouting();
            AppBuilder.UseAuthentication();
            AppBuilder.UseAuthorization();

            // This must come after auth because the culture is based on the auth'd user
            AppBuilder.UseRequestLocalization();

            // Must be called after UseRouting and before UseEndpoints
            AppBuilder.UseSession();

            // DO NOT PUT ANY UseEndpoints declarations here!! Those must all come very last in the pipeline,
            // endpoints are terminating middleware. All of our endpoints are declared in ext of IUmbracoApplicationBuilder
        }
Exemplo n.º 15
0
        public static LoggerConfiguration MinimalConfiguration(
            this LoggerConfiguration logConfig,
            Umbraco.Cms.Core.Hosting.IHostingEnvironment hostingEnvironment,
            ILoggingConfiguration loggingConfiguration,
            IConfiguration configuration,
            out UmbracoFileConfiguration umbFileConfiguration)
        {
            global::Serilog.Debugging.SelfLog.Enable(msg => System.Diagnostics.Debug.WriteLine(msg));

            //Set this environment variable - so that it can be used in external config file
            //add key="serilog:write-to:RollingFile.pathFormat" value="%BASEDIR%\logs\log.txt" />
            Environment.SetEnvironmentVariable("BASEDIR", hostingEnvironment.MapPathContentRoot("/").TrimEnd(Path.DirectorySeparatorChar), EnvironmentVariableTarget.Process);
            Environment.SetEnvironmentVariable("UMBLOGDIR", loggingConfiguration.LogDirectory, EnvironmentVariableTarget.Process);
            Environment.SetEnvironmentVariable("MACHINENAME", Environment.MachineName, EnvironmentVariableTarget.Process);

            logConfig.MinimumLevel.Verbose() //Set to highest level of logging (as any sinks may want to restrict it to Errors only)
            .Enrich.WithProcessId()
            .Enrich.WithProcessName()
            .Enrich.WithThreadId()
            .Enrich.WithProperty("ApplicationId", hostingEnvironment.ApplicationId)     // Updated later by ApplicationIdEnricher
            .Enrich.WithProperty("MachineName", Environment.MachineName)
            .Enrich.With <Log4NetLevelMapperEnricher>()
            .Enrich.FromLogContext();     // allows us to dynamically enrich

            //This is not optimal, but seems to be the only way if we do not make an Serilog.Sink.UmbracoFile sink all the way.
            var umbracoFileConfiguration = new UmbracoFileConfiguration(configuration);

            umbFileConfiguration = umbracoFileConfiguration;

            logConfig.WriteTo.UmbracoFile(
                path: umbracoFileConfiguration.GetPath(loggingConfiguration.LogDirectory),
                fileSizeLimitBytes: umbracoFileConfiguration.FileSizeLimitBytes,
                restrictedToMinimumLevel: umbracoFileConfiguration.RestrictedToMinimumLevel,
                rollingInterval: umbracoFileConfiguration.RollingInterval,
                flushToDiskInterval: umbracoFileConfiguration.FlushToDiskInterval,
                rollOnFileSizeLimit: umbracoFileConfiguration.RollOnFileSizeLimit,
                retainedFileCountLimit: umbracoFileConfiguration.RetainedFileCountLimit
                );

            return(logConfig);
        }
Exemplo n.º 16
0
        /// <summary>
        /// Create and configure the logger
        /// </summary>
        public static IServiceCollection AddLogger(
            this IServiceCollection services,
            IHostingEnvironment hostingEnvironment,
            ILoggingConfiguration loggingConfiguration,
            IConfiguration configuration)
        {
            // Create a serilog logger
            var logger = SerilogLogger.CreateWithDefaultConfiguration(hostingEnvironment, loggingConfiguration, configuration, out var umbracoFileConfig);

            services.AddSingleton(umbracoFileConfig);

            // This is nessasary to pick up all the loggins to MS ILogger.
            Log.Logger = logger.SerilogLog;

            // Wire up all the bits that serilog needs. We need to use our own code since the Serilog ext methods don't cater to our needs since
            // we don't want to use the global serilog `Log` object and we don't have our own ILogger implementation before the HostBuilder runs which
            // is the only other option that these ext methods allow.
            // I have created a PR to make this nicer https://github.com/serilog/serilog-extensions-hosting/pull/19 but we'll need to wait for that.
            // Also see : https://github.com/serilog/serilog-extensions-hosting/blob/dev/src/Serilog.Extensions.Hosting/SerilogHostBuilderExtensions.cs

            services.AddLogging(configure =>
            {
                configure.AddSerilog(logger.SerilogLog, false);
            });

            // This won't (and shouldn't) take ownership of the logger.
            services.AddSingleton(logger.SerilogLog);

            // Registered to provide two services...
            var diagnosticContext = new DiagnosticContext(logger.SerilogLog);

            // Consumed by e.g. middleware
            services.AddSingleton(diagnosticContext);

            // Consumed by user code
            services.AddSingleton <IDiagnosticContext>(diagnosticContext);
            services.AddSingleton(loggingConfiguration);

            return(services);
        }
Exemplo n.º 17
0
 public BootFailedMiddleware(IRuntimeState runtimeState, IHostingEnvironment hostingEnvironment, IWebHostEnvironment webHostEnvironment)
 {
     _runtimeState       = runtimeState;
     _hostingEnvironment = hostingEnvironment;
     _webHostEnvironment = webHostEnvironment;
 }
Exemplo n.º 18
0
 public BootFailedMiddleware(IRuntimeState runtimeState, IHostingEnvironment hostingEnvironment)
     : this(runtimeState, hostingEnvironment, StaticServiceProvider.Instance.GetRequiredService <IWebHostEnvironment>())
 {
     _runtimeState       = runtimeState;
     _hostingEnvironment = hostingEnvironment;
 }