コード例 #1
0
        public void CallingMethods()
        {
            NLogLogMock logMock = new NLogLogMock();
            NLogLogger  logger  = new NLogLogger(logMock);
            bool        b       = logger.IsDebugEnabled;

            b = logger.IsErrorEnabled;
            b = logger.IsFatalEnabled;
            b = logger.IsInfoEnabled;
            b = logger.IsWarnEnabled;

            logger.Debug(null);
            logger.Debug(null, null);
            logger.DebugFormat(null, null);

            logger.Error(null);
            logger.Error(null, null);
            logger.ErrorFormat(null, null);

            logger.Warn(null);
            logger.Warn(null, null);
            logger.WarnFormat(null, null);

            logger.Info(null);
            logger.Info(null, null);
            logger.InfoFormat(null, null);

            logger.Fatal(null);
            logger.Fatal(null, null);

            logMock.debug.Should().Be(1);
            logMock.debugException.Should().Be(1);
            logMock.debugFormat.Should().Be(1);
            logMock.info.Should().Be(1);
            logMock.infoException.Should().Be(1);
            logMock.infoFormat.Should().Be(1);
            logMock.warn.Should().Be(1);
            logMock.warnException.Should().Be(1);
            logMock.warnFormat.Should().Be(1);
            logMock.error.Should().Be(1);
            logMock.errorException.Should().Be(1);
            logMock.errorFormat.Should().Be(1);
            logMock.fatal.Should().Be(1);
            logMock.fatalException.Should().Be(1);
            logMock.isDebugEnabled.Should().Be(1);
            logMock.isInfoEnabled.Should().Be(1);
            logMock.isWarnEnabled.Should().Be(1);
            logMock.isErrorEnabled.Should().Be(1);
            logMock.isFatalEnabled.Should().Be(1);
        }
コード例 #2
0
        public void Add_File_Target()
        {
            string tmpFile = Path.GetTempFileName();
            ILog   log     = new NLogLogger("Test_Logger");

            log.AddFileTarget("Test_Target", tmpFile);
            log.Debug("DEBUG MESSAGE");
            log.Info("INFO MESSAGE");
            log.Error("ERROR MESSAGE");
            log.Warn("WARN MESSAGE");
            log.Fatal("FATAL MESSAGE");
            log.Flush();

            string logContents = File.ReadAllText(tmpFile);

            Console.Write(logContents);

            Assert.True(logContents.Contains("DEBUG MESSAGE"));
            Assert.True(logContents.Contains("INFO MESSAGE"));
            Assert.True(logContents.Contains("ERROR MESSAGE"));
            Assert.True(logContents.Contains("WARN MESSAGE"));
            Assert.True(logContents.Contains("FATAL MESSAGE"));

            File.Delete(tmpFile);
        }
コード例 #3
0
        public void Logger_Log_DelegatesToNLog()
        {
            var     target = GetLogMemoryTarget();
            ILogger log    = new NLogLogger(LogManager.GetLogger("cat"));

            log.Info("msg");
            Assert.Equal("cat|Info|msg||", target.Logs.Last());
            log.Log(LogLevel.Info, "msg");
            Assert.Equal("cat|Info|msg||", target.Logs.Last());

            log.Debug("msg");
            Assert.Equal("cat|Debug|msg||", target.Logs.Last());
            log.Log(LogLevel.Debug, "msg");
            Assert.Equal("cat|Debug|msg||", target.Logs.Last());

            log.Warn("msg");
            Assert.Equal("cat|Warn|msg||", target.Logs.Last());
            log.Log(LogLevel.Warning, "msg");
            Assert.Equal("cat|Warn|msg||", target.Logs.Last());

            log.Error("msg", new Exception("ex"));
            Assert.Equal("cat|Error|msg|ex|", target.Logs.Last());
            log.Log(LogLevel.Error, "msg", new Exception("ex"));
            Assert.Equal("cat|Error|msg|ex|", target.Logs.Last());

            log.Fatal("msg");
            Assert.Equal("cat|Fatal|msg||", target.Logs.Last());
            log.Fatal("msg", new Exception("ex"));
            Assert.Equal("cat|Fatal|msg|ex|", target.Logs.Last());
            log.Log(LogLevel.Fatal, "msg", new Exception("ex"));
            Assert.Equal("cat|Fatal|msg|ex|", target.Logs.Last());
        }
