Skip to content

Commit

Permalink
📝 Logging
Browse files Browse the repository at this point in the history
Resolves #102
  • Loading branch information
rowanmiller committed Jan 26, 2016
1 parent c5387ae commit bf559df
Show file tree
Hide file tree
Showing 16 changed files with 640 additions and 0 deletions.
1 change: 1 addition & 0 deletions docs/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ Entity Framework Documentation
providers/index
modeling/index
cli/index
miscellaneous/index

Contribute
----------
Expand Down
8 changes: 8 additions & 0 deletions docs/miscellaneous/index.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
Miscellaneous
=============

.. toctree::
:titlesonly:
:caption: The following articles are available

logging
66 changes: 66 additions & 0 deletions docs/miscellaneous/logging.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
Logging
=======

.. contents:: `In this article:`
:local:

Create a logger
---------------

The first step is to create an implementation of ``ILoggerProvider`` and ``ILogger``.
* ``ILoggerProvider`` is the component that decides when to create instances of your logger(s). The provider may chose to create different loggers in different situations.
* ``ILogger`` is the component that does the actual logging. It will be passed information from the framework when certain events occur.

Here is a simple implementation that logs a human readable representation of every event to a text file and the Console.

.. literalinclude:: logging/sample/EFLogging/MyLoggerProvider.cs
:language: csharp
:linenos:

.. tip::
The arguments passed to the Log method are:
* ``logLevel`` is the level (e.g. Warning, Info, Verbose, etc.) of the event being logged
* ``eventId`` is a library/assembly specific id that represents the type of event being logged
* ``state`` can be any object that holds state relevant to what is being logged
* ``exception`` gives you the exception that occurred if an error is being logged
* ``formatter`` uses state and exception to create a human readable string to be logged

Register your logger
--------------------

ASP.NET Core
^^^^^^^^^^^^

In an ASP.NET Core application, you register your logger in the Configure method of Startup.cs::

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddProvider(new MyLoggerProvider());

...
}

Other applications
^^^^^^^^^^^^^^^^^^

In your application startup code, create and instance of you context and register your logger.

.. note::
You only need to register the logger with a single context instance. Once you have registered it, it will be used for all other instances of the context in the same AppDomain.

.. literalinclude:: logging/sample/EFLogging.ConsoleApp/Program.cs
:language: csharp
:linenos:
:lines: 11-15

Filtering what is logged
------------------------

The easiest way to filter what is logged, is to adjust your logger provider to only return your logger for certain categories of events. For EF, the category passed to your logger provider will be the type name of the component that is logging the event.

For example, here is a logger provider that returns the logger only for events related to executing SQL against a relational database. For all other categories of events, a null logger (which does nothing) is returned.

.. literalinclude:: logging/sample/EFLogging/MyFilteredLoggerProvider.cs
:language: csharp
:linenos:
:emphasize-lines: 17-22
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
</startup>
</configuration>
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{804A9357-D201-468C-ABB4-9B77E1D91EA3}</ProjectGuid>
<OutputType>Exe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>EFLogging.ConsoleApp</RootNamespace>
<AssemblyName>EFLogging.ConsoleApp</AssemblyName>
<TargetFrameworkVersion>v4.6.1</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="EntityFramework.Core, Version=7.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\packages\EntityFramework.Core.7.0.0-rc1-final\lib\net451\EntityFramework.Core.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="Microsoft.Extensions.Caching.Abstractions, Version=1.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.Extensions.Caching.Abstractions.1.0.0-rc1-final\lib\net451\Microsoft.Extensions.Caching.Abstractions.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="Microsoft.Extensions.Caching.Memory, Version=1.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.Extensions.Caching.Memory.1.0.0-rc1-final\lib\net451\Microsoft.Extensions.Caching.Memory.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="Microsoft.Extensions.Configuration, Version=1.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.Extensions.Configuration.1.0.0-rc1-final\lib\net451\Microsoft.Extensions.Configuration.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="Microsoft.Extensions.Configuration.Abstractions, Version=1.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.Extensions.Configuration.Abstractions.1.0.0-rc1-final\lib\net451\Microsoft.Extensions.Configuration.Abstractions.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="Microsoft.Extensions.Configuration.Binder, Version=1.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.Extensions.Configuration.Binder.1.0.0-rc1-final\lib\net451\Microsoft.Extensions.Configuration.Binder.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="Microsoft.Extensions.DependencyInjection, Version=1.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.Extensions.DependencyInjection.1.0.0-rc1-final\lib\net451\Microsoft.Extensions.DependencyInjection.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="Microsoft.Extensions.DependencyInjection.Abstractions, Version=1.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.Extensions.DependencyInjection.Abstractions.1.0.0-rc1-final\lib\net451\Microsoft.Extensions.DependencyInjection.Abstractions.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="Microsoft.Extensions.Logging, Version=1.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.Extensions.Logging.1.0.0-rc1-final\lib\net451\Microsoft.Extensions.Logging.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="Microsoft.Extensions.Logging.Abstractions, Version=1.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.Extensions.Logging.Abstractions.1.0.0-rc1-final\lib\net451\Microsoft.Extensions.Logging.Abstractions.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="Microsoft.Extensions.OptionsModel, Version=1.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.Extensions.OptionsModel.1.0.0-rc1-final\lib\net451\Microsoft.Extensions.OptionsModel.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="Microsoft.Extensions.Primitives, Version=1.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.Extensions.Primitives.1.0.0-rc1-final\lib\net451\Microsoft.Extensions.Primitives.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="Remotion.Linq, Version=2.0.0.0, Culture=neutral, PublicKeyToken=fee00910d6e5f53b, processorArchitecture=MSIL">
<HintPath>..\packages\Remotion.Linq.2.0.1\lib\net45\Remotion.Linq.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="System" />
<Reference Include="System.Collections.Concurrent" />
<Reference Include="System.Collections.Immutable, Version=1.1.36.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>..\packages\System.Collections.Immutable.1.1.36\lib\portable-net45+win8+wp8+wpa81\System.Collections.Immutable.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="System.ComponentModel.DataAnnotations" />
<Reference Include="System.Core" />
<Reference Include="System.Interactive.Async, Version=1.2.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>..\packages\Ix-Async.1.2.5\lib\net45\System.Interactive.Async.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<None Include="App.config" />
<None Include="packages.config" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\EFLogging\EFLogging.csproj">
<Project>{d3a5391d-9351-44d6-8122-2821c6e4bd62}</Project>
<Name>EFLogging</Name>
</ProjectReference>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>
33 changes: 33 additions & 0 deletions docs/miscellaneous/logging/sample/EFLogging.ConsoleApp/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
using Microsoft.Data.Entity.Infrastructure;
using Microsoft.Extensions.Logging;
using System;

