Asp.net mvc 登录AspNetCore托管/重定向控制台输出
我最近刚刚在我们的软件中添加了一个AspNetCore项目,它只不过是一个小型MVC站点。为了主持这个项目,我使用了Asp.net mvc 登录AspNetCore托管/重定向控制台输出,asp.net-mvc,asp.net-core,self-hosting,Asp.net Mvc,Asp.net Core,Self Hosting,我最近刚刚在我们的软件中添加了一个AspNetCore项目,它只不过是一个小型MVC站点。为了主持这个项目,我使用了Microsoft.AspNetCore.Hosting和Topshelf的功能在windows服务中运行托管 问题是,一旦托管进程在windows服务中运行,我就无法从中获取任何调试信息。通常所有信息都会写入控制台,由于我在我们的软件中使用自己的跟踪/日志,如果可能的话,我希望继续使用它,或者至少告诉宿主进程将所有信息简单地转发给跟踪的方法调用,以防遗漏任何信息,并在未来 以下是
Microsoft.AspNetCore.Hosting
和Topshelf
的功能在windows服务中运行托管
问题是,一旦托管进程在windows服务中运行,我就无法从中获取任何调试信息。通常所有信息都会写入控制台,由于我在我们的软件中使用自己的跟踪/日志,如果可能的话,我希望继续使用它,或者至少告诉宿主进程将所有信息简单地转发给跟踪的方法调用,以防遗漏任何信息,并在未来
以下是主机的代码
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?}");
});
}
}
公共类程序
{
公共静态void Main(字符串[]args)
{
//可执行文件的名称
var nameofex=Process.GetCurrentProcess().MainModule.FileName;
//当前可执行文件的路径
var pathToContentRoot=Path.GetDirectoryName(nameofex);
//静态文件的www根目录的路径
var pathToWebRoot=pathToContentRoot+@“\wwwroot”;
IWebHost主机=WebHost.CreateDefaultBuilder()
.UseKestrel()
.UseContentRoot(pathToContentRoot)
.Useii整合()
.UseWebRoot(PathTowerBoot)
.UseStartup()
.UseApplicationInsights()
.Build();
host.RunAsCustomService();
}
}
公共静态类WebHostServiceExtensions
{
公共静态无效RunAsCustomService(此IWebHost主机)
{
var webHostService=新服务(主机);
运行(webHostService);
}
}
公营创业
{
公共启动(IHostingEnvironment环境)
{
if(env.IsDevelopment())
{
env.ContentRootPath=env.ContentRootPath.Replace(“Bin”,@“Main”);
env.ContentRootFileProvider=新的物理文件提供程序(env.ContentRootPath);
env.WebRootPath=env.WebRootPath.Replace(“Bin”,@“Main”);
env.WebRootFileProvider=新的物理文件提供程序(env.WebRootPath);
}
var builder=new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile(“appsettings.json”,可选:false,reloadOnChange:true)
.AddJsonFile($“appsettings.{env.EnvironmentName}.json”,可选:true)
.AddenEnvironmentVariables();
Configuration=builder.Build();
}
公共IConfigurationRoot配置{get;}
//此方法由运行时调用。请使用此方法将服务添加到容器中。
public void配置服务(IServiceCollection服务)
{
services.AddSession(选项=>{
options.IdleTimeout=TimeSpan.FromMinutes(500);});
//添加框架服务。
服务
.AddLocalization(options=>options.ResourcesPath=“Resources”)
.AddMvc().ConfigureApplicationPartManager(管理器=>
{
var oldMetadataReferenceFeatureProvider=manager.FeatureProviders.First(f=>f是MetadataReferenceFeatureProvider);
manager.FeatureProviders.Remove(oldMetadataReferenceFeatureProvider);
添加(新引用MetadataReferenceFeatureProvider());
})
.AddViewLocalization(LanguageViewLocationExpanderFormat.后缀)
.AddDataAnnotationsLocalization();
services.AddSingleton();
services.AddSingleton();
Configure(Configuration.GetSection(“ValidationFilters”);
}
//此方法由运行时调用。请使用此方法配置HTTP请求管道。
公共void配置(IApplicationBuilder应用程序、IHostingEnvironment环境、iLogger工厂)
{
app.UseSession();
loggerFactory.AddConsole(Configuration.GetSection(“Logging”);
loggerFactory.AddDebug();
if(env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseBrowserLink();
}
其他的
{
app.UseExceptionHandler(“/Home/Error”);
}
app.UseStaticFiles();
IList supportedCultures=新列表
{
新文化信息(“美国”),
新文化信息(“de”),
};
app.UseRequestLocalization(新的RequestLocalizationOptions
{
DefaultRequestCulture=新的RequestCulture(“en-US”),
SupportedCultures=SupportedCultures,
支持的教育=支持的文化
});
app.UseMvc(路由=>
{
routes.MapRoute(
名称:“默认”,
模板:“{controller=FFD}/{action=Index}/{id?}”);
});
}
}
我会使用Serilog
登录任何.NET应用程序
Serilog可以配置为将输出重定向到多个目标,例如控制台、滚动文件。如果您有自定义日志记录目的地/要求,则可以通过编写自定义接收器
转发输出
使用IWebHostBuilder
扩展,很容易集成到ASP.Net核心应用程序中
来源
- SerilogASP.Net核心示例
- 提供水槽
- 开发水槽