Skip to content

Commit

Permalink
CM-167 : How to write logs from within Startup.cs/Program.cs (CodeMaz…
Browse files Browse the repository at this point in the history
…eBlog#983)

* CM-167 : How do I write logs from within Startup.cs/Program.cs?

* moved namespaces to global using

* removing the extra line

* removing unused directives, formatting correction
  • Loading branch information
muhammedsalimp authored Apr 3, 2023
1 parent 32fb581 commit 4f2f911
Show file tree
Hide file tree
Showing 18 changed files with 426 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>net7.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="7.0.3" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.4.0" />
</ItemGroup>

</Project>
35 changes: 35 additions & 0 deletions dotnet-logging/LoggingFromStartup/LoggingFromProgram/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

app.Logger.LogInformation("This is an informational log from Program.cs");

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}

app.MapGet("/TestLog", async context =>
{
app.Logger.LogInformation("Testing logging from Minimal API endpoint in Program.cs");
await context.Response.WriteAsync("Testing");
});

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.Run();

public partial class Program { }
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
{
"$schema": "https://json.schemastore.org/launchsettings.json",
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:36487",
"sslPort": 44332
}
},
"profiles": {
"http": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"launchUrl": "swagger",
"applicationUrl": "http://localhost:5117",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"https": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"launchUrl": "swagger",
"applicationUrl": "https://localhost:7211;http://localhost:5117",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"launchUrl": "swagger",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
}
37 changes: 37 additions & 0 deletions dotnet-logging/LoggingFromStartup/LoggingFromStartup.sln
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.5.33424.131
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "LoggingFromProgram", "LoggingFromProgram\LoggingFromProgram.csproj", "{92B84893-9295-4534-ABCA-1AE84326FAD2}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LoggingFromStartup", "LoggingFromStartup\LoggingFromStartup.csproj", "{C2E317F3-661C-40CD-A409-2256C8D55BDE}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Tests", "Tests\Tests.csproj", "{A9833E08-E38A-4B48-AD78-506D61320DF3}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{92B84893-9295-4534-ABCA-1AE84326FAD2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{92B84893-9295-4534-ABCA-1AE84326FAD2}.Debug|Any CPU.Build.0 = Debug|Any CPU
{92B84893-9295-4534-ABCA-1AE84326FAD2}.Release|Any CPU.ActiveCfg = Release|Any CPU
{92B84893-9295-4534-ABCA-1AE84326FAD2}.Release|Any CPU.Build.0 = Release|Any CPU
{C2E317F3-661C-40CD-A409-2256C8D55BDE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{C2E317F3-661C-40CD-A409-2256C8D55BDE}.Debug|Any CPU.Build.0 = Debug|Any CPU
{C2E317F3-661C-40CD-A409-2256C8D55BDE}.Release|Any CPU.ActiveCfg = Release|Any CPU
{C2E317F3-661C-40CD-A409-2256C8D55BDE}.Release|Any CPU.Build.0 = Release|Any CPU
{A9833E08-E38A-4B48-AD78-506D61320DF3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{A9833E08-E38A-4B48-AD78-506D61320DF3}.Debug|Any CPU.Build.0 = Debug|Any CPU
{A9833E08-E38A-4B48-AD78-506D61320DF3}.Release|Any CPU.ActiveCfg = Release|Any CPU
{A9833E08-E38A-4B48-AD78-506D61320DF3}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {9D4DA780-EC7F-4FB6-B24E-DC27AAF19B50}
EndGlobalSection
EndGlobal
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;

namespace LoggingFromStartup.Controllers
{
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
private static readonly string[] Summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};

private readonly ILogger<WeatherForecastController> _logger;

public WeatherForecastController(ILogger<WeatherForecastController> logger)
{
_logger = logger;
}

[HttpGet]
public IEnumerable<WeatherForecast> Get()
{
var rng = new Random();
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateTime.Now.AddDays(index),
TemperatureC = rng.Next(-20, 55),
Summary = Summaries[rng.Next(Summaries.Length)]
})
.ToArray();
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>net5.0</TargetFramework>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Swashbuckle.AspNetCore" Version="5.6.3" />
</ItemGroup>

</Project>
27 changes: 27 additions & 0 deletions dotnet-logging/LoggingFromStartup/LoggingFromStartup/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

namespace LoggingFromStartup
{
public class Program
{
public static void Main(string[] args)
{
var host = CreateHostBuilder(args).Build();

var logger = host.Services.GetRequiredService<ILogger<Program>>();
logger.LogInformation("This is an informational log from Main()");

host.Run();
}

public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
{
"$schema": "http://json.schemastore.org/launchsettings.json",
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:8385",
"sslPort": 44330
}
},
"profiles": {
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"launchUrl": "swagger",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"LoggingFromStartup": {
"commandName": "Project",
"dotnetRunMessages": "true",
"launchBrowser": true,
"launchUrl": "swagger",
"applicationUrl": "https://localhost:5001;http://localhost:5000",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
56 changes: 56 additions & 0 deletions dotnet-logging/LoggingFromStartup/LoggingFromStartup/Startup.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.OpenApi.Models;

namespace LoggingFromStartup
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}

public IConfiguration Configuration { get; }

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "LoggingFromStartup", Version = "v1" });
});
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app,
IWebHostEnvironment env,
ILogger<Startup> logger)
{
logger.LogInformation("This is an informational log from Startup.cs");

if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "LoggingFromStartup v1"));
}

app.UseHttpsRedirection();

app.UseRouting();

app.UseAuthorization();

app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
using System;

namespace LoggingFromStartup
{
public class WeatherForecast
{
public DateTime Date { get; set; }

public int TemperatureC { get; set; }

public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);

public string Summary { get; set; }
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*"
}
26 changes: 26 additions & 0 deletions dotnet-logging/LoggingFromStartup/Tests/LoggingFromProgramTest.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
namespace Tests
{
public class LoggingFromProgramTest : IClassFixture<WebApplicationFactory<Program>>
{

private readonly WebApplicationFactory<Program> _factory;

public LoggingFromProgramTest(WebApplicationFactory<Program> factory)
{
_factory = factory;
}

[Fact]
public async Task WhenGettingTestLog_ThenReturnSuccess()
{
// arrange
var client = _factory.CreateClient();

// act
var response = await client.GetAsync("TestLog");

//assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
}
}
Loading

0 comments on commit 4f2f911

Please sign in to comment.