master
bicijinlian 6 years ago
parent 32ba26cf0f
commit d29bfc0088

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.8" />
</startup>
</configuration>

@ -0,0 +1,41 @@
<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd"
autoReload="true"
keepVariablesOnReload="false"
throwExceptions="true"
throwConfigExceptions="true"
internalLogLevel="Trace"
internalLogFile="${basedir}\logs\internal-nlog.txt"
>
<!--引入Nlog扩展包-->
<extensions>
<!--<add assembly="NLog.Web.AspNetCore"/>-->
</extensions>
<!--自定义变量-->
<variable name="myvariable" value="test" />
<!--设置目标-->
<targets>
<!--默认彩色控制台-->
<target xsi:type="ColoredConsole"
name="ColoredConsoleLog"
encoding="utf-8"
layout="${longdate}|${level:uppercase=true}|${logger}|${message}"
/>
<!--写入日志文件-->
<target xsi:type="File"
name="allfile"
fileName="${basedir}\logs\nlog-all-${shortdate}.log"
layout="${longdate}|${event-properties:item=EventId_Id}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}" />
</targets>
<!--设置规则-->
<rules>
<logger ruleName="*" minlevel="Trace" writeTo="ColoredConsoleLog" />
<logger ruleName="*" minlevel="Trace" writeTo="allfile" />
</rules>
</nlog>

File diff suppressed because it is too large Load Diff

@ -0,0 +1,35 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NLog;
using NLog.Config;
using NLog.Fluent;
namespace NLogStudy.ConsoleApp.Default
{
public class NLogBox
{
public Logger Logger;
public NLogBox()
{
Logger = NLog.LogManager.GetCurrentClassLogger();
}
public static LoggingConfiguration GetConfig()
{
LoggingConfiguration configuration = new LoggingConfiguration();
// Targets where to log to: File and Console
var logfile = new NLog.Targets.FileTarget("logfile") { FileName = "file.txt" };
var logconsole = new NLog.Targets.ConsoleTarget("logconsole");
// Rules for mapping loggers to targets
configuration.AddRule(LogLevel.Info, LogLevel.Fatal, logconsole);
configuration.AddRule(LogLevel.Debug, LogLevel.Fatal, logfile);
return configuration;
}
}
}

@ -0,0 +1,70 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" 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>{2A92247E-0483-4444-B150-6826A5DAB107}</ProjectGuid>
<OutputType>Exe</OutputType>
<RootNamespace>NLogStudy.ConsoleApp.Default</RootNamespace>
<AssemblyName>NLogStudy.ConsoleApp.Default</AssemblyName>
<TargetFrameworkVersion>v4.8</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
<Deterministic>true</Deterministic>
</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="NLog, Version=4.0.0.0, Culture=neutral, PublicKeyToken=5120e14c03d0593c, processorArchitecture=MSIL">
<HintPath>..\packages\NLog.4.6.8\lib\net45\NLog.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Configuration" />
<Reference Include="System.Core" />
<Reference Include="System.IO.Compression" />
<Reference Include="System.Runtime.Serialization" />
<Reference Include="System.ServiceModel" />
<Reference Include="System.Transactions" />
<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="NLogBox.cs" />
<Compile Include="NLogWrap.cs" />
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<None Include="App.config" />
<Content Include="NLog.config">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
<None Include="NLog.xsd">
<SubType>Designer</SubType>
</None>
<None Include="packages.config" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>

@ -0,0 +1,40 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NLog;
using NLog.Config;
using NLog.Fluent;
namespace NLogStudy.ConsoleApp.Default
{
public class NLogWrap<T>
{
public Logger Logger;
public NLogWrap()
{
Logger = NLog.LogManager.GetLogger(typeof(T).FullName);
}
public Logger GetLogger()
{
return LogManager.GetCurrentClassLogger();
}
public static LoggingConfiguration GetConfig()
{
LoggingConfiguration configuration = new LoggingConfiguration();
// Targets where to log to: File and Console
var logfile = new NLog.Targets.FileTarget("logfile") { FileName = "file.txt" };
var logconsole = new NLog.Targets.ConsoleTarget("logconsole");
// Rules for mapping loggers to targets
configuration.AddRule(LogLevel.Info, LogLevel.Fatal, logconsole);
configuration.AddRule(LogLevel.Debug, LogLevel.Fatal, logfile);
return configuration;
}
}
}

