Announcement

Collapse

Looking for a User App or Add-On built by the NinjaTrader community?

Visit NinjaTrader EcoSystem and our free User App Share!

Have a question for the NinjaScript developer community? Open a new thread in our NinjaScript File Sharing Discussion Forum!
See more
See less

Partner 728x90

Collapse

Use Log4net In Ninja trader custom project

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

    Use Log4net In Ninja trader custom project

    Hi Guys,

    I had my strategy packaged into a dll and was able to integrate into ninjatrader successfully. But I am having some troubles configuring my log4net in ninja trader.

    is there a way for me to put my log4net configuration into ninjatrader and have my log output to the target file as I did when I had my dll running in my own test project? (what i did was putting all the configurations into app.config)

    Thanks,

    An

    #2
    Hi An,

    Thanks for the post and welcome to the NinjaTrader forums. Unfortunately we cannot provide support for custom applications, but will leave this thread open for other community members to respond.

    If you would like assistance using NinjaScript to output to a file, please see the following reference samples:
    http://www.ninjatrader.com/support/forum/showthread.php?t=3475
    http://www.ninjatrader.com/support/f...ead.php?t=3477
    Ryan M.NinjaTrader Customer Service

    Comment


      #3
      I do not know if this will answer all of your questions but this link might get you going in the right direction.
      For logging service my choice is log4net from Apache Software Foundation. It is easy to use, open source and well documented. There are also so many logging services but they are not open source. S…

      Comment


        #4
        Thanks ScJohn,

        I did exactly the same in my unit test project which was running perfectly. But I am having troubles using it in Ninjatrader on step 4.

        4. Now put this web.config/app.config file in configuration tag.

        I don't know where I should put it. Do you have similar problem before?

        Thanks,

        An

        Comment


          #5
          Though this is a old thread, I would like to know if anyone was able to resolve the issue. I would like to know where to place the config file ?

          Comment


            #6
            I have Log4Net now working... Yeah not sure why the App.config will not be read so instead redirected to a another config file.

            Steps for my example:
            1) Create directory C:\NinjaTraderLogs
            2) Create config file C:\NinjaTraderLogs\Log4Net.config.
            Example config for Rolling File Appender
            Code:
            <?xml version="1.0" encoding="utf-8" ?>
            <configuration>
              <configSections>
                <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
              </configSections>
              <log4net>
                    <appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
                  <file value="C:\NinjaTraderLogs\NinjaLogs.txt" />
                  <appendToFile value="true" />
                  <rollingStyle value="Size" />
                  <maxSizeRollBackups value="5" />
                  <maximumFileSize value="10MB" />
                  <staticLogFileName value="true" />
                  <layout type="log4net.Layout.PatternLayout">
                    <conversionPattern value="%date [%thread] %level %logger - %message%newline" />
                  </layout>
                </appender>
                <root>
                  <level value="All" />
                  <appender-ref ref="RollingFileAppender" />
                </root>
              </log4net>
            </configuration>
            3) In some custom Indi or Strategy add following assembly statement :
            Code:
            [[COLOR=blue]assembly[/COLOR]: log4net.Config.[COLOR=#2b91af]XmlConfigurator[/COLOR](ConfigFile = [COLOR=#a31515]"C:\\NinjaTraderLogs\\Log4Net.config"[/COLOR], Watch = [COLOR=blue]true[/COLOR])]
            4) In each class (Indi, Strat, etc) you want to use the logger add the following just inside the class:
            Code:
            [COLOR=blue]private[/COLOR] [COLOR=blue]static[/COLOR] [COLOR=blue]readonly[/COLOR] log4net.[COLOR=#2b91af]ILog[/COLOR] log = log4net.[COLOR=#2b91af]LogManager[/COLOR].GetLogger(System.Reflection.[COLOR=#2b91af]MethodBase[/COLOR].GetCurrentMethod().DeclaringType);
            5) Now create log statements like
            Code:
            log.Debug("this is my variable = " + variable1);
            There are various log levels that can be used (e.g. log.Debug, log.Error, log.Info, etc). The config file currently is set to log all levels with
            Code:
            <level value="All" />
            This can be changed at runtime as needed.

            You could also create a different config file for each strategy, indi, etc and create separate log files for each if you like.

            Many appenders are available. Some will create xml files, some will post log messages to a database, some will send email, etc...

            Hope this helps.

            Comment


              #7
              Hey tornadoatc thanks for your input.

              I did exactly what you described, and I don't get log4net working for me, probably I'm missing something...

              1 and 2, are done locally and I copied your config file...

              3 I added the following code to C:\Users\<my user>\Documents\NinjaTrader 8\bin\Custom\AssemblyInfo.cs
              Code:
               [assembly: log4net.Config.XmlConfigurator(ConfigFile = "C:\\NinjaTraderLogs\\Log4Net.config", Watch = true)]
              4 In my strategy I wrote:
              Code:
              ...in the strategy class...
              
              private static ILog logr;
              
              protected override void OnStateChange()
              {
                     if(State == State.Configure)
                     {
                            log4net.Config.XmlConfigurator.Configure();
                            logr = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
                            logr.Info("logr.Info()");
                     }
              }
              5 I compiled and enabled the strategy which should result, if I understand correctly, in 1 log entry in a newly created log file?

              Thanks in advance for your expertise
              Paul

              Comment


                #8
                I added:
                Code:
                log4net.Config.XmlConfigurator.Configure(new FileInfo("C:\\NinjaTraderLogs\\Log4Net.config"));
                and now it is working...

                Comment


                  #9
                  tornadoatc & Paulito123 , thank you for your experimentation and guidance with implementing Log4Net.
                  Please provide more detail on how you've implemented Log4Net.

                  I've attempted to implement Log4net two different ways. Both have failed.

                  First, in VisualStudio Community 2019, in the NinjaTrader.Custom project, I added a reference to Log4Net via NuGet Package (picture 1).
                  When attempting to use any log4net code (e.g. private static log4net.ILog log), this approach yielded an error "The type or namespace name 'log4net' could not be found".

                  Second, I've downloaded Log4Net Binaries (Apache log4net – Download Apache log4net - Apache log4net).
                  In the NinjaScript Editor, I added a reference to the net45/log4Net.dll (picture 2).
                  Attempting to compile after adding this reference yields the compile error "Duplicate 'global::System.Runtime.Versioning.TargetFramework Attribute' attribute" in the NinjaScript File "\NETFramework,Version=v4\8\AssemblyAttributes .cs" (picture 3).

                  Any guidance is greatly appreciated.
                  Shannon

                  Attached Files

                  Comment


                    #10
                    Hello Shansen, thanks for writing in.

                    The DLL files must be manually downloaded and placed within the Documents\NinjaTrader 8\bin\Custom folder, it looks like you have the DLLs in a different folder.

                    Please let me know if this does not resolve your inquiry.
                    Chris L.NinjaTrader Customer Service

                    Comment


                      #11
                      Brilliant! Thanks Chris

                      Comment


                        #12
                        I found Ninja traders a very helpful platform, these scripts are very useful in html.
                        Last edited by kaveeen77; 08-12-2021, 03:58 AM.

                        Comment


                          #13
                          Originally posted by tornadoatc View Post
                          I have Log4Net now working... Yeah not sure why the App.config will not be read so instead redirected to a another config file.

                          Steps for my example:
                          1) Create directory C:\NinjaTraderLogs
                          2) Create config file C:\NinjaTraderLogs\Log4Net.config.
                          Example config for Rolling File Appender
                          Code:
                          <?xml version="1.0" encoding="utf-8" ?>
                          <configuration>
                          <configSections>
                          <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
                          </configSections>
                          <log4net>
                          <appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
                          <file value="C:\NinjaTraderLogs\NinjaLogs.txt" />
                          <appendToFile value="true" />
                          <rollingStyle value="Size" />
                          <maxSizeRollBackups value="5" />
                          <maximumFileSize value="10MB" />
                          <staticLogFileName value="true" />
                          <layout type="log4net.Layout.PatternLayout">
                          <conversionPattern value="%date [%thread] %level %logger - %message%newline" />
                          </layout>
                          </appender>
                          <root>
                          <level value="All" />
                          <appender-ref ref="RollingFileAppender" />
                          </root>
                          </log4net>
                          </configuration>
                          3) In some custom Indi or Strategy add following assembly statement :
                          Code:
                          [[COLOR=blue]assembly[/COLOR]: log4net.Config.[COLOR=#2b91af]XmlConfigurator[/COLOR](ConfigFile = [COLOR=#a31515]"C:\\NinjaTraderLogs\\Log4Net.config"[/COLOR], Watch = [COLOR=blue]true[/COLOR])]
                          4) In each class (Indi, Strat, etc) you want to use the logger add the following just inside the class:
                          Code:
                          [COLOR=blue]private[/COLOR] [COLOR=blue]static[/COLOR] [COLOR=blue]readonly[/COLOR] log4net.[COLOR=#2b91af]ILog[/COLOR] log = log4net.[COLOR=#2b91af]LogManager[/COLOR].GetLogger(System.Reflection.[COLOR=#2b91af]MethodBase[/COLOR].GetCurrentMethod().DeclaringType);
                          5) Now create log statements like
                          Code:
                          log.Debug("this is my variable = " + variable1);
                          There are various log levels that can be used (e.g. log.Debug, log.Error, log.Info, etc). The config file currently is set to log all levels with
                          Code:
                          <level value="All" />
                          This can be changed at runtime as needed.

                          You could also create a different config file for each strategy, indi, etc and create separate log files for each if you like.

                          Many appenders are available. Some will create xml files, some will post log messages to a database, some will send email, etc...

                          Hope this helps.
                          this is brilliant. However, i only see 5 lines for each exception. How can i get more frames?

                          2021-11-20 14:09:28,648 [UI thread 3] INFO NinjaTrader.NinjaScript.Strategies.EMA20Pullback - at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
                          at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)
                          at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)
                          at System.IO.StreamWriter.CreateFile(String path, Boolean append, Boolean checkHost)
                          at System.IO.StreamWriter..ctor(String path, Boolean append, Encoding encoding, Int32 bufferSize, Boolean checkHost)
                          at System.IO.StreamWriter..ctor(String path, Boolean append)
                          at NinjaTrader.NinjaScript.Strategies.EMA20Pullback.w rite2fileJson(String str, String filename, Boolean append) in c:\Users\trading\Documents\NinjaTrader 8\bin\Custom\Strategies\EMA20Pullback.cs:line 2016

                          Comment

                          Latest Posts

                          Collapse

                          Topics Statistics Last Post
                          Started by mmenigma, Today, 02:22 PM
                          0 responses
                          1 view
                          0 likes
                          Last Post mmenigma  
                          Started by frankthearm, Today, 09:08 AM
                          9 responses
                          35 views
                          0 likes
                          Last Post NinjaTrader_Clayton  
                          Started by NRITV, Today, 01:15 PM
                          2 responses
                          9 views
                          0 likes
                          Last Post NRITV
                          by NRITV
                           
                          Started by maybeimnotrader, Yesterday, 05:46 PM
                          5 responses
                          26 views
                          0 likes
                          Last Post NinjaTrader_ChelseaB  
                          Started by quantismo, Yesterday, 05:13 PM
                          2 responses
                          21 views
                          0 likes
                          Last Post quantismo  
                          Working...
                          X