В Linux CentOS 8 при использовании. NET core 3 / 3.1 не отображаются журналы. - PullRequest
1 голос
/ 01 марта 2020

Я хотел бы дать сообщения об ошибках, но это все, что я получаю ...

Я что-то упустил? Что-то изменилось для Linux развертываний в. NET ядро ​​3.1 против 2.1 / 2.2?

enter image description here

Я попытался выйти из системы, как только возможно ...

Program.cs

public class Program
    {
        public static void Main(string[] args)
        {
            bool dev = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") == "Development";
            var logPath = dev ? "/Logs/gweb_log.txt" : "/var/log/gweb/gweb.log";

            Log.Logger = new LoggerConfiguration()
                .MinimumLevel.Debug()
                //.MinimumLevel.Override("Microsoft", LogEventLevel.Information)
                .Enrich.FromLogContext()
                //.WriteTo.AzureApp()
                .WriteTo.File(logPath, rollingInterval: RollingInterval.Day, fileSizeLimitBytes: 10485760, rollOnFileSizeLimit: true, retainedFileCountLimit: 3)
                .CreateLogger();

            try
            {
                Log.Information($"Garos_Web Started Utc: {DateTime.UtcNow}!");
                CreateHostBuilder(args).Build().Run();
            }

            catch (Exception e)
            {
                Log.Error($"Something went wrong. UTC: {DateTime.UtcNow}");
                Log.Error(e.Message);
                if (e.InnerException != null && !string.IsNullOrEmpty(e.InnerException.Message))
                {
                    Log.Error(e.InnerException.Message);
                }

                Log.Error(e.StackTrace);
            }
            finally
            {
                Log.CloseAndFlush();
            }

        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseSerilog()
                    .UseStartup<Startup>()
                    .UseKestrel(options =>
                    {
                        options.Listen(System.Net.IPAddress.Loopback, 5000);
                    });
                }
            );
    }

Удостоверьтесь, что добавление сертификата подписи было новым, но я полагаю, хорошее требование от платформы ...

Запуск Файл .cs

public class Startup
    {
        public Startup(IConfiguration configuration, IWebHostEnvironment webHostEnvironment)
        {
            Configuration = configuration;
            WebHostEnvironment = webHostEnvironment;
        }

        public IConfiguration Configuration { get; }
        public IWebHostEnvironment WebHostEnvironment { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            Configuration.GetSection("AppSettings").Bind(AppSettings.Default);

            services.AddDbContext<GarosWebDbContext>(options =>
                options.UseMySql(AppSettings.Default.ConnectionStrings.DefaultConnection));

            services.AddDefaultIdentity<GarosUser>(options => options.SignIn.RequireConfirmedAccount = true)
                .AddEntityFrameworkStores<GarosWebDbContext>();


            var certPath = Path.Combine(WebHostEnvironment.ContentRootPath, "garos_web_identity_server.pfx");
            var cert = new X509Certificate2(certPath, AppSettings.Default.IdentitySigningKey);

            services.AddIdentityServer()              
            .AddApiAuthorization<GarosUser, GarosWebDbContext>()
            .AddSigningCredential(cert);


            services.AddAuthentication()
                .AddIdentityServerJwt();

            services.AddControllersWithViews();

            services.AddRazorPages();

            // In production, the React files will be served from this directory
            services.AddSpaStaticFiles(configuration =>
            {
                configuration.RootPath = "ClientApp/build";
            });

        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseDatabaseErrorPage();
            }
            else
            {
                app.UseExceptionHandler("/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            //app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseSpaStaticFiles();

            app.UseRouting();

            app.UseAuthentication();
            app.UseIdentityServer();
            app.UseAuthorization();


#if !DEBUG //Stop Registering users when in production (this is because we are using identity out of the box and don't want to allow more users at this time)
            app.UseAuthorization().Use((async (context, next) => {


                if (context.Request.RouteValues.Values.Contains("/Account/Register"))
                {
                    Debug.WriteLine("Inside");
                    context.Response.StatusCode = 404;                              
                }

                else
                {
                    await next();
                }
            }));
#endif
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller}/{action=Index}/{id?}");
                endpoints.MapRazorPages();                
            });

            app.UseSpa(spa =>
            {
                spa.Options.SourcePath = "ClientApp";

                if (env.IsDevelopment())
                {
                    spa.UseReactDevelopmentServer(npmScript: "start");
                }
            });
        }
    }

/ etc / systemd / system / kestrel-webapplication.service на сервере

[Unit]
Description=GAROS_WEB .NET Web Application running on CentOS 8

[Service]
WorkingDirectory=/website_production/PublishOutput
ExecStart=/usr/share/dotnet/dotnet /website_production/PublishOutput/garos_web.dll
Restart=always
# restart service after 10 seconds if dotnet service crashes
RestartSec=10
SyslogIdentifier=garos_web_webapp
User=garos_web
Environment=ASPNETCORE_ENVIRONMENT=Production
Environment=DOTNET_PRINT_TELEMETRY_MESSAGE=false

[Install]
WantedBy=multi-user.target

1 Ответ

2 голосов
/ 01 марта 2020

Как насчет добавления .WriteTo.Console() к этой настройке Serilog? Вам также необходимо иметь этот пакет в соответствующем файле csproj: https://www.nuget.org/packages/serilog.sinks.console/

...