コード例 #4
0
 private bool ValidateSearchOutput(List <Album> albums, string site)
 {
     if (SearchHasEnded == false)
     {
         Monitor.Enter(this);
         try
         {
             _mSitesSearched++;
             log.Debug($"{site} Albums: {albums.Count} Searched: {_mSitesSearched} Sites Count: {AlbumSites.Count}");
             if (albums.Count > 0)
             {
                 _controller.AlbumFound = new object[] { albums, site };
                 if (_mSitesSearched == AlbumSites.Count)
                 {
                     Dispose();
                 }
                 return(true);
             }
             else
             {
                 if (_mSitesSearched == AlbumSites.Count)
                 {
                     Dispose();
                 }
                 return(false);
             }
         }
         finally
         {
             Monitor.Exit(this);
         }
     }
     return(false);
 }
コード例 #5
0
ファイル: Discogs.cs プロジェクト: ShobikaPalani/MPTagThat-2
        protected override void GetAlbumInfoWithTimer()
        {
            log.Debug("Discogs: Looking up Album on Discogs");
            Albums.Clear();
            try
            {
                var task   = GetAlbumQuery();
                var result = task.Result; // Ignoring the result here, since we have added the album already in the task.

                log.Debug($"Discogs: Found {Albums.Count} albums");
            }
            catch (Exception ex)
            {
                log.Debug($"Discogs: Exception receiving Album Information. {ex.Message} {ex.StackTrace}");
            }
        }
コード例 #6
0
 protected override void GetAlbumInfoWithTimer()
 {
     log.Debug("MusicBrainz: Looking up Album on MusicBrainz");
     Albums.Clear();
     try
     {
         var album = GetAlbumQuery(ArtistName, AlbumName);
         if (album.Result != null)
         {
             Albums.Add(album.Result);
         }
         log.Debug($"MusicBrainz: Found {Albums.Count} albums");
     }
     catch (Exception ex)
     {
         log.Debug($"MusicBrainz: Exception receiving Album Information. {ex.Message} {ex.StackTrace}");
     }
 }
コード例 #7
0
        public void WhenNoCurrentClassNameIsSpecifiedNLogUsesDefaultCurrentClassName()
        {
            var logger = new NLogLogger(new TestApplicationSettings());

            var logMessageId = logger.Debug("This is a log message", "Some extra log details");

            var logMessage = GetLogMessageFromDatabase(logMessageId);

            Assert.AreEqual("Infrastructure.Loggers.NLogLogger", logMessage.Source);
        }
コード例 #8
0
        private static void LogTest()
        {
            var logger = new NLogLogger(new ApplicationSettings());

            logger.Debug("Just testing debug", "Debug");
            logger.Info("Just testing info", "Info");
            logger.Warn("Just testing warning", "Warning");
            logger.Error("Just testing error", "Error");
            logger.Fatal("Testing with exception", new Exception("TestException"), "Some details again");
        }
