首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >登录AspNetCore主机/重定向控制台输出

登录AspNetCore主机/重定向控制台输出
EN

Stack Overflow用户
提问于 2018-07-04 08:02:59
回答 1查看 1.7K关注 0票数 2

我最近刚在我们的软件中添加了一个AspNetCore项目,它不过是一个小型的MVC站点。为了主持这个项目,我使用Microsoft.AspNetCore.HostingTopshelf的功能在windows服务中运行宿主。

问题是,一旦宿主进程在windows服务中运行,我就无法从它获得任何调试信息。通常,所有信息都会写入控制台,而且由于我在软件中使用了自己的跟踪/日志记录,所以如果可能的话,我希望继续使用它,或者至少告诉宿主进程将所有信息转发到跟踪的方法调用中,以避免遗漏任何信息,并在将来实现像NLog这样的常见记录器。

这是主机的代码

代码语言:javascript
复制
public class Program
{
    public static void Main(string[] args)
    {
        // Name of the executable
        var nameOfExe = Process.GetCurrentProcess().MainModule.FileName;

        // Path of the current executable
        var pathToContentRoot = Path.GetDirectoryName(nameOfExe);

        // Path of the www root for the static files
        var pathToWebRoot = pathToContentRoot + @"\wwwroot";

        IWebHost host = WebHost.CreateDefaultBuilder()
        .UseKestrel()
        .UseContentRoot(pathToContentRoot)
        .UseIISIntegration()
        .UseWebRoot(pathToWebRoot)
        .UseStartup<Startup>()
        .UseApplicationInsights()
        .Build();

        host.RunAsCustomService();
    }
}


public static class WebHostServiceExtensions
{
    public static void RunAsCustomService(this IWebHost host)
    {
        var webHostService = new Service(host);
        ServiceBase.Run(webHostService);
    }
}


public class Startup
{
    public Startup(IHostingEnvironment env)
    {
        if(env.IsDevelopment())
        {
            env.ContentRootPath = env.ContentRootPath.Replace("Bin", @"Main");
            env.ContentRootFileProvider = new PhysicalFileProvider(env.ContentRootPath);
            env.WebRootPath = env.WebRootPath.Replace("Bin", @"Main");
            env.WebRootFileProvider = new PhysicalFileProvider(env.WebRootPath);
        }

        var builder = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
            .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
            .AddEnvironmentVariables();
        Configuration = builder.Build();
    }

    public IConfigurationRoot Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddSession(options => {
            options.IdleTimeout = TimeSpan.FromMinutes(500); });
        // Add framework services.
        services
            .AddLocalization(options => options.ResourcesPath = "Resources")

            .AddMvc().ConfigureApplicationPartManager(manager =>
            {
                var oldMetadataReferenceFeatureProvider = manager.FeatureProviders.First(f => f is MetadataReferenceFeatureProvider);
                manager.FeatureProviders.Remove(oldMetadataReferenceFeatureProvider);
                manager.FeatureProviders.Add(new ReferencesMetadataReferenceFeatureProvider());
            })
            .AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix)
            .AddDataAnnotationsLocalization();

        services.AddSingleton<FFDModel>();
        services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

        services.Configure<WebSettings>(Configuration.GetSection("ValidationFilters"));
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        app.UseSession();

        loggerFactory.AddConsole(Configuration.GetSection("Logging"));
        loggerFactory.AddDebug();

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseBrowserLink();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
        }

        app.UseStaticFiles();

        IList<CultureInfo> supportedCultures = new List<CultureInfo>
        {
             new CultureInfo("en-US"),
             new CultureInfo("de-DE"),
            };
        app.UseRequestLocalization(new RequestLocalizationOptions
        {
            DefaultRequestCulture = new RequestCulture("en-US"),
            SupportedCultures = supportedCultures,
            SupportedUICultures = supportedCultures
        });

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=FFD}/{action=Index}/{id?}");
        });
    }
}
EN

回答 1

Stack Overflow用户

发布于 2018-07-04 08:25:02

我将使用Serilog https://serilog.net登录任何.NET应用程序。

可以将Serilog配置为将输出重定向到多个目标,例如控制台、滚动文件。如果您有自定义日志目标/需求,则可以通过编写自定义Sink来转发输出。

使用ASP.Net扩展https://github.com/serilog/serilog-aspnetcore很容易集成到IWebHostBuilder核心应用程序中

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51168673

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档