Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions Diagnostics/PostSharp.Samples.Logging.ElmahIo/Pages/Error.cshtml
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
@page
@model ErrorModel
@{
ViewData["Title"] = "Error";
}

<h1 class="text-danger">Error.</h1>
<h2 class="text-danger">An error occurred while processing your request.</h2>

@if (Model.ShowRequestId)
{
<p>
<strong>Request ID:</strong> <code>@Model.RequestId</code>
</p>
}

<h3>Development Mode</h3>
<p>
Swapping to the <strong>Development</strong> environment displays detailed information about the error that occurred.
</p>
<p>
<strong>The Development environment shouldn't be enabled for deployed applications.</strong>
It can result in displaying sensitive information from exceptions to end users.
For local debugging, enable the <strong>Development</strong> environment by setting the <strong>ASPNETCORE_ENVIRONMENT</strong> environment variable to <strong>Development</strong>
and restarting the app.
</p>
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;

namespace PostSharp.Samples.Logging.ElmahIo.Pages
{
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public class ErrorModel : PageModel
{
public string RequestId
{
get;
set;
}

public bool ShowRequestId => !string.IsNullOrEmpty(RequestId);

private readonly ILogger<ErrorModel> _logger;

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

public void OnGet()
{
RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier;
}
}
}
18 changes: 18 additions & 0 deletions Diagnostics/PostSharp.Samples.Logging.ElmahIo/Pages/Index.cshtml
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
@page
@model IndexModel
@{
ViewData["Title"] = "Home page";
}

<div class="text-center">
<h1 class="display-4">What am I made of?</h1>
<p>
<form method="post">
How much do you weigh, in kilograms:&nbsp;
<input asp-for="NumberOfKgs" />
<input type="submit" value="Tell me about my body" />
<br></br>
<p style="white-space: pre-line">@ViewData.Model.Result</p>
</form>
</p>
</div>
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Numerics;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Localization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;
using Serilog;