コード例 #9
0
        public LoginInternalResult Login(string username, string password, int companyNumber, string languageID, bool firstLogin, bool singleTenant)
        {
            _nLogLogger.Debug($"username {username}", "Login");
            _nLogLogger.Debug($"password {password}", "Login");
            _nLogLogger.Debug($"companyNumber {companyNumber}", "Login");
            _nLogLogger.Debug($"languageID {languageID}", "Login");
            _nLogLogger.Debug($"firstLogin {firstLogin}", "Login");
            _nLogLogger.Debug($"singleTenant {singleTenant}", "Login");
            var pdsUserLoginDataSet = new pdsUserLoginDataSet();

            pdsUserLoginDataSet.ttblUserLogin.AddttblUserLoginRow(username, password, companyNumber, languageID, firstLogin, singleTenant);
            var cErrorMessage = string.Empty;

            StopwatchUtil.Time(
                () =>
            {
                this._poLoginproxy.Login(ref this._pdsContext, ref pdsUserLoginDataSet, out cErrorMessage);
            });
            _nLogLoggerP.Trace("Login");
            if (!string.IsNullOrEmpty(cErrorMessage))
            {
                if (cErrorMessage.Contains(OperInUse))
                {
                    _nLogLogger.Warn($"Error returned - {cErrorMessage}", "PopulateLoginModel");
                }
                else
                {
                    _nLogLogger.Error($"Error returned - {cErrorMessage}", "PopulateLoginModel");
                }
            }
            if (pdsUserLoginDataSet.HasErrors)
            {
                _nLogLogger.Error("pdsUserContext is showing errors", "Login");
            }
            var result = new UserLogin();

            if (pdsUserLoginDataSet.ttblUserLogin.Count > 0)
            {
                result = UserLogin.BuildUserLoginFromRow(pdsUserLoginDataSet.ttblUserLogin[0]);
            }
            var loginInternalResult = this.PopulateLoginModel(pdsUserLoginDataSet.HasErrors, cErrorMessage, result, firstLogin);

            loginInternalResult.availUsers = new List <AvailUsers>();
            foreach (DataRow row in pdsUserLoginDataSet.ttblAvailUsers)
            {
                _nLogLogger.Debug($"Building Avail Users", "Login");
                loginInternalResult.availUsers.Add(AvailUsers.BuildAvailUsersFromRow(row));
            }
            _nLogLogger.Debug($"Finished Login", "Login");
            return(loginInternalResult);
        }
コード例 #10
0
        public void NullableValuesInHttpContextDoNotBreakLogging()
        {
            // Set nullable values is true to set user to null and urlreferrer to null.
            var logger = new NLogLogger(new TestApplicationSettings(), "NLogLoggerTests", GetHttpContext(nullValues: true));

            var logMessageId = logger.Debug("This is a log message");

            var logMessage = GetLogMessageFromDatabase(logMessageId);

            Assert.AreEqual(string.Empty, logMessage.Username);
            Assert.AreEqual(string.Empty, logMessage.UrlReferrer);
        }
コード例 #11
0
        new public void Run(string[] args)
        {
            var(app, buildConfigProvider, getDbBasePath) = BuildCommandLineApp();
            ManualResetEventSlim appClosed = new ManualResetEventSlim(false);

            app.OnExecute(async() =>
            {
                var configProvider = buildConfigProvider();
                var initConfig     = configProvider.GetConfig <IInitConfig>();
                if (initConfig.RemovingLogFilesEnabled)
                {
                    RemoveLogFiles(initConfig.LogDirectory);
                }

                Logger = new NLogLogger(initConfig.LogFileName, initConfig.LogDirectory);
                LogMemoryConfiguration();

                var pathDbPath = getDbBasePath();
                if (!string.IsNullOrWhiteSpace(pathDbPath))
                {
                    var newDbPath = Path.Combine(pathDbPath, initConfig.BaseDbPath);
                    if (Logger.IsDebug)
                    {
                        Logger.Debug($"Adding prefix to baseDbPath, new value: {newDbPath}, old value: {initConfig.BaseDbPath}");
                    }
                    initConfig.BaseDbPath = newDbPath ?? Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "db");
                }

                Console.Title = initConfig.LogFileName;


                var serializer = new UnforgivingJsonSerializer();
                if (Logger.IsInfo)
                {
                    Logger.Info($"Nethermind config:\n{serializer.Serialize(initConfig, true)}\n");
                }



                await StartRunners(configProvider);



                Console.WriteLine("All done, goodbye!");
                appClosed.Set();

                return(0);
            });

            app.Execute(args);
            appClosed.Wait();
        }