namespace EFLogging.ConsoleApp
{
class Program
{
static void Main(string[] args)
{
using (var db = new BloggingContext())
{
var loggerFactory = ((IInfrastructure<IServiceProvider>)db).GetService<ILoggerFactory>();
loggerFactory.AddProvider(new MyLoggerProvider());
}

using (var db = new BloggingContext())
{
db.Database.EnsureCreated();
db.Blogs.Add(new Blog { Url = "http://sample.com" });
db.SaveChanges();
}

using (var db = new BloggingContext())
{
foreach (var blog in db.Blogs)
{
Console.WriteLine(blog.Url);
}
}
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("EFLogging.ConsoleApp")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("EFLogging.ConsoleApp")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]

// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("804a9357-d201-468c-abb4-9b77e1d91ea3")]

// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="EntityFramework.Core" version="7.0.0-rc1-final" targetFramework="net461" />
<package id="Ix-Async" version="1.2.5" targetFramework="net461" />
<package id="Microsoft.Extensions.Caching.Abstractions" version="1.0.0-rc1-final" targetFramework="net461" />
<package id="Microsoft.Extensions.Caching.Memory" version="1.0.0-rc1-final" targetFramework="net461" />
<package id="Microsoft.Extensions.Configuration" version="1.0.0-rc1-final" targetFramework="net461" />
<package id="Microsoft.Extensions.Configuration.Abstractions" version="1.0.0-rc1-final" targetFramework="net461" />
<package id="Microsoft.Extensions.Configuration.Binder" version="1.0.0-rc1-final" targetFramework="net461" />
<package id="Microsoft.Extensions.DependencyInjection" version="1.0.0-rc1-final" targetFramework="net461" />
<package id="Microsoft.Extensions.DependencyInjection.Abstractions" version="1.0.0-rc1-final" targetFramework="net461" />
<package id="Microsoft.Extensions.Logging" version="1.0.0-rc1-final" targetFramework="net461" />
<package id="Microsoft.Extensions.Logging.Abstractions" version="1.0.0-rc1-final" targetFramework="net461" />
<package id="Microsoft.Extensions.OptionsModel" version="1.0.0-rc1-final" targetFramework="net461" />
<package id="Microsoft.Extensions.Primitives" version="1.0.0-rc1-final" targetFramework="net461" />
<package id="Remotion.Linq" version="2.0.1" targetFramework="net461" />
<package id="System.Collections.Immutable" version="1.1.36" targetFramework="net461" />
</packages>
28 changes: 28 additions & 0 deletions docs/miscellaneous/logging/sample/EFLogging.sln
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 14
VisualStudioVersion = 14.0.24720.0
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EFLogging.ConsoleApp", "EFLogging.ConsoleApp\EFLogging.ConsoleApp.csproj", "{804A9357-D201-468C-ABB4-9B77E1D91EA3}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EFLogging", "EFLogging\EFLogging.csproj", "{D3A5391D-9351-44D6-8122-2821C6E4BD62}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{804A9357-D201-468C-ABB4-9B77E1D91EA3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{804A9357-D201-468C-ABB4-9B77E1D91EA3}.Debug|Any CPU.Build.0 = Debug|Any CPU
{804A9357-D201-468C-ABB4-9B77E1D91EA3}.Release|Any CPU.ActiveCfg = Release|Any CPU
{804A9357-D201-468C-ABB4-9B77E1D91EA3}.Release|Any CPU.Build.0 = Release|Any CPU
{D3A5391D-9351-44D6-8122-2821C6E4BD62}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{D3A5391D-9351-44D6-8122-2821C6E4BD62}.Debug|Any CPU.Build.0 = Debug|Any CPU
{D3A5391D-9351-44D6-8122-2821C6E4BD62}.Release|Any CPU.ActiveCfg = Release|Any CPU
{D3A5391D-9351-44D6-8122-2821C6E4BD62}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal
8 changes: 8 additions & 0 deletions docs/miscellaneous/logging/sample/EFLogging/Blog.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
namespace EFLogging
{
public class Blog
{
public int BlogId { get; set; }
public string Url { get; set; }
}
}
14 changes: 14 additions & 0 deletions docs/miscellaneous/logging/sample/EFLogging/BloggingContext.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
using Microsoft.Data.Entity;

namespace EFLogging
{
public class BloggingContext : DbContext
{
public DbSet<Blog> Blogs { get; set; }

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(@"Server=(localdb)\mssqllocaldb;Database=EFLogging;Trusted_Connection=True;");
}
}
}

0 comments on commit bf559df

Please sign in to comment.