namespace PostSharp.Samples.Logging.ElmahIo.Pages
{
public class IndexModel : PageModel
{
[BindProperty]
public string Result
{
get;
set;
}

[BindProperty]
public string NumberOfKgs
{
get;
set;
}

public void OnPost()
{
this.WriteInterestingFacts();
}

public void OnGet()
{

this.WriteInterestingFacts();
}

private void WriteInterestingFacts()
{
try
{
float kgs = this.GetKilograms(this.NumberOfKgs);
this.Result =
"You weigh " + kgs + " kilograms.\n" +
"You would sell for " + WorthInGold(kgs) + " if you were made of gold.\n" +
"You would explode as " + Explosion(kgs) + " atomic bombs if you were turned into pure energy.\n" +
"You would fall for " + EiffelFall(kgs) + " seconds if you fell from the Eiffel Tower.";
}
catch (Exception)
{
this.Result = "I can't tell you anything about your body.";
}
}

private string EiffelFall(in float kgs) // Ha ha, your mass doesn't actually matter ^^
{
int distance = 300; // m
// distance = acceleration * time squared
// time = square root of (distance / acceleration)
float time = MathF.Sqrt((float) distance / 9.81f);
return time.ToString("F2");
}

private string Explosion(in float kgs)
{
// e = m * c * c
BigInteger c = 299792458;
BigInteger cc = c * c;
BigInteger eTimes1000 = (cc) * new BigInteger((int) (kgs * 1000)); // reasonable accuracy
BigInteger e = eTimes1000 / 1000;
BigInteger atomicEnergy = new BigInteger(100) * 1000 * 1000 * 1000 * 1000;
BigInteger bombs = e / atomicEnergy;
return bombs.ToString();
}

private string WorthInGold(in float kgs)
{
float costOfKgOfGold = 61612; // USD as of September 22, 2020
return "$" + (kgs * costOfKgOfGold);
}

private float GetKilograms(string numberOfStars)
{
return float.Parse(numberOfStars, this.GetUserCulture());
}

private CultureInfo GetUserCulture()
{
var locale = this.Request.HttpContext.Features.Get<IRequestCultureFeature>();
return locale.RequestCulture.Culture;
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<title>@ViewData["Title"] - PostSharp.Samples.Logging.ElmahIo</title>
<link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css"/>
<link rel="stylesheet" href="~/css/site.css"/>
</head>
<body>
<header>
<nav class="navbar navbar-expand-sm navbar-toggleable-sm navbar-light bg-white border-bottom box-shadow mb-3">
<div class="container">
<a class="navbar-brand" asp-area="" asp-page="/Index">PostSharp.Samples.Logging.ElmahIo</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target=".navbar-collapse" aria-controls="navbarSupportedContent"
aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="navbar-collapse collapse d-sm-inline-flex flex-sm-row-reverse">
<ul class="navbar-nav flex-grow-1">
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-page="/Index">Home</a>
</li>
</ul>
</div>
</div>
</nav>
</header>
<div class="container">
<main role="main" class="pb-3">
@RenderBody()
</main>
</div>

<footer class="border-top footer text-muted">
<div class="container">
&copy; 2020 - PostSharp.Samples.Logging.ElmahIo
</div>
</footer>

<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
<script src="~/js/site.js" asp-append-version="true"></script>

@RenderSection("Scripts", required: false)
</body>
</html>
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
<script src="~/lib/jquery-validation/dist/jquery.validate.min.js"></script>
<script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.min.js"></script>
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
@using PostSharp.Samples.Logging.ElmahIo
@namespace PostSharp.Samples.Logging.ElmahIo.Pages
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
@{
Layout = "_Layout";
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Elmah.Io.AspNetCore.Serilog">
<Version>3.0.3</Version>
</PackageReference>
<PackageReference Include="PostSharp.Patterns.Diagnostics">
<Version>6.6.14</Version>
</PackageReference>
<PackageReference Include="PostSharp.Patterns.Diagnostics.Serilog">
<Version>6.6.14</Version>
</PackageReference>
<PackageReference Include="Serilog.Sinks.ColoredConsole">
<Version>3.0.1</Version>
</PackageReference>
<PackageReference Include="Serilog.Sinks.ElmahIO">
<Version>3.5.0</Version>
</PackageReference>
<PackageReference Include="Serilog.Sinks.File">
<Version>4.1.0</Version>
</PackageReference>
</ItemGroup>

</Project>
60 changes: 60 additions & 0 deletions Diagnostics/PostSharp.Samples.Logging.ElmahIo/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using PostSharp.Patterns.Diagnostics;
using PostSharp.Patterns.Diagnostics.Backends.Serilog;
using Serilog;
using Serilog.Events;
using Serilog.Sinks.ElmahIo;

// Add PostSharp Logging to all methods and properties in the entire application:
[assembly: Log]

namespace PostSharp.Samples.Logging.ElmahIo
{
public class Program
{
public static void Main(string[] args)
{
// Set up Serilog:
const string formatString = @"{Timestamp:yyyy-MM-dd HH:mm:ss}[{Level:u3}] {Indent:l}{Message}{NewLine}{Exception}";
Log.Logger =
new LoggerConfiguration()
.MinimumLevel.Debug() // Capture all logs (PostSharp by default logs most traces at the Debug level)
.Enrich.FromLogContext() // Add information from the web request to Serilog (used by elmah.io)
.WriteTo.ColoredConsole(outputTemplate: formatString) // Pretty formatting and indentation for console/file
.WriteTo.File("log.log", outputTemplate: formatString)
.WriteTo.ElmahIo(new ElmahIoSinkOptions(
"YOUR_API_KEY", // Use key and ID from your elmah.io account
new Guid("YOUR_LOG_ID")
)
{
MinimumLogEventLevel = LogEventLevel.Warning // only send warnings and errors to elmah.io
})
.CreateLogger();

// Set up PostSharp Logging:
LoggingServices.DefaultBackend = new SerilogLoggingBackend(Log.Logger)
{
Options =
{
// Add exception stack traces to both detailed and elmah.io logs:
IncludeExceptionDetails = true
}
};
CreateHostBuilder(args).Build().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,27 @@
{
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:61460",
"sslPort": 44392
}
},
"profiles": {
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"PostSharp.Samples.Logging.ElmahIo": {
"commandName": "Project",
"launchBrowser": true,
"applicationUrl": "https://localhost:5001;http://localhost:5000",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
9 changes: 9 additions & 0 deletions Diagnostics/PostSharp.Samples.Logging.ElmahIo/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
This example demonstrates how to use both PostSharp Logging and the error monitoring service [elmah.io](https://elmah.io) in an ASP.NET Core application.

You will need to create an elmah.io account and use your API key and log id in the setup code in `Program.cs`

`Program.cs` contains initialization logic, and `Startup.cs` has an extra statement that adds additional properties to logged events in elmah.io.

The `[assembly: Log]` custom attribute in `Program.cs` adds logging to the whole project.

We describe this project in some detail in a joint blog post with elmah.io [at our blog](https://blog.postsharp.net/elmah-io).
Loading