Skip to content

Commit b2ac4e8

Browse files
committed
Add elmah.io shared blog post code
1 parent 4f21290 commit b2ac4e8

51 files changed

Lines changed: 40261 additions & 0 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
@page
2+
@model ErrorModel
3+
@{
4+
ViewData["Title"] = "Error";
5+
}
6+
7+
<h1 class="text-danger">Error.</h1>
8+
<h2 class="text-danger">An error occurred while processing your request.</h2>
9+
10+
@if (Model.ShowRequestId)
11+
{
12+
<p>
13+
<strong>Request ID:</strong> <code>@Model.RequestId</code>
14+
</p>
15+
}
16+
17+
<h3>Development Mode</h3>
18+
<p>
19+
Swapping to the <strong>Development</strong> environment displays detailed information about the error that occurred.
20+
</p>
21+
<p>
22+
<strong>The Development environment shouldn't be enabled for deployed applications.</strong>
23+
It can result in displaying sensitive information from exceptions to end users.
24+
For local debugging, enable the <strong>Development</strong> environment by setting the <strong>ASPNETCORE_ENVIRONMENT</strong> environment variable to <strong>Development</strong>
25+
and restarting the app.
26+
</p>
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
using System;
2+
using System.Collections.Generic;
3+
using System.Diagnostics;
4+
using System.Linq;
5+
using System.Threading.Tasks;
6+
using Microsoft.AspNetCore.Mvc;
7+
using Microsoft.AspNetCore.Mvc.RazorPages;
8+
using Microsoft.Extensions.Logging;
9+
10+
namespace PostSharp.Samples.Logging.ElmahIo.Pages
11+
{
12+
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
13+
public class ErrorModel : PageModel
14+
{
15+
public string RequestId
16+
{
17+
get;
18+
set;
19+
}
20+
21+
public bool ShowRequestId => !string.IsNullOrEmpty(RequestId);
22+
23+
private readonly ILogger<ErrorModel> _logger;
24+
25+
public ErrorModel(ILogger<ErrorModel> logger)
26+
{
27+
_logger = logger;
28+
}
29+
30+
public void OnGet()
31+
{
32+
RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier;
33+
}
34+
}
35+
}
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
@page
2+
@model IndexModel
3+
@{
4+
ViewData["Title"] = "Home page";
5+
}
6+
7+
<div class="text-center">
8+
<h1 class="display-4">What am I made of?</h1>
9+
<p>
10+
<form method="post">
11+
How much do you weigh, in kilograms:&nbsp;
12+
<input asp-for="NumberOfKgs" />
13+
<input type="submit" value="Tell me about my body" />
14+
<br></br>
15+
<p style="white-space: pre-line">@ViewData.Model.Result</p>
16+
</form>
17+
</p>
18+
</div>
Lines changed: 97 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,97 @@
1+
using System;
2+
using System.Collections.Generic;
3+
using System.Globalization;
4+
using System.Linq;
5+
using System.Numerics;
6+
using System.Threading.Tasks;
7+
using Microsoft.AspNetCore.Localization;
8+
using Microsoft.AspNetCore.Mvc;
9+
using Microsoft.AspNetCore.Mvc.RazorPages;
10+
using Microsoft.Extensions.Logging;
11+
using Serilog;
12+
13+
namespace PostSharp.Samples.Logging.ElmahIo.Pages
14+
{
15+
public class IndexModel : PageModel
16+
{
17+
[BindProperty]
18+
public string Result
19+
{
20+
get;
21+
set;
22+
}
23+
24+
[BindProperty]
25+
public string NumberOfKgs
26+
{
27+
get;
28+
set;
29+
}
30+
31+
public void OnPost()
32+
{
33+
this.WriteInterestingFacts();
34+
}
35+
36+
public void OnGet()
37+
{
38+
39+
this.WriteInterestingFacts();
40+
}
41+
42+
private void WriteInterestingFacts()
43+
{
44+
try
45+
{
46+
float kgs = this.GetKilograms(this.NumberOfKgs);
47+
this.Result =
48+
"You weigh " + kgs + " kilograms.\n" +
49+
"You would sell for " + WorthInGold(kgs) + " if you were made of gold.\n" +
50+
"You would explode as " + Explosion(kgs) + " atomic bombs if you were turned into pure energy.\n" +
51+
"You would fall for " + EiffelFall(kgs) + " seconds if you fell from the Eiffel Tower.";
52+
}
53+
catch (Exception)
54+
{
55+
this.Result = "I can't tell you anything about your body.";
56+
}
57+
}
58+
59+
private string EiffelFall(in float kgs) // Ha ha, your mass doesn't actually matter ^^
60+
{
61+
int distance = 300; // m
62+
// distance = acceleration * time squared
63+
// time = square root of (distance / acceleration)
64+
float time = MathF.Sqrt((float) distance / 9.81f);
65+
return time.ToString("F2");
66+
}
67+
68+
private string Explosion(in float kgs)
69+
{
70+
// e = m * c * c
71+
BigInteger c = 299792458;
72+
BigInteger cc = c * c;
73+
BigInteger eTimes1000 = (cc) * new BigInteger((int) (kgs * 1000)); // reasonable accuracy
74+
BigInteger e = eTimes1000 / 1000;
75+
BigInteger atomicEnergy = new BigInteger(100) * 1000 * 1000 * 1000 * 1000;
76+
BigInteger bombs = e / atomicEnergy;
77+
return bombs.ToString();
78+
}
79+
80+
private string WorthInGold(in float kgs)
81+
{
82+
float costOfKgOfGold = 61612; // USD as of September 22, 2020
83+
return "$" + (kgs * costOfKgOfGold);
84+
}
85+
86+
private float GetKilograms(string numberOfStars)
87+
{
88+
return float.Parse(numberOfStars, this.GetUserCulture());
89+
}
90+
91+
private CultureInfo GetUserCulture()
92+
{
93+
var locale = this.Request.HttpContext.Features.Get<IRequestCultureFeature>();
94+
return locale.RequestCulture.Culture;
95+
}
96+
}
97+
}
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
<!DOCTYPE html>
2+
<html lang="en">
3+
<head>
4+
<meta charset="utf-8"/>
5+
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
6+
<title>@ViewData["Title"] - PostSharp.Samples.Logging.ElmahIo</title>
7+
<link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css"/>
8+
<link rel="stylesheet" href="~/css/site.css"/>
9+
</head>
10+
<body>
11+
<header>
12+
<nav class="navbar navbar-expand-sm navbar-toggleable-sm navbar-light bg-white border-bottom box-shadow mb-3">
13+
<div class="container">
14+
<a class="navbar-brand" asp-area="" asp-page="/Index">PostSharp.Samples.Logging.ElmahIo</a>
15+
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target=".navbar-collapse" aria-controls="navbarSupportedContent"
16+
aria-expanded="false" aria-label="Toggle navigation">
17+
<span class="navbar-toggler-icon"></span>
18+
</button>
19+
<div class="navbar-collapse collapse d-sm-inline-flex flex-sm-row-reverse">
20+
<ul class="navbar-nav flex-grow-1">
21+
<li class="nav-item">
22+
<a class="nav-link text-dark" asp-area="" asp-page="/Index">Home</a>
23+
</li>
24+
</ul>
25+
</div>
26+
</div>
27+
</nav>
28+
</header>
29+
<div class="container">
30+
<main role="main" class="pb-3">
31+
@RenderBody()
32+
</main>
33+
</div>
34+
35+
<footer class="border-top footer text-muted">
36+
<div class="container">
37+
&copy; 2020 - PostSharp.Samples.Logging.ElmahIo
38+
</div>
39+
</footer>
40+
41+
<script src="~/lib/jquery/dist/jquery.min.js"></script>
42+
<script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
43+
<script src="~/js/site.js" asp-append-version="true"></script>
44+
45+
@RenderSection("Scripts", required: false)
46+
</body>
47+
</html>
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
<script src="~/lib/jquery-validation/dist/jquery.validate.min.js"></script>
2+
<script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.min.js"></script>
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
@using PostSharp.Samples.Logging.ElmahIo
2+
@namespace PostSharp.Samples.Logging.ElmahIo.Pages
3+
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
@{
2+
Layout = "_Layout";
3+
}
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
<Project Sdk="Microsoft.NET.Sdk.Web">
2+
3+
<PropertyGroup>
4+
<TargetFramework>netcoreapp3.1</TargetFramework>
5+
</PropertyGroup>
6+
7+
<ItemGroup>
8+
<PackageReference Include="Elmah.Io.AspNetCore.Serilog">
9+
<Version>3.0.3</Version>
10+
</PackageReference>
11+
<PackageReference Include="PostSharp.Patterns.Diagnostics">
12+
<Version>6.6.14</Version>
13+
</PackageReference>
14+
<PackageReference Include="PostSharp.Patterns.Diagnostics.Serilog">
15+
<Version>6.6.14</Version>
16+
</PackageReference>
17+
<PackageReference Include="Serilog.Sinks.ColoredConsole">
18+
<Version>3.0.1</Version>
19+
</PackageReference>
20+
<PackageReference Include="Serilog.Sinks.ElmahIO">
21+
<Version>3.5.0</Version>
22+
</PackageReference>
23+
<PackageReference Include="Serilog.Sinks.File">
24+
<Version>4.1.0</Version>
25+
</PackageReference>
26+
</ItemGroup>
27+
28+
</Project>
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
using System;
2+
using System.Collections.Generic;
3+
using System.Linq;
4+
using System.Threading.Tasks;
5+
using Microsoft.AspNetCore.Hosting;
6+
using Microsoft.Extensions.Configuration;
7+
using Microsoft.Extensions.Hosting;
8+
using Microsoft.Extensions.Logging;
9+
using PostSharp.Patterns.Diagnostics;
10+
using PostSharp.Patterns.Diagnostics.Backends.Serilog;
11+
using Serilog;
12+
using Serilog.Events;
13+
using Serilog.Sinks.ElmahIo;
14+
15+
// Add PostSharp Logging to all methods and properties in the entire application:
16+
[assembly: Log]
17+
18+
namespace PostSharp.Samples.Logging.ElmahIo
19+
{
20+
public class Program
21+
{
22+
public static void Main(string[] args)
23+
{
24+
// Set up Serilog:
25+
const string formatString = @"{Timestamp:yyyy-MM-dd HH:mm:ss}[{Level:u3}] {Indent:l}{Message}{NewLine}{Exception}";
26+
Log.Logger =
27+
new LoggerConfiguration()
28+
.MinimumLevel.Debug() // Capture all logs (PostSharp by default logs most traces at the Debug level)
29+
.Enrich.FromLogContext() // Add information from the web request to Serilog (used by elmah.io)
30+
.WriteTo.ColoredConsole(outputTemplate: formatString) // Pretty formatting and indentation for console/file
31+
.WriteTo.File("log.log", outputTemplate: formatString)
32+
.WriteTo.ElmahIo(new ElmahIoSinkOptions(
33+
"0b50912ab59d41a599bba7f8dfc7b89e", // Use key and ID from your elmah.io account
34+
new Guid("aaffe1c7-56c9-4b57-8f31-0eacc6c39481")
35+
)
36+
{
37+
MinimumLogEventLevel = LogEventLevel.Warning // only send warnings and errors to elmah.io
38+
})
39+
.CreateLogger();
40+
41+
// Set up PostSharp Logging:
42+
LoggingServices.DefaultBackend = new SerilogLoggingBackend(Log.Logger)
43+
{
44+
Options =
45+
{
46+
// Add exception stack traces to both detailed and elmah.io logs:
47+
IncludeExceptionDetails = true
48+
}
49+
};
50+
CreateHostBuilder(args).Build().Run();
51+
}
52+
53+
public static IHostBuilder CreateHostBuilder(string[] args) =>
54+
Host.CreateDefaultBuilder(args)
55+
.ConfigureWebHostDefaults(webBuilder =>
56+
{
57+
webBuilder.UseStartup<Startup>();
58+
});
59+
}
60+
}

0 commit comments

Comments
 (0)