NanoProfiler - a light weight .NET profiling library

NanoProfiler 有許多的套件。


如果是 Web 專案,安裝 NanoProfiler.Web 即可 (會連帶安裝 NanoProfiler)。


套件安裝完後要設定 CircularBuffer,可透過程式設定…

1
2
3
4
5
6
protected void Application_Start(object sender, EventArgs e)
{
...
ProfilingSession.CircularBuffer = new CircularBuffer<ITimingSession>(200, session => false);
...
}


也可以透過設定檔設定…

1
2
3
4
5
6
7
8
<configuration>
<configSections>
<section name="slf4net" type="slf4net.Configuration.SlfConfigurationSection, slf4net" />
<section name="nanoprofiler" type="EF.Diagnostics.Profiling.Configuration.NanoProfilerConfigurationSection, NanoProfiler" />
</configSections>
...
<nanoprofiler circularBufferSize="200" />
</configuration>


CircularBuffer 設定完後,就可以設定要 Profile 的部分,像是每個 Request 的進出。

1
2
3
4
5
6
7
8
9
protected void Application_BeginRequest(object sender, EventArgs e)
{
ProfilingSession.Start("root");
}

protected void Application_EndRequest(object sender, EventArgs e)
{
ProfilingSession.Stop();
}


以及 Request 中想要監測的部分。

1
2
3
4
using (var step = ProfilingSession.Current.Step("[StepName]"))
{
...
}


將程式運行起來,訪問 http://[Domain]/nanoprofiler/view 即可看到 profile 的結果。


這邊如果要將資料保存下來,可以加裝 NanoProfiler.Storages.Json,並修改設定去指定使用 Storage。

1
2
3
4
5
6
7
8
9
<configuration>
<configSections>
<section name="slf4net" type="slf4net.Configuration.SlfConfigurationSection, slf4net" />
<section name="nanoprofiler" type="EF.Diagnostics.Profiling.Configuration.NanoProfilerConfigurationSection, NanoProfiler" />
...
</configSections>
...
<nanoprofiler circularBufferSize="200" storage="EF.Diagnostics.Profiling.Storages.Json.JsonProfilingStorage, NanoProfiler.Storages.Json"/>
</configuration>


如果 Profile 要過濾掉一些位置,可以透過程式設定 filter。

1
2
3
4
5
6
7
8
protected void Application_Start()
{
...
// register profiling filters to exclude some URLs from profiling
ProfilingSession.ProfilingFilters.Add(new NameContainsProfilingFilter("_tools/"));
ProfilingSession.ProfilingFilters.Add(new FileExtensionProfilingFilter("jpg", "js", "css"));
...
}


或是透過設定檔設定也可以。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<configuration>
<configSections>
<section name="slf4net" type="slf4net.Configuration.SlfConfigurationSection, slf4net" />
<section name="nanoprofiler" type="EF.Diagnostics.Profiling.Configuration.NanoProfilerConfigurationSection, NanoProfiler" />
...
</configSections>
...
<nanoprofiler circularBufferSize="200" storage="EF.Diagnostics.Profiling.Storages.Json.JsonProfilingStorage, NanoProfiler.Storages.Json">
<filters>
<add key="_tools" value="_tools/" type="Contain" />
<add key="exts" value="ico,jpg,js,css" type="EF.Diagnostics.Profiling.Web.ProfilingFilters.FileExtensionProfilingFilter, NanoProfiler.Web" />
<add key="ViewProfilingLogsHandler" value="ViewProfilingLogsHandler.*" type="regex" />
</filters>
</nanoprofiler>
</configuration>