How does ADO. NET Entity Framework output logs to log4net (EF, log4net)

Source: Internet
Author: User
Tags log4net
The EF team launched a complete set of cache and SQL Execution log solutions, efproviderwrappers. Their practice is to add a layer of packaging on the original EF provider, and use this layer of packaging interception for data caching and log monitoring. The cached data is the native data returned by the database after query, and is not an entity object. This avoids the extreme negative impact of the entity object status on the cache. In addition, this cache is transparent to upper-layer data queries, and within the same closed range, after the object type on which the cached data depends is updated (the corresponding table has a curd operation), the cache is automatically cleared. Log monitoring can be easily processed after this layer of packaging. You can download from the previous link to the original Code .

The following describes how to use it:
1. Download the source code compilation and add reference:
(1) efproviderwrappertoolkit. dll
(2) eftracingprovider. dll (used to output SQL)

(3) efcachingprovider. dll (for caching)

2. inherit an extended objectcontext from the generated objectcontext and define the required extended attributes. The focus is to redefine the constructor and generate the encapsulated entityconnection object.
Note:
(1) name = northwndentities the "northwndentities" here is the name of the connectionstring that generates EF in APP. config or web. config.
(2) "eftracingprovider", "efcachingprovider". If one is not used, delete the corresponding string.