コード例 #12
0
        public void GetLogItems_AddedOneLogItem_ContainsOneLogItem()
        {
            var logRepository = new LogRepository(Session);
            var logger        = new NLogLogger(DefaultTestApplicationSettings);
            var gridSettings  = new GridSettings {
                PageSize = 10, PageIndex = 0
            };

            const string message = "Test";

            logger.Debug(message);

            var logItems = logRepository.GetLogItems(gridSettings);

            Assert.AreEqual(1, logItems.Count);
            Assert.AreEqual(message, logItems[0].Message);
        }
コード例 #13
0
        public void CountLogItems_AddedTenLogItems_CollectionContainsTenLogItems()
        {
            var logRepository = new LogRepository(Session);
            var logger        = new NLogLogger(DefaultTestApplicationSettings);
            var gridSettings  = new GridSettings {
                PageSize = 20, PageIndex = 0
            };

            const int totalMessages = 10;

            for (var messageCounter = 0; messageCounter < totalMessages; messageCounter++)
            {
                logger.Debug("Test");
            }

            var logItems = logRepository.GetLogItems(gridSettings);

            Assert.AreEqual(10, logItems.Count);
        }
コード例 #14
0
ファイル: LogTest.cs プロジェクト: Serge1007/project2
        public void CallMethods()
        {
            log.Debug("DebugMessage");
            log.Info("InfoMessage");
            log.Warn("WarnMessage");
            log.Error("ErrorMessage");
            log.Error("ErrorMessage", e);

            Assert.AreEqual("ErrorMessage", "ErrorMessage");

            StreamReader file = new StreamReader($"{DatabasePath}\\{DatabaseName}");

            while ((line = file.ReadLine()) != null)
            {
                contain = line.Contains("InfoMessage");
                if (contain == true)
                {
                    break;
                }
            }

            file.Close();
            Assert.AreEqual(contain, true);
        }
コード例 #15
0
ファイル: LoginService.cs プロジェクト: arentlog/web-ui
        public PreLoginResults PreLogin(string host)
        {
            var preLoginResults      = new PreLoginResults();
            var claimsAndLoginObject = new ClaimsAndLoginObject(new ProgressConfiguration());

            var logTenant = !string.IsNullOrEmpty(claimsAndLoginObject.DeveloperLogin) ? claimsAndLoginObject.DeveloperTenant : claimsAndLoginObject.Tenant;
            var logUser   = !string.IsNullOrEmpty(claimsAndLoginObject.DeveloperLogin) ? claimsAndLoginObject.DeveloperLogin : claimsAndLoginObject.Identity;

            var nLogger = new NLogLogger(
                logTenant,
                logUser,
                0,
                new Guid(),
                "PreLogin",
                host);

            nLogger.Info("Start", "PreLogin");

            ReportErrors(nLogger, claimsAndLoginObject.LoggingEMessages, claimsAndLoginObject.LoggingIMessages, claimsAndLoginObject.LoggingWMessages);

            if (claimsAndLoginObject.InvalidLogin)
            {
                var errorCode = LoginErrorEnums.Unknown;
                if (claimsAndLoginObject.LoggingEMessages.Any())
                {
                    errorCode = claimsAndLoginObject.LoggingEMessages.First().Value;
                }
                RejectLogin(nLogger, "Unauthorized", errorCode);
                return(new PreLoginResults {
                    LoginMode = PreLoginModes.Unauthorized
                });
            }

            if (claimsAndLoginObject.SsoEnabled || !string.IsNullOrEmpty(claimsAndLoginObject.DeveloperLogin))
            {
                var loginUser = logUser + (claimsAndLoginObject.MultiTenant ? "/" : string.Empty) + logTenant;
                nLogger.Info("Before Login", "PreLogin");
                var loginInternalResult = this._loginRepository.Login(loginUser, this._ssoFirst, 0, string.Empty, true, !claimsAndLoginObject.MultiTenant);
                nLogger.Info("After Login", "PreLogin");
                if (!loginInternalResult.availUsers.Any())
                {
                    // Login did not return valid users
                    if (claimsAndLoginObject.AutoProvisionEnabled)
                    {
                        // Try an autoprovision
                        nLogger.Debug(
                            $"Auto Provision Called ifsuser-{claimsAndLoginObject.Identity} tenantid-{claimsAndLoginObject.Tenant} emailaddr-{claimsAndLoginObject.IfsEmail} firstname-{claimsAndLoginObject.IfsGivenName} lastname-{claimsAndLoginObject.IfsLastName} aecompanies-{claimsAndLoginObject.IfsAccountingEntities} securityroles-{claimsAndLoginObject.IfsSecurity}");

                        var provisionRecord = new Crtsasoofromifs
                        {
                            ifsuser       = loginUser,
                            aecompanies   = claimsAndLoginObject.IfsAccountingEntities,
                            firstname     = claimsAndLoginObject.IfsGivenName,
                            lastname      = claimsAndLoginObject.IfsLastName,
                            emailaddr     = claimsAndLoginObject.IfsEmail,
                            securityroles = claimsAndLoginObject.IfsSecurity,
                            tenantid      = claimsAndLoginObject.Tenant
                        };

                        var provisionResult = this._loginRepository.CreateSASOOFromIFS(provisionRecord);

                        if (!string.IsNullOrEmpty(provisionResult.cErrorMessage))
                        {
                            RejectLogin(nLogger, $"Auto Provision Failed - {provisionResult.cErrorMessage}", LoginErrorEnums.AutoProvisionFailed);
                            return(new PreLoginResults {
                                LoginMode = PreLoginModes.Unauthorized
                            });
                        }

                        // Try a first stage login again
                        loginInternalResult = this._loginRepository.Login(loginUser, this._ssoFirst, 0, string.Empty, true, !claimsAndLoginObject.MultiTenant);
                        if (!loginInternalResult.availUsers.Any())
                        {
                            // Reject login as no users found.
                            RejectLogin(nLogger, string.Format(
                                            $"Login did not return any valid user company combinations - {loginInternalResult.ErrorMessage} - Auto Provison was run"), LoginErrorEnums.NoUsersReturnedAfterAutoProvision);
                            return(new PreLoginResults {
                                LoginMode = PreLoginModes.Unauthorized
                            });
                        }
                    }
                    else
                    {
                        // Reject login as no users found.
                        RejectLogin(nLogger, string.Format(
                                        $"Login did not return any valid user company combinations - {loginInternalResult.ErrorMessage}"), LoginErrorEnums.NoCombinationOfUsersPassedBack);
                        return(new PreLoginResults {
                            LoginMode = PreLoginModes.Unauthorized
                        });
                    }
                }

                // If we have reached this stage - we have at least one login unless we have LASTCONO record only.
                var lastCono = 0;
                preLoginResults.AvailableLogin = new List <AvailUsers>();
                foreach (var availUser in loginInternalResult.availUsers)
                {
                    nLogger.Debug("Populate Each User", "PreLogin");
                    if (availUser.availuser == "LASTCONO")
                    {
                        nLogger.Debug("Populate Each User - Last Cono", "PreLogin");
                        lastCono = availUser.availcono;
                    }
                    else
                    {
                        nLogger.Debug("Populate Each User - Add", "PreLogin");
                        preLoginResults.AvailableLogin.Add(availUser);
                    }
                }
                if (!preLoginResults.AvailableLogin.Any())
                {
                    // Reject login as no users found.
                    RejectLogin(nLogger, string.Format(
                                    $"Login did not return any valid user company combinations - {loginInternalResult.ErrorMessage}"), LoginErrorEnums.NoCombinationOfUsersPassedBack);
                    return(new PreLoginResults {
                        LoginMode = PreLoginModes.Unauthorized
                    });
                }
                nLogger.Debug("Before Set Default", "PreLogin");
                foreach (var user in preLoginResults.AvailableLogin)
                {
                    if (user.availcono == lastCono)
                    {
                        nLogger.Debug("Last Cono Set", "PreLogin");
                        preLoginResults.DefaultLogin = user.DisplayValue;
                        break;
                    }
                }
                preLoginResults.LoginMode = PreLoginModes.SSOLoginSelectFromList;
            }
            else
            {
                preLoginResults.LoginMode        = claimsAndLoginObject.MultiTenant ? PreLoginModes.StandardLoginWithTenant : PreLoginModes.StandardLogin;
                preLoginResults.AvailableTenants = claimsAndLoginObject.ListOfTenants;
            }
            nLogger.Debug("End", "PreLogin");
            return(preLoginResults);
        }
 public void Debug(string message)
 {
     _nLogLogger.Debug(message);
     _traceWriterLogger.Debug(message);
 }
コード例 #17
0
        public static bool CaseConvert(ref SongData song)
        {
            log.Trace(">>>");
            bool bErrors = false;

            // Convert the Filename
            if (_options.ConversionSettings.ConvertFileName)
            {
                var fileName = ConvertCase(Path.GetFileNameWithoutExtension(song.FileName));

                // Now check the length of the filename
                if (fileName.Length > 255)
                {
                    log.Debug($"Filename too long: {fileName}");
                    song.Status    = 2;
                    song.StatusMsg = LocalizeDictionary.Instance.GetLocalizedObject("MPTagThat", "Strings",
                                                                                    "tagAndRename_NameTooLong", LocalizeDictionary.Instance.Culture).ToString();
                    bErrors = true;
                }

                if (!bErrors)
                {
                    // Now that we have a correct Filename
                    if (fileName != Path.GetFileNameWithoutExtension(song.FileName))
                    {
                        song.FileName = $"{fileName}{Path.GetExtension(song.FileName)}";
                        song.Changed  = true;
                    }
                }
            }

            // Convert the Tags
            if (_options.ConversionSettings.ConvertTags)
            {
                string strConv;
                var    bChanged = false;
                if (_options.ConversionSettings.ConvertArtist)
                {
                    strConv  = song.Artist;
                    bChanged = (strConv = ConvertCase(strConv)) != song.Artist;
                    if (bChanged)
                    {
                        song.Artist  = strConv;
                        song.Changed = true;
                    }
                }

                if (_options.ConversionSettings.ConvertAlbumArtist)
                {
                    strConv  = song.AlbumArtist;
                    bChanged = (strConv = ConvertCase(strConv)) != song.AlbumArtist;
                    if (bChanged)
                    {
                        song.AlbumArtist = strConv;
                        song.Changed     = true;
                    }
                }

                if (_options.ConversionSettings.ConvertAlbum)
                {
                    strConv  = song.Album;
                    bChanged = (strConv = ConvertCase(strConv)) != song.Album;
                    if (bChanged)
                    {
                        song.Album   = strConv;
                        song.Changed = true;
                    }
                }

                if (_options.ConversionSettings.ConvertTitle)
                {
                    strConv  = song.Title;
                    bChanged = (strConv = ConvertCase(strConv)) != song.Title;
                    if (bChanged)
                    {
                        song.Title   = strConv;
                        song.Changed = true;
                    }
                }

                if (_options.ConversionSettings.ConvertComment)
                {
                    strConv  = song.Comment;
                    bChanged = (strConv = ConvertCase(strConv)) != song.Comment;
                    if (bChanged)
                    {
                        song.Comment = strConv;
                        song.Changed = true;
                    }
                }
            }
            log.Trace("<<<");
            return(song.Changed == true);
        }