@ -0,0 +1,62 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NLog;
using NLog.Config;
using NLog.Fluent;
namespace NLogStudy.ConsoleApp.Default
{
class Program
{
private static NLog.Logger Logger;
static void Main(string[] args)
{
Demo8();
Console.WriteLine("任意键退出");
Console.ReadKey();
}
static void Demo8()
{
var log = new NLogBox().Logger;
log.Info()
.Message("This is a test fluent message '{0}'.", DateTime.Now.Ticks)
.Property("Test", "InfoWrite")
.Write();
}
static void FluentDemo()
{
var log = new NLogWrap<Program>().Logger;
log.Info()
.Message("This is a test fluent message '{0}'.", DateTime.Now.Ticks)
.Property("Test", "InfoWrite")
.Write();
}
static void Demo2()
{
var log = new NLogWrap<Program>().Logger;
LogEventInfo theEvent = new LogEventInfo(LogLevel.Error, "logconsole", "Pass my custom value");
theEvent.Properties["MyValue"] = "My custom string";
// deprecated
theEvent.Properties["TheAnswer"] = 42;
log.Log(theEvent);
}
static void Demo1()
{
LogManager.Configuration = NLogWrap<Program>.GetConfig();
Logger = LogManager.GetCurrentClassLogger();
Logger.Error("测试错误");
}
}
}

@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// 有关程序集的一般信息由以下
// 控制。更改这些特性值可修改
// 与程序集关联的信息。
[assembly: AssemblyTitle("NLogStudy.ConsoleApp.Default")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("NLogStudy.ConsoleApp.Default")]
[assembly: AssemblyCopyright("Copyright © 2019")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 将 ComVisible 设置为 false 会使此程序集中的类型
//对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型
//请将此类型的 ComVisible 特性设置为 true。
[assembly: ComVisible(false)]
// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
[assembly: Guid("2a92247e-0483-4444-b150-6826a5dab107")]
// 程序集的版本信息由下列四个值组成:
//
// 主版本
// 次版本
// 生成号
// 修订号
//
//可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值
//通过使用 "*",如下所示:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="NLog" version="4.6.8" targetFramework="net48" />
</packages>

File diff suppressed because it is too large Load Diff

@ -1,8 +1,42 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp3.0</TargetFramework>
<TargetFramework>netcoreapp2.2</TargetFramework>
</PropertyGroup>
<ItemGroup>
<None Remove="appsettings.json" />
<None Remove="nlog.config" />
</ItemGroup>
<ItemGroup>
<Content Include="appsettings.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
<ExcludeFromSingleFile>true</ExcludeFromSingleFile>
<CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
</Content>
<Content Include="nlog.config">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
<ExcludeFromSingleFile>true</ExcludeFromSingleFile>
<CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
</Content>
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="3.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="3.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="3.0.0" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="3.0.0" />
<PackageReference Include="NLog" Version="4.6.8" />
<PackageReference Include="NLog.Extensions.Logging" Version="1.6.1" />
</ItemGroup>
<ItemGroup>
<None Update="NLog.xsd">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
<SubType>Designer</SubType>
</None>
</ItemGroup>
</Project>

@ -1,4 +1,10 @@
using System;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NLog;
using NLog.Config;
using NLog.Extensions.Logging;
namespace NLogStudy.CoreApp2.ConsoleApp
{
@ -6,7 +12,68 @@ namespace NLogStudy.CoreApp2.ConsoleApp
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
var logger = LogManager.GetCurrentClassLogger();
var logger2 = LogManager.GetLogger(typeof(Program).FullName);
logger2.Error("========{demo}-{test}",021,88888888);
try
{
logger.Error("--------");
}
catch (Exception ex)
{
// NLog: catch any exception and log it.
logger.Error(ex, "Stopped program because of exception");
throw;
}
finally
{
// Ensure to flush and stop internal timers/threads before application-exit (Avoid segmentation fault on Linux)
LogManager.Shutdown();
}
Console.ReadKey();
}
/// <summary>
/// 显式(手动)加载配置文件
/// </summary>
static void ExplicitLoadingConfig()
{
//加载配置文件指定Nlog.config
NLog.LogManager.Configuration = new NLog.Config.XmlLoggingConfiguration("nlog.config");
//加载配置文件:从指定字符串
var xmlStream = new System.IO.StringReader("<nlog>*****</nlog>");
var xmlReader = System.Xml.XmlReader.Create(xmlStream);
NLog.LogManager.Configuration = new NLog.Config.XmlLoggingConfiguration(xmlReader, null);
//加载配置文件: Xamarin 资源文件
//加载配置文件: Xamarin Android
//Xamarin Android,将自动扫描 assets文件夹中的 NLog.config
LogManager.Configuration = new XmlLoggingConfiguration("assets/someothername.config");
}
/// <summary>
/// 自动加载配置文件
/// 在启动时NLog会在各种文件中搜索其配置如下所述。
/// 它加载找到的第一个nlog配置找到第一个nlog配置后搜索结束如果找不到配置则NLog失败。
/// </summary>
static void AutoLoadingConfig()
{
//对于独立的*.exe应用程序按如下顺序搜索配置文件
//标准应用程序配置文件通常为applicationname.exe.config
//应用程序目录中的applicationname.exe.nlog
//应用程序目录中的NLog.configdotnet core应用运行在docker中时配置文件名大小写敏感即区分大写小
//NLog.dll所在目录中的NLog.dll.nlog仅当GAC中未安装NLog时
//对于ASP.NET、ASP.NET Core 应用程序,按如下顺序搜索配置文件
//标准Web应用程序文件web.config
//web.nlog与web.config位于同一目录
//应用程序目录中的NLog.config
//NLog.dll所在目录中的NLog.dll.nlog仅当GAC中未安装NLog时
}
}
}

@ -0,0 +1,8 @@
{
"Logging": {
"LogLevel": {
"Default": "Warning"
}
},
"AllowedHosts": "*"
}

@ -0,0 +1,29 @@
<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd"
autoReload="true"
keepVariablesOnReload="false"
throwExceptions="true"
throwConfigExceptions="true"
internalLogLevel="Warn"
internalLogFile="${basedir}\logs\internal-nlog.txt"
>
<!--引入Nlog扩展包-->
<extensions>
<!--<add assembly="NLog.Web.AspNetCore"/>-->
<!--<add assembly="NLog.Redis"/>-->
<!--<add assembly="NLog.Targets.Redis" />-->
</extensions>
<!--自定义变量-->
<variable name="myvariable" value="test" />
<!--设置目标-->
<targets>
<target xsi:type="ColoredConsole" name="consoleTarget"/>
</targets>
<rules>
<logger name="*" minlevel="Info" writeTo="consoleTarget" />
</rules>
</nlog>

@ -0,0 +1,55 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using NLog;
using NLog.Fluent;
namespace NLogStudy.CoreWeb2.UseMySQL.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
public NLog.Logger logger;
public ValuesController(Microsoft.Extensions.Logging.ILogger<ValuesController> lg)
{
this.logger = LogManager.GetCurrentClassLogger();
}
// GET api/values
[HttpGet]
public ActionResult<IEnumerable<string>> Get()
{
logger.Error().Message("=======================================").Property("aa", "bb").Write();
logger.Error("数据库测试#{user}#{type}#{project}","adm",1,"tctw");
return new string[] { "value1", "value2" };
}
// GET api/values/5
[HttpGet("{id}")]
public ActionResult<string> Get(int id)
{
return "value";
}
// POST api/values
[HttpPost]
public void Post([FromBody] string value)
{
}
// PUT api/values/5
[HttpPut("{id}")]
public void Put(int id, [FromBody] string value)
{
}
// DELETE api/values/5
[HttpDelete("{id}")]
public void Delete(int id)
{
}
}
}

File diff suppressed because it is too large Load Diff

@ -0,0 +1,23 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>netcoreapp2.2</TargetFramework>
<AspNetCoreHostingModel>InProcess</AspNetCoreHostingModel>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.App" />
<PackageReference Include="Microsoft.AspNetCore.Razor.Design" Version="2.2.0" PrivateAssets="All" />
<PackageReference Include="MySqlConnector" Version="0.61.0" />
<PackageReference Include="MySqlConnector.Logging.NLog" Version="0.58.0" />
<PackageReference Include="NLog" Version="4.6.8" />
<PackageReference Include="NLog.Web.AspNetCore" Version="4.9.0" />
</ItemGroup>
<ItemGroup>
<Content Update="nlog.config">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
</ItemGroup>
</Project>

@ -0,0 +1,45 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using NLog;
using NLog.Web;
namespace NLogStudy.CoreWeb2.UseMySQL
{
public class Program
{
public static void Main(string[] args)
{
CreateWebHostBuilder(args).Build().Run();
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.ConfigureLogging((hostBuild,logBuild) =>
{
logBuild.ClearProviders();
logBuild.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace);
string connectString= hostBuild.Configuration.GetValue<string>("ConnectionStrings:NLog");
//设置数据库连接字符串方法1使用变量
//nlog配置文件中connectionString="${var:connectionString}"
//NLog.LogManager.Configuration.Variables["connectionString"] = connectString;
//设置数据库连接字符串方法2代码配置Target属性
NLog.LogManager.Configuration.FindTargetByName<NLog.Targets.DatabaseTarget>("MySQLTarget").ConnectionString = connectString;
//设置数据库连接字符串方法3全局诊断字典(测试不通过)
//GlobalDiagnosticsContext.Set("connectionString", connectString);
})
.UseNLog();
}
}

@ -0,0 +1,30 @@
{
"$schema": "http://json.schemastore.org/launchsettings.json",
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:57025",
"sslPort": 0
}
},
"profiles": {
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"launchUrl": "api/values",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"NLogStudy.CoreWeb2.UseMySQL": {
"commandName": "Project",
"launchBrowser": true,
"launchUrl": "api/values",
"applicationUrl": "http://localhost:5000",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}

@ -0,0 +1,42 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using NLog.Extensions.Logging;
namespace NLogStudy.CoreWeb2.UseMySQL
{
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.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseMvc();
}
}
}

@ -0,0 +1,9 @@
{
"Logging": {
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Microsoft": "Information"
}
}
}

@ -0,0 +1,11 @@
{
"ConnectionStrings": {
"NLog":"server=127.0.0.1;port=3306;user=root;password=yt-461400;database=nlog;Sslmode=None;Character Set=utf8;"
},
"Logging": {
"LogLevel": {
"Default": "Warning"
}
},
"AllowedHosts": "*"
}

@ -0,0 +1,58 @@
<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd"
autoReload="true"
keepVariablesOnReload="false"
throwExceptions="true"
throwConfigExceptions="true"
internalLogLevel="Trace"
internalLogFile="${basedir}\logs\internal-nlog.txt"
>
<!--引入Nlog扩展包-->
<extensions>
<add assembly="NLog.Web.AspNetCore"/>
</extensions>
<!--自定义变量-->
<variable name="myvariable" value="test" />
<!--设置目标-->
<targets>
<!--默认彩色控制台-->
<target xsi:type="ColoredConsole"
name="ColoredConsoleLog"
encoding="utf-8"
layout="${longdate}|${level:uppercase=true}|${logger}|${message}">
</target>
<!--调试窗口-->
<target name="debugLog" xsi:type="Debugger" layout="${logger}::${message}"></target>
<!--写入日志文件-->
<target xsi:type="File"
name="allfile"
fileName="${basedir}\logs\nlog-all-${shortdate}.log"
layout="${longdate}|${event-properties:item=EventId_Id}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}">
</target>
<target xsi:type="Database"
name="MySQLTarget"
dbProvider="MySql.Data.MySqlClient.MySqlConnection, MySqlConnector"
keepConnection="false"
commandType="Text"
commandText="insert into applog (zl_timestamp, zl_user, zl_level, zl_type, zl_message, zl_exception, zl_project) values (@timestamp,@user,@level,@type,@message,@exception,@project);"
>
<parameter name="@timestamp" layout="${longdate}"/>
<parameter name="@user" layout="${event-context:item=user}"/>
<parameter name="@level" layout="${level}"/>
<parameter name="@type" layout="${event-context:item=type}"/>
<parameter name="@message" layout="${message}"/>
<parameter name="@exception" layout="${exception:tostring}"/>
<parameter name="@project" layout="${event-context:item=project}"/>
</target>
</targets>
<!--设置规则-->
<rules>
<logger ruleName="*" minlevel="Warn" writeTo="ColoredConsoleLog,debugLog,MySQLTarget" />
</rules>
</nlog>

@ -40,5 +40,6 @@
<rules>
<logger name="*" minlevel="Info" writeTo="MySQLTarget" />
<logger name="*" minlevel="Info" writeTo="console" />
<logger name="*" minlevel="Trace" writeTo="MySQLTarget" />
</rules>
</nlog>

@ -23,36 +23,38 @@
<target xsi:type="ColoredConsole"
name="ColoredConsoleLog"
encoding="utf-8"
header="-------------------------------------------"
layout="${longdate}|${level:uppercase=true}|${logger}|${message}"
footer="############################################"
/>
<!--默认彩色控制台-->
<target xsi:type="Console" name="ConsoleLog" />
<!--调试窗口-->
<target name="debugLog" xsi:type="Debugger" layout="${logger}::${message}"/>
<!--写入日志文件-->
<target xsi:type="File"
name="allfile"
<!--写入通用日志文件-->
<target xsi:type="File"
name="allfile"
fileName="${basedir}\logs\nlog-all-${shortdate}.log"
layout="${longdate}|${event-properties:item=EventId_Id}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}" />
layout="${longdate}|${event-properties:item=EventId_Id}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}">
</target>
<target xsi:type="Database"
name="MySQLTarget"
dbProvider="MySql.Data.MySqlClient.MySqlConnection, MySql.Data"
connectionString="server=127.0.0.1;port=3306;user=root;password=yt-461400;database=nlog;Sslmode=None;Character Set=utf8;"
keepConnection="false"
commandType="Text"
commandText="insert into applog (zl_timestamp, zl_user, zl_level, zl_type, zl_message, zl_exception, zl_project) values (@timestamp,@user,@level,@type,@message,@exception,@project);"
>
<parameter name="@timestamp" layout="${longdate}"/>
<parameter name="@user" layout="${event-context:item=user}"/>
<parameter name="@level" layout="${level}"/>
<parameter name="@type" layout="${event-context:item=type}"/>
<parameter name="@message" layout="${message}"/>
<parameter name="@exception" layout="${exception:tostring}"/>
<parameter name="@project" layout="${event-context:item=project}"/>
</target>
<!-- 写入文件使用asp.net core -->
<target xsi:type="File"
name="webFilelog"
fileName="${basedir}\logs\nlog-own-${shortdate}.log"
layout="${longdate}|${event-properties:item=EventId_Id}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}|url: ${aspnet-request-url}|action: ${aspnet-mvc-action}" />
</targets>
<!--设置规则-->
<rules>
<logger ruleName="*" minlevel="Warn" writeTo="ColoredConsoleLog" />
<logger ruleName="*" minlevel="Trace" writeTo="debugLog" />
<!--<logger ruleName="System*" minlevel="Trace" writeTo="ColoredConsoleLog" />-->
<!--<logger ruleName="*" minlevel="Trace" writeTo="ConsoleLog" />
<logger ruleName="*" minlevel="Trace" writeTo="allfile" />
<logger ruleName="*" minlevel="Trace" writeTo="webFilelog" />-->
<logger ruleName="*" minlevel="Warn" writeTo="ColoredConsoleLog,debugLog,allfile" />
</rules>
</nlog>

@ -12,6 +12,7 @@ EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Documents", "Documents", "{208F7D4B-D0ED-4838-867F-670FAAE04BC3}"
ProjectSection(SolutionItems) = preProject
Study.md = Study.md
配置文件.md = 配置文件.md
EndProjectSection
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "NLogStudy.WebCore2.Database", "NLogStudy.WebCore2.Database\NLogStudy.WebCore2.Database.csproj", "{E6F61C33-1123-4CE0-A67F-CB22312E4B6E}"
@ -22,7 +23,11 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "NetFramework", "NetFramewor
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "NLogStudy.CoreApp2.ConsoleApp", "NLogStudy.CoreApp2.ConsoleApp\NLogStudy.CoreApp2.ConsoleApp.csproj", "{36486C33-686F-4289-A393-9638221F597D}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NLogStudy.CoreWeb2.UseRedis", "NLogStudy.CoreWeb2.UseRedis\NLogStudy.CoreWeb2.UseRedis.csproj", "{A09AE790-7201-42D2-A489-92F3C2C937EB}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "NLogStudy.CoreWeb2.UseRedis", "NLogStudy.CoreWeb2.UseRedis\NLogStudy.CoreWeb2.UseRedis.csproj", "{A09AE790-7201-42D2-A489-92F3C2C937EB}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NLogStudy.ConsoleApp.Default", "NLogStudy.ConsoleApp.Default\NLogStudy.ConsoleApp.Default.csproj", "{2A92247E-0483-4444-B150-6826A5DAB107}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NLogStudy.CoreWeb2.UseMySQL", "NLogStudy.CoreWeb2.UseMySQL\NLogStudy.CoreWeb2.UseMySQL.csproj", "{2FBAA6D4-2B7A-44E7-9E6A-27DC6AFCEA24}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
@ -50,6 +55,14 @@ Global
{A09AE790-7201-42D2-A489-92F3C2C937EB}.Debug|Any CPU.Build.0 = Debug|Any CPU
{A09AE790-7201-42D2-A489-92F3C2C937EB}.Release|Any CPU.ActiveCfg = Release|Any CPU
{A09AE790-7201-42D2-A489-92F3C2C937EB}.Release|Any CPU.Build.0 = Release|Any CPU
{2A92247E-0483-4444-B150-6826A5DAB107}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{2A92247E-0483-4444-B150-6826A5DAB107}.Debug|Any CPU.Build.0 = Debug|Any CPU
{2A92247E-0483-4444-B150-6826A5DAB107}.Release|Any CPU.ActiveCfg = Release|Any CPU
{2A92247E-0483-4444-B150-6826A5DAB107}.Release|Any CPU.Build.0 = Release|Any CPU
{2FBAA6D4-2B7A-44E7-9E6A-27DC6AFCEA24}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{2FBAA6D4-2B7A-44E7-9E6A-27DC6AFCEA24}.Debug|Any CPU.Build.0 = Debug|Any CPU
{2FBAA6D4-2B7A-44E7-9E6A-27DC6AFCEA24}.Release|Any CPU.ActiveCfg = Release|Any CPU
{2FBAA6D4-2B7A-44E7-9E6A-27DC6AFCEA24}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
@ -60,6 +73,8 @@ Global
{C1435088-3E35-47AB-9672-3EA9813771ED} = {A4009762-9525-445C-AE31-7D240F3E2BA4}
{36486C33-686F-4289-A393-9638221F597D} = {A4009762-9525-445C-AE31-7D240F3E2BA4}
{A09AE790-7201-42D2-A489-92F3C2C937EB} = {A4009762-9525-445C-AE31-7D240F3E2BA4}
{2A92247E-0483-4444-B150-6826A5DAB107} = {A4C5C2CC-8F8A-49C9-AAF6-AADA380791F0}
{2FBAA6D4-2B7A-44E7-9E6A-27DC6AFCEA24} = {A4009762-9525-445C-AE31-7D240F3E2BA4}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {EB3CF482-270A-4536-9A9B-EA1145B7E859}

@ -0,0 +1,83 @@
# 配置文件概述
## 配置文件智能提示
+ 方法一引入Nuget包:NLog.config 和 NLog.Schema
+ 方法二下载NLog.xsd文件并配置
> 下载提示文件 https://nlog-project.org/schemas/NLog.xsd 并放入项目根目录
> 编辑nlog.config文件在nlog根节点中添加属性 xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd"
## 配置文件位置
### 自动匹配
在程序启动时NLog会在各种文件中搜索其配置(如下所述)。它加载找到的第一个nlog配置文件按下述默认位置依次查找nlog配置找到第一个搜索结束使用配置全部位置搜索完仍然找不到配置则NLog失败。
对于独立的* .exe应用程序文件搜索如下
+ 标准应用程序配置文件通常为applicationname.exe.config
+ 应用程序目录中的applicationname.exe.nlog
+ 应用程序目录中的NLog.config名称敏感使用docker dotnet core
+ NLog.dll所在目录中的NLog.dll.nlog仅当GAC中未安装NLog时
对于ASP.NET应用程序文件搜索如下
+ 标准Web应用程序文件web.config
+ web.nlog与web.config位于同一目录
+ 应用程序目录中的NLog.config
+ NLog.dll所在目录中的NLog.dll.nlog仅当GAC中未安装NLog时
### 显式(手动)指定匹配
+ 加载配置文件指定Nlog.config文件
```csharp
NLog.LogManager.Configuration = new NLog.Config.XmlLoggingConfiguration("nlog.config");
```
+ 加载配置文件:从指定字符串
```csharp
var xmlStream = new System.IO.StringReader("<nlog>*****</nlog>");
var xmlReader = System.Xml.XmlReader.Create(xmlStream);
NLog.LogManager.Configuration = new NLog.Config.XmlLoggingConfiguration(xmlReader, null);
```
+ 加载配置文件: Xamarin 资源文件
+ 加载配置文件: Xamarin Android, 自动扫描 assets文件夹中的 NLog.config
```csharp
LogManager.Configuration = new XmlLoggingConfiguration("assets/someothername.config");
```
## 配置文件布局
NLog配置的格式为XML并且可以嵌入Visual Studio项目配置文件app.config或web.config也可以是独立的XML文件。
+ 嵌入到项目配置文件中
```xml
<configuration>
<configSections>
<!--添加Nlog配置节-->
<section name="nlog" type="NLog.Config.ConfigSectionHandler, NLog"/>
</configSections>
...
<!--NLog配置-->
<nlog>
...
</nlog>
</configuration>
```
+ 独立XML文件: **NLog.config**
```xml
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
...
</nlog>
```
## 顶级元素
nlog配置有以下顶级元素,其中targets和rules在任何配置中都是必需的其他为可选项在高级方案中很有用。
+ targets :定义日志目标/输出
+ rules :定义日志路由规则
+ extensions :从* .dll文件加载NLog扩展程序集
+ include :包括外部配置文件
+ variable :设置配置变量
最简单的配置一个target 和 一个rule
Loading…
Cancel
Save