[C-sharp] View plaincopyprint?
    1. Public extendednorthwindentities ()
    2. : This ( "name = northwindentities" )
    3. {
    4. }
    5. Public extendednorthwindentities ( string connectionstring)
    6. : base (entityconnectionwrapperutils. createentityconnectionwithwrappers (
    7. connectionstring,
    8. "eftracingprovider" ,
    9. "efcachingprovider"
    10. )
    11. {
    12. }

Public extendednorthwindentities () <br/>: This ("name = northwindentities") <br/>{< br/>}< br/> Public extendednorthwindentities (string connectionstring) <br/>: Base (entityconnectionwrapperutils. createentityconnectionwithwrappers (<br/> connectionstring, <br/> "eftracingprovider", <br/> "efcachingprovider" <br/>) <br/>{< br/>}

3. ApplicationProgramProvider:
(1) if it is a winform application, you can call the following two statements of code at application startup to register the application.[C-sharp]View plaincopyprint?

    1. Eftracingproviderconfiguration. registerprovider ();
    2. Efcachingproviderconfiguration. registerprovider ();

Eftracingproviderconfiguration. registerprovider (); <br/> efcachingproviderconfiguration. registerprovider (); <br/>
(2) For a web application, you need to append the following configuration in Web. config: (same level as the system. Web node)[XHTML]View plaincopyprint?

  1. <System. Data>
  2. <Dbproviderfactories>
  3. Add name = "Ef caching data provider" invariant = "efcachingprovider" description = "caching provider wrapper" type = "efcachingprovider. efcachingproviderfactory, efcachingprovider, version = 1.0.0.0, culture = neutral, publickeytoken = def642f226e0e59b " />
  4. Add name = "Ef tracing data provider " invariant = " eftracingprovider " description = "tracing provider wrapper" type = "eftracingprovider. eftracingproviderfactory, eftracingprovider, version = 1.0.0.0, culture = neutral, publickeytoken = def642f226e0e59b " />
  5. <Add Name="Ef generic provider wrapper" Invariant="Efproviderwrapper" Description="Generic provider wrapper" Type="Efproviderwrappertoolkit. efproviderwrapperfactory, efproviderwrappertoolkit, version = 1.0.0.0, culture = neutral, publickeytoken = def642f226e0e59b" />
  6. </Dbproviderfactories>
  7. System. data

<System. DATA> <br/> <dbproviderfactories> <br/> <Add name = "Ef caching data provider" invariant = "efcachingprovider" Description = "caching provider wrapper" type = "efcachingprovider. efcachingproviderfactory, efcachingprovider, version = 1.0.0.0, culture = neutral, publickeytoken = def642f226e0e59b "/> <br/> <Add name =" Ef tracing data provider "invariant =" eftracingprovider "Description =" tracing provider wrapper "type =" eftracingprovider. eftracingproviderfactory, eftracingprovider, version = 1.0.0.0, culture = neutral, publickeytoken = Taobao "/> <br/> <Add name =" Ef generic provider wrapper "invariant =" efproviderwrapper "Description =" generic provider wrapper "type =" efproviderwrappertoolkit. efproviderwrapperfactory, efproviderwrappertoolkit, version = 1.0.0.0, culture = neutral, publickeytoken = def642f226e0e59b "/> <br/> </dbproviderfactories> <br/> </system. DATA> <br/>

How to append log4net output:
According to the above steps, some code is added to the extension class of objectcontext. For details, see the comments in the Code:[C-sharp]View plaincopyprint?

  1. PublicPartialClassExtendednorthwindentities: northwndentities
  2. {
  3. Private StaticIlog logger;
  4. StaticExtendednorthwindentities ()
  5. {
  6. // Register tracingprovider
  7. Eftracingproviderconfiguration. registerprovider ();
  8. // Initialize log4net and configure it in the independent "log4net. config"
  9. Log4net. config. xmlconfigurator. Configure (NewFileinfo ("Log4net. config"));
  10. // Initialize a logger
  11. Logger = log4net. logmanager. getlogger ("Eflog4net");
  12. }
  13. PublicExtendednorthwindentities ()
  14. :This("Name = northwndentities")
  15. {
  16. // Bind the commandexecuting event of eftracingconnection and output the log
  17. This. Unwrapconnection <eftracingconnection> (). commandexecuting + = (S, e) =>
  18. {
  19. // Output tracestring (SQL)
  20. Logger. debug (environment. newline + E. totracestring (). trimend ());
  21. };
  22. }
  23. PublicExtendednorthwindentities (StringConnectionstring)
  24. :Base(Entityconnectionwrapperutils. createentityconnectionwithwrappers (
  25. Connectionstring,
  26. "Eftracingprovider"
  27. ))
  28. {
  29. }

Public partial class extendednorthwindentities: northwndentities <br/>{< br/> Private Static ilog logger; <br/> static extendednorthwindentities () <br/>{< br/> // register tracingprovider <br/> eftracingproviderconfiguration. registerprovider (); <br/> // initialize log4net, Which is configured in an independent "log4net. config ". <br/> log4net. config. xmlconfigurator. configure (New fileinfo ("log4net. config "); <br/> // initialize a logger <br/> logger = log4net. logmanager. getlogger ("eflog4net"); <br/>}< br/> Public extendednorthwindentities () <br/>: This ("name = northwndentities ") <br/>{< br/> // bind the commandexecuting event of eftracingconnection, and output log <br/> This. unwrapconnection <eftracingconnection> (). commandexecuting + = (S, e) => <br/>{< br/> // output tracestring (SQL) <br/> logger. debug (environment. newline + E. totracestring (). trimend (); <br/>}; <br/>}< br/> Public extendednorthwindentities (string connectionstring) <br/>: Base (entityconnectionwrapperutils. createentityconnectionwithwrappers (<br/> connectionstring, <br/> "eftracingprovider" <br/>) <br/>{< br/>}< br/>}
The configuration of log4net. config is as follows: (for other detailed configuration instructions of log4net, refer to the http://logging.apache.org/log4net/release/config-examples.html) [C-sharp] View plaincopyprint?

  1. <? XML version ="1.0"Encoding ="UTF-8"?>
  2. <Configuration>
  3. <Log4net>
  4. <Root>
  5. <Level value ="All"/>
  6. <Appender-Ref Ref="Rollingfileappender"/>
  7. <Appender-Ref Ref="Leleappender"/>
  8. </Root>
  9. <Appender name ="Rollingfileappender"Type ="Log4net. appender. rollingfileappender, log4net">
  10. <Param name ="File"Value =Http://www.cnblogs.com/logs/EFLogs.txt"/>
  11. <Param name ="Appendtofile"Value ="True"/>
  12. <Param name ="Rollingstyle"Value ="Date"/>
  13. <Param name ="Datepattern"Value ="YYYY. Mm. dd"/>
  14. <Param name ="Staticlogfilename"Value ="True"/>
  15. <Layout type ="Log4net. layout. patternlayout, log4net">
  16. <Param name ="Conversionpattern"Value ="% D [% T] %-5 p % C-% m % N"/>
  17. </Layout>
  18. </Appender>
  19. <Appender name ="Leleappender"Type ="Log4net. appender. coloredconsoleappender, log4net">
  20. <Mapping>
  21. <Level value ="Debug"/>
  22. <! -- <Forecolor value ="White"/> -->
  23. <Backcolor value ="Cyan, highintensity"/>
  24. </Mapping>
  25. <Layout type ="Log4net. layout. patternlayout, log4net">
  26. <Param name ="Conversionpattern"Value ="% D [% T] [%-5 p] % C-% m % N"/>
  27. </Layout>
  28. </Appender>
  29. </Log4net>
  30. </Configuration>

<? XML version = "1.0" encoding = "UTF-8"?> <Br/> <configuration> <br/> <log4net> <br/> <root> <br/> <level value = "all"/> <br/> <appender -Ref ref = "rollingfileappender"/> <br/> <appender-ref = "leleappender"/> <br/> </root> <br/> <appender name = "rollingfileappender" type = "log4net. appender. rollingfileappender, log4net "> <br/> <Param name =" file "value =" http://www.cnblogs.com/logs/EFLogs.txt "/> <br/> <Param name =" appendtofile "value =" Tru E "/> <br/> <Param name =" rollingstyle "value =" date "/> <br/> <Param name =" datepattern "value =" YYYY. mm. dd "/> <br/> <Param name =" staticlogfilename "value =" true "/> <br/> <layout type =" log4net. layout. patternlayout, log4net "> <br/> <Param name =" conversionpattern "value =" % d [% T] %-5 p % C-% m % N "/> <br/> </layout> <br/> </appender> <br/> <appender name = "leleappender" type = "log4net. appender. coloredcon Soleappender, log4net "> <br/> <mapping> <br/> <level value =" debug "/> <br/> <! -- <Forecolor value = "white"/> --> <br/> <backcolor value = "cyan, highintensity "/> <br/> </mapping> <br/> <layout type =" log4net. layout. patternlayout, log4net "> <br/> <Param name =" conversionpattern "value =" % d [% T] [%-5 p] % C-% m % N "/> <br/> </layout> <br/> </appender> <br/> </log4net> <br/> </configuration>

In this way, you can control the SQL output generated by EF through the log4net configuration file. In the above log4net, two appender are configured. One is output to the console, and the other is output to eflogs.txt.
Next, call EF to see the output log:[C-sharp]View plaincopyprint?

  1. Static VoidMain (String[] ARGs)
  2. {
  3. Using(Var db =NewExtendednorthwindentities ())
  4. {
  5. VaR toyproducts = from PInDB. Products
  6. Where p. Category. categoryname. Contains ("Seafood")
  7. SelectNew{P. Category. categoryname, P. productname, P. unitprice };
  8. Console. writeline ("-----------------");
  9. Foreach(VAR PInToyproducts)
  10. Console. writeline ("{0,-10} {1,-35} {2, 10 }", P. categoryname, P. productname, P. unitprice );
  11. }
  12. Console. Read ();
  13. }

Static void main (string [] ARGs) <br/>{< br/> using (var db = new extendednorthwindentities ()) <br/> {<br/> var toyproducts = from P in dB. products <br/> where p. category. categoryname. contains ("seafood") <br/> select new {P. category. categoryname, P. productname, P. unitprice }; <br/> console. writeline ("-----------------"); <br/> foreach (var p in toyproducts) <br/> console. writeline ("{0,-10} {1,-35} {2, 10}", p. categoryname, P. productname, P. unitprice); <br/>}< br/> console. read (); <br/>}

 

 

the output in the blue background above is the SQL log configured and output through log4net. In addition, this efproviderwrappers not only allows us to output log functions, but also provides important functions for its caching, in the next Article , I will focus on how to use efproviderwrappers to implement data caching.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.