public TwitterShareService(TwitterPersistenceService twitterPersistenceService,TweetMessageService tweetMessageService)
 {
     _twitterPersistenceService = twitterPersistenceService;
     _tweetMessageService = tweetMessageService;
     _logger = LogManager.GetLogger("log");
     Authenticate();
 }
 public DownloadService(IProvideDownloadClient downloadClientProvider,
     IEventAggregator eventAggregator, Logger logger)
 {
     _downloadClientProvider = downloadClientProvider;
     _eventAggregator = eventAggregator;
     _logger = logger;
 }
 protected MessagePipelineBase(IMessageHandlerProvider messageHandlerProvider, ILifetimeScope lifetimeScope, IMessage message, Logger logger)
     : base(logger)
 {
     _messageHandlerProvider = messageHandlerProvider;
     LifetimeScope = lifetimeScope;
     Message = message;
 }
Beispiel #4
0
 public static void RemoveAppender(Logger.LogDelegate appender)
 {
     _appenders -= appender;
     foreach (var logger in _loggers.Values) {
         logger.OnLog -= appender;
     }
 }
 public PatientController(
     IPatientService patientService,
     IUnitOfWorkAsync unitOfWork) : base(unitOfWork)
 {
     _patientService = patientService;
      _logger = LogManager.GetLogger(GetType().Name);
 }
        public static Job GetJob(int jobId, Logger defaultLogger)
        {
            Job currentJob;
            using (var repo = new JobRepository())
            {
                defaultLogger.Info("Passed job with ID of {0}", jobId);

                currentJob = repo.GetJobById(jobId);

                if (currentJob == null)
                {
                    defaultLogger.Warn("Job not found");
                    return null;
                }

                defaultLogger.Info("Job found. URL is {0} and branch is {1}", currentJob.Url, currentJob.Branch);

                if (currentJob.State != JobState.Pending)
                {
                    defaultLogger.Warn("Cannot start job. Current state is {0}", currentJob.State);
                    return null;
                }

                repo.UpdateStateForJob(currentJob, JobState.Running);
            }

            return currentJob;
        }
Beispiel #7
0
 public static void AddAppender(Logger.LogDelegate appender)
 {
     _appenders += appender;
     foreach (var logger in _loggers.Values) {
         logger.OnLog += appender;
     }
 }
Beispiel #8
0
        public NLog()
        {
            // 確保設定檔存在,如果不存在就建立一個設定檔
            MakeSureConfigExist();

            logger = LogManager.GetLogger("");
        }
Beispiel #9
0
        // GET: Movies
        public ActionResult Index(string movieGenre, string searchString)
        {
            var GenreLst = new List<string>();

            var GenreQry = from d in db.Movies
                           orderby d.Genre
                           select d.Genre;

            GenreLst.AddRange(GenreQry.Distinct());
            ViewBag.movieGenre = new SelectList(GenreLst);

            var movies = from m in db.Movies
                         select m;

            if (!String.IsNullOrEmpty(searchString))
            {
                movies = movies.Where(s => s.Title.Contains(searchString));
            }

            if (!string.IsNullOrEmpty(movieGenre))
            {
                movies = movies.Where(x => x.Genre == movieGenre);
            }

            var config = LogManager.Configuration;
            string basedirPath = AppDomain.CurrentDomain.BaseDirectory;
#if TRACE
            logger = NLog.LogManager.GetLogger("rule1");
            logger.Info("\n{0}", movies);
#endif
            return View(movies);
        }
Beispiel #10
0
 /// <summary>
 /// Create a new NLog logger instance.
 /// </summary>
 /// <param name="name">Name of type to log as.</param>
 public NLogLog([NotNull] NLog.Logger log, [NotNull] string name)
 {
     if (name == null)
         throw new ArgumentNullException("name");
     _log = log;
     _log.Debug(() => "");
 }
Beispiel #11
0
        private int Run()
        {
            Bootstrap();
            _logger = _container.Resolve<Logger>();

            var exitCode = HostFactory.Run(host =>
            {
                host.Service<RefreshService>(svc =>
                {
                    svc.ConstructUsing(() =>
                    {
                        var agent = new RefreshService(RefreshInterval, () => _container.Resolve<RabbitMonitorRepository>() as RabbitMonitorRepository);

                        agent.OnReport += (s, e) => _logger.Trace(e.Data);
                        agent.OnError += (s, e) => _logger.Fatal(e.Data);

                        return agent;
                    });

                    svc.WhenStarted(a => a.Start());
                    svc.WhenStopped(a => a.Stop());
                });

                host.SetDescription("Refresh Service Agent for RabbitMQ");
                host.SetDisplayName("RabbitMQ Refresh Agent");
                host.SetServiceName("RabbitMQRefreshAgent");
                host.RunAsNetworkService();
            });

            return (int)exitCode;
        }
Beispiel #12
0
 static Logger createLogger(string name)
 {
     var logger = new Logger(name);
     logger.logLevel = globalLogLevel;
     logger.OnLog += _appenders;
     return logger;
 }
 public RedownloadFailedDownloadService(IConfigService configService, IEpisodeService episodeService, ICommandExecutor commandExecutor, Logger logger)
 {
     _configService = configService;
     _episodeService = episodeService;
     _commandExecutor = commandExecutor;
     _logger = logger;
 }
Beispiel #14
0
 static void Exit(Logger logger, CancellationTokenSource src, ExtensionRunnerExitCode exitCode)
 {
     if(logger != null)
         logger.Info("Exiting (code: " + exitCode + ")");
     src.Cancel();
     Environment.Exit((int)exitCode);
 }
Beispiel #15
0
 public SpinService(IRuntimeInfo runtimeInfo, IProcessProvider processProvider, IStartupContext startupContext, Logger logger)
 {
     _runtimeInfo = runtimeInfo;
     _processProvider = processProvider;
     _startupContext = startupContext;
     _logger = logger;
 }
 public CheckUpdateService(IUpdatePackageProvider updatePackageProvider,
                           IConfigFileProvider configFileProvider,
                           Logger logger)
 {
     _updatePackageProvider = updatePackageProvider;
     _configFileProvider = configFileProvider;
     _logger = logger;
 }
 public CleanExtraFileService(IMetadataFileService metadataFileService,
                             IDiskProvider diskProvider,
                             Logger logger)
 {
     _metadataFileService = metadataFileService;
     _diskProvider = diskProvider;
     _logger = logger;
 }
 /// <summary>
 ///     Creates a logger with the name of class which calls this constructor
 /// </summary>
 public Logger()
 {
     var stackTrace = new StackTrace(); // get call stack
     var stackFrames = stackTrace.GetFrames(); // get method calls (frames)
     var callingFrame = stackFrames?[1];
     var method = callingFrame?.GetMethod();
     logger = LogManager.GetLogger(method?.DeclaringType?.Name);
 }
Beispiel #19
0
 public Logger([NotNull] ILogMessageProcessor logMessageProcessor, string category = null)
 {
     if (logMessageProcessor == null) throw new ArgumentNullException("logMessageProcessor");
     this.logMessageProcessor = logMessageProcessor;
     if (category == null)
         category = string.Empty;
     logger = LogManager.GetLogger(category);
 }
Beispiel #20
0
 public Router(INzbDroneServiceFactory nzbDroneServiceFactory, IServiceProvider serviceProvider,
                 IConsoleService consoleService, Logger logger)
 {
     _nzbDroneServiceFactory = nzbDroneServiceFactory;
     _serviceProvider = serviceProvider;
     _consoleService = consoleService;
     _logger = logger;
 }
		public object GetWidgetData(Widget widget, WidgetParameter[] parameters, ISession session, Logger logger)
		{
			var wChannel = parameters.First(p => p.Name == PARAM_CHANNEL).ValueInt;
			return new
			{
				channel = wChannel
			};
		}
Beispiel #22
0
 public QueueSpecification(IQueueService queueService,
                                QualityUpgradableSpecification qualityUpgradableSpecification,
                                Logger logger)
 {
     _queueService = queueService;
     _qualityUpgradableSpecification = qualityUpgradableSpecification;
     _logger = logger;
 }
Beispiel #23
0
        public QueueProcessorService(Settings settings)
        {
            Database.SetInitializer<HeatHotmailContext>(null);
            Database.SetInitializer<HeatYahooContext>(null);

            _settings = settings;
            _logger = LogManager.GetCurrentClassLogger();
        }
        public MailQueueItem(MailBox account)
        {
            if (account == null) throw new ArgumentNullException("account");

            Account = account;
            Priority = 0;
            _lastTimeItemChecked = DateTime.UtcNow;
            _log = LogManager.GetLogger("MailQueueItem");
        }
Beispiel #25
0
		static Logger()
		{
			_verboseLogger = LogManager.GetLogger("TestR");
			_benchmarkLogger = LogManager.GetLogger("TestR.Benchmark");
			_consoleTarget = new ConsoleTarget();
			_consoleTarget.Layout = "${longdate} ${message}";
			_enableBenchmarking = false;
			_enableTracing = false;
		}
Beispiel #26
0
 public Router(INzbDroneServiceFactory nzbDroneServiceFactory, IServiceProvider serviceProvider, IStartupArguments startupArguments,
                 IConsoleService consoleService, IRuntimeInfo runtimeInfo, Logger logger)
 {
     _nzbDroneServiceFactory = nzbDroneServiceFactory;
     _serviceProvider = serviceProvider;
     _startupArguments = startupArguments;
     _consoleService = consoleService;
     _runtimeInfo = runtimeInfo;
     _logger = logger;
 }
Beispiel #27
0
 public HistorySpecification(IHistoryService historyService,
                                    QualityUpgradableSpecification qualityUpgradableSpecification,
                                    IProvideDownloadClient downloadClientProvider,
                                    Logger logger)
 {
     _historyService = historyService;
     _qualityUpgradableSpecification = qualityUpgradableSpecification;
     _downloadClientProvider = downloadClientProvider;
     _logger = logger;
 }
Beispiel #28
0
 public DelaySpecification(IPendingReleaseService pendingReleaseService,
                           IQualityUpgradableSpecification qualityUpgradableSpecification,
                           IDelayProfileService delayProfileService,
                           Logger logger)
 {
     _pendingReleaseService = pendingReleaseService;
     _qualityUpgradableSpecification = qualityUpgradableSpecification;
     _delayProfileService = delayProfileService;
     _logger = logger;
 }
Beispiel #29
0
 public IndexHtmlMapper(IAppFolderInfo appFolderInfo,
                        IDiskProvider diskProvider,
                        IConfigFileProvider configFileProvider,
                        Logger logger)
     : base(diskProvider, logger)
 {
     _diskProvider = diskProvider;
     _configFileProvider = configFileProvider;
     _indexPath = Path.Combine(appFolderInfo.StartUpFolder, "UI", "index.html");
 }
        protected StaticResourceMapperBase(IDiskProvider diskProvider, Logger logger)
        {
            _diskProvider = diskProvider;
            _logger = logger;

            if (!RuntimeInfo.IsProduction)
            {
                _caseSensitive = true;
            }
        }
        void Page_Error(object sender, EventArgs e)
        {
            // Code that runs when an unhandled error occurs
            Exception lastException = Server.GetLastError();

            NLog.Logger logger  = NLog.LogManager.GetCurrentClassLogger();
            var         message = String.Format($"Unhandled Exception happened: {lastException.GetType()}; with message: {lastException.Message}");

            logger.Error(lastException, message);

            Server.ClearError();          //clear the error so we can continue onwards
            Response.Redirect("~/Error"); //direct user to error page
        }
 public void Setup()
 {
     WhiteListClient client = new WhiteListClient();
     string prodEnvUrl = UrlProvider.ProductionUrl;
     client.Init(prodEnvUrl);
     WhiteListClientFactory.SetClient(client);
     _verifier = new WhiteListCompanyVerifier();
     var config = new NLog.Config.LoggingConfiguration();
     var logfile = new NLog.Targets.FileTarget("logfile") { FileName = "file.txt" };
     config.AddRule(LogLevel.Info, LogLevel.Fatal, logfile);
     NLog.LogManager.Configuration = config;
     Logger = NLog.LogManager.GetCurrentClassLogger();
 }
Beispiel #33
0
        private Logger()
        {
            var config  = new NLog.Config.LoggingConfiguration();
            var logfile = new NLog.Targets.FileTarget("logfile")
            {
                FileName = "pluginlog.log", ArchiveEvery = NLog.Targets.FileArchivePeriod.Day, MaxArchiveFiles = 3, ArchiveFileName = "archive/log.{###}.log", ArchiveNumbering = NLog.Targets.ArchiveNumberingMode.Rolling, Layout = "${longdate}|${level:uppercase=true}|${processname}|${threadid}|${message}"
            };

            config.AddRule(LogLevel.Debug, LogLevel.Fatal, logfile);
            NLog.LogManager.Configuration = config;
            log = LogManager.GetCurrentClassLogger();
            LogMessage(TracingLevel.DEBUG, "Logger Initialized");
        }
Beispiel #34
0
        public NLogImpl(string configfilepath, string loggerName)
        {
            var path = PathTool.getInstance().Map(configfilepath);

            LogManager.Configuration = new XmlLoggingConfiguration(path);

            if (!IsExistLogger(loggerName))
            {
                throw new ArgumentException("初始化日志组件失败!日志配置文件里无此loggerName:" + loggerName, "loggerName");
            }

            logger = LogManager.GetLogger(loggerName);
        }
Beispiel #35
0
        private Logger()
        {
            var config  = new NLog.Config.LoggingConfiguration();
            var logfile = new NLog.Targets.FileTarget("logfile")
            {
                FileName = "pluginlog.log", ArchiveEvery = NLog.Targets.FileArchivePeriod.Day, MaxArchiveFiles = 10, ArchiveFileName = "logs/log.{###}.log", ArchiveNumbering = NLog.Targets.ArchiveNumberingMode.Rolling
            };

            config.AddRule(LogLevel.Debug, LogLevel.Fatal, logfile);
            NLog.LogManager.Configuration = config;
            log = LogManager.GetCurrentClassLogger();
            LogMessage(TracingLevel.DEBUG, "Logger Initialized");
        }
Beispiel #36
0
        internal void Connect(string host, ushort port)
        {
            if (_logger == null)
            {
                _logger = LogManager.GetCurrentClassLogger();
            }

            _twitchSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            _twitchSocket.BeginConnect(host, port, ConnectCallback, null);
            _logger.Info($"Beginning connection to server {host}:{port}");
            _storedhost = host;
            _storedport = port;
        }
Beispiel #37
0
 static Log()
 {
     if (logger == null)
     {
         lock (_locker)
         {
             if (logger == null)
             {
                 logger = LogManager.GetCurrentClassLogger();
             }
         }
     }
 }
Beispiel #38
0
        private static void CreateLogger()
        {
            LoggingConfiguration loggingConfiguration = new LoggingConfiguration();
            FileTarget           fileTarget           = new FileTarget
            {
                FileName = Environment.LogFilePath,
                Layout   = "${longdate} [${threadid}] ${callsite} ${level:uppercase=true} ${message}"
            };

            loggingConfiguration.LoggingRules.Add(new LoggingRule("*", LogLevel.Debug, fileTarget));
            LogManager.Configuration = loggingConfiguration;
            logger = LogManager.GetLogger(String.Empty);
        }
Beispiel #39
0
        public static long StopWatchNormal(this NLog.Logger logger, string message, Action action, [CallerMemberName] string methodName = "")
        {
            var stopWatch = new System.Diagnostics.Stopwatch();

            stopWatch.Start();
            action();
            stopWatch.Stop();
            var    milliseconds = stopWatch.ElapsedMilliseconds;
            string info         = $"{message} <{milliseconds}ms>";

            logger.WoxInfo(info, methodName);
            return(milliseconds);
        }
Beispiel #40
0
 public PixelService(NLog.Logger logger, DbContextOptions dbContextOptions,
                     UsersParser usersParser, ImagesParser imagesParser, ImageMetaParser imageMetaParser,
                     FileLoader fileLoader, GoogleService googleService, MSVisionService msvisionService)
 {
     this._logger           = logger;
     this._dbContextOptions = dbContextOptions;
     this._usersParser      = usersParser;
     this._imagesParser     = imagesParser;
     this._imageMetaParser  = imageMetaParser;
     this._fileLoader       = fileLoader;
     this._googleService    = googleService;
     this._msvisionService  = msvisionService;
 }
Beispiel #41
0
        private void ConfigureLoggingService()
        {
            // Set a variable in the gdc which is be used in NLog.config for the
            // base path of our app: ${gdc:item=appbasepath}
            string logfilesPath = GMFileAccess.GetSolutionSiblingFolder(Configuration["Logging:LogfilesPath"]);

            //string logfilesPath = GMFileAccess.GetFullPath(Configuration["AppSettings:LogfilesPath"]);
            GlobalDiagnosticsContext.Set("logfilesPath", logfilesPath);

            // Create an instance of NLog.Logger manually here since it is not available
            // from dependency injection yet.
            logger = LogManager.LoadConfiguration("nlog.config").GetCurrentClassLogger();
        }
        public static bool Write(string req, string res, string path)
        {
            try
            {
                NLog.Logger logger = NLogBuilder.ConfigureNLog(Directory.GetCurrentDirectory() + "\\NlogRequestResponse.config").GetCurrentClassLogger();
                GlobalDiagnosticsContext.Set("Request", req);
                GlobalDiagnosticsContext.Set("Response", res);
                logger.Info(path);
            }
            catch { return(false); }

            return(true);
        }
Beispiel #43
0
 public Logger([NotNull] ILogMessageDump logMessageDump, string category = null)
 {
     if (logMessageDump == null)
     {
         throw new ArgumentNullException(nameof(logMessageDump));
     }
     this.logMessageDump = logMessageDump;
     if (category == null)
     {
         category = string.Empty;
     }
     this.category = category;
     logger        = LogManager.GetLogger(category);
 }
Beispiel #44
0
        public DreamsLogService(Context context)
        {
            _context = context;
            _log     = LogManager.GetCurrentClassLogger();
            var config = new LoggingConfiguration();

#if DEBUG
            PrepareConsoleTarget(config);
#endif

            PrepareFileTarget(config);
            LogManager.Configuration = config;
            _log = LogManager.GetLogger(DreamsResources.Common_Application_Label);
        }
Beispiel #45
0
        private static void CreateLogger()
        {
            LoggingConfiguration loggingConfiguration = new LoggingConfiguration();
            FileTarget           fileTarget           = new FileTarget
            {
                FileName = Environment.LogFilePath,
                Layout   = "${longdate} [${threadid}] ${callsite} ${level:uppercase=true} ${message}",
            };
            AsyncTargetWrapper fileAsyncTargetWrapper = new AsyncTargetWrapper(fileTarget, ASYNC_LOG_QUEUE_SIZE, AsyncTargetWrapperOverflowAction.Grow);

            loggingConfiguration.LoggingRules.Add(new LoggingRule("*", LogLevel.Debug, fileAsyncTargetWrapper));
            LogManager.Configuration = loggingConfiguration;
            logger = LogManager.GetLogger(String.Empty);
        }
Beispiel #46
0
            /// <summary>
            /// Записывает в журнал сообщение об исключении
            /// </summary>
            /// <param name="type">Тип журнала</param>
            /// <param name="level">Уровень сообщения</param>
            /// <param name="exception">Исключение</param>
            /// <param name="message">Сообщение</param>
            /// <param name="parameters">Параметры формирования сообщения</param>
            private static void LogException(LogType type, NLog.LogLevel level, Exception exception, string message, params object[] parameters)
            {
                NLog.Logger logger = GetLogger(type);
                if (logger == null)
                {
                    return;
                }

                if (logger.IsEnabled(level))
                {
                    string msg = parameters.Length > 0 ? string.Format(message, parameters) : message;
                    logger.LogException(level, msg, exception);
                }
            }
Beispiel #47
0
        public NLogLogger(string derictory)
        {
            log = NLog.LogManager.GetLogger(LoggerName);
            var config = new NLog.Config.LoggingConfiguration();

            var logfile = new NLog.Targets.FileTarget("logfile")
            {
                FileName = derictory
            };

            config.AddRule(LogLevel.Debug, LogLevel.Fatal, logfile);

            NLog.LogManager.Configuration = config;
        }
Beispiel #48
0
 private void RaiseLogEvent(LogEventInfo logEventInfo)
 {
     if (logEventInfo != null)
     {
         if (_logger == null)
         {
             _logger = LogManager.GetLogger(LoggerName);
         }
         if (_logger != null)
         {
             _logger.Log(logEventInfo);
         }
     }
 }
Beispiel #49
0
        // this works in multithreaded environment, but a local instance of watch is always needed. It profiles inside one function, not  between different callstack levels
        public static void ProfiledInfo(this NLog.Logger logger, string message, Stopwatch watch, bool forceConsoleTarget = false)  // Profiled info can go silently to log files
        {
            watch.Stop();
            var msgEx = $"{message} takes {watch.Elapsed.TotalMilliseconds:f3}ms";

            logger.Info(msgEx);

            if (forceConsoleTarget)
            {
                Console.WriteLine(msgEx);
            }

            watch.Restart();
        }
Beispiel #50
0
        public LoggerService(Context context)
        {
            _context = context;
            _log     = LogManager.GetCurrentClassLogger();
            var config = new LoggingConfiguration();

#if DEBUG
            PrepareConsoleTarget(config);
#endif

            PrepareFileTarget(config);
            LogManager.Configuration = config;
            _log = LogManager.GetLogger(APP_NAME);
        }
Beispiel #51
0
 void IDisposable.Dispose()
 {
     _logger = null;
     try
     {
         _factory.Dispose();
     }
     finally
     {
         _factory = null;
         // NOTE: Just optomization
         GC.SuppressFinalize(this);
     }
 }
Beispiel #52
0
        public static string CreateOrder(List <ObjectType> OrderList)
        {
            // Setup logger.
            var config  = new NLog.Config.LoggingConfiguration();
            var logfile = new NLog.Targets.FileTarget("logfile")
            {
                FileName = "logs/httpreq.log"
            };

            config.AddRule(LogLevel.Debug, LogLevel.Fatal, logfile);
            NLog.LogManager.Configuration = config;
            NLog.Logger Logger = NLog.LogManager.GetCurrentClassLogger();

            // Start building httpd client.
            var client = new HttpClient();

            // ACCEPT header
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            // Get base url from appsettings.json.
            var    readConfig = GetConfiguration();
            string url        = readConfig.GetSection("invoicesAddr").Value;

            if (url is null)
            {
                Logger.Warn("Error sending HTTP request not able to read from config url for Invoices api host to send post request to save invoice.");
                return("Error sending HTTP request to Invoices api and saved Orders.");
            }
            client.BaseAddress = new Uri(url);

            var data = JsonConvert.SerializeObject(OrderList, Formatting.Indented);
            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "relativeAddress");

            //CONTENT-TYPE header
            request.Content = new StringContent(data, Encoding.UTF8, "application/json");

            // Try sending http POST request.
            try
            {
                var    response        = client.PostAsync("/SaveOrdersDetails", request.Content);
                string responseDetails = response.Result.ToString();
                Logger.Info("Sucessfully sent HTTP request to api Invoices with repsonse" + responseDetails);
                return("Sucessfully sent HTTP request to api Invoices");
            }
            catch (HttpRequestException ex)
            {
                Logger.Warn("Error sending HTTP request", ex);
                return("Error sending HTTP request to Invoices api and saved Orders.");
            }
        }
Beispiel #53
0
        static Logger()
        {
            //var config = new NLog.Config.LoggingConfiguration();
            //var logfile = new NLog.Targets.FileTarget("logfile") { FileName = filePath };
            //var layout = NLog.Layouts.Layout.FromString("${longdate} ${message} ${exception:format=ToString,StackTrace}");
            //var logconsole = new NLog.Targets.ConsoleTarget("logconsole");
            //config.AddRule(LogLevel.Debug, LogLevel.Fatal, logconsole);
            //logfile.Layout = layout;
            //config.AddRule(LogLevel.Trace, LogLevel.Fatal, logfile);
            //NLog.LogManager.Configuration = config;


            Log = LogManager.GetCurrentClassLogger();
        }
Beispiel #54
0
    //Nlog
    protected void Button3_Click(object sender, EventArgs e)
    {
        //写日志
        //Logger logger = LogManager.GetCurrentClassLogger();
        NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();

        Thread.Sleep(1000);
        //记录警告信息
        logger.Warn("this is a Nlog warn log!");

        logger.Fatal("this is a Nlog fatal log!");

        logger.Debug("this is a Nlog debug log!");

        logger.Trace("this is a Nlog trace log!");

        logger.Error("this is a Nlog error log!");
        logger.Info("this is a Nlog info log");

        //记录一般信息
        string logname      = "Info"; //这里的logname可以任意字符串
        Logger loggerByName = LogManager.GetLogger(logname);
        string log2         = "this is a Nlog common log";

        loggerByName.Info(log2);



        //获取cookie值
        string [] ss = Request.Cookies.AllKeys;
        int       i  = 0;

        foreach (string s in ss)
        {
            try
            {
                string t = Request.Cookies[s].Value.ToString();
                Response.Write("****************************");
                Response.Write(s + "=" + t);
                //logger.Info("info cookie name"+t);
            }
            catch
            {
                Response.Write(i);
                i++;
                logger.Error("获取cookie{0}失败!", s);
            }
        }
    }
Beispiel #55
0
        public static void GProfiledInfo(this NLog.Logger logger, string message, bool forceConsoleTarget = false)  // Profiled info can go silently to log files
        {
            var lastTimeStamp = g_lastTimeStamp ?? DateTime.Now;
            var elapsedTime   = DateTime.Now - lastTimeStamp;
            var msgEx         = $"{message} takes {elapsedTime.TotalMilliseconds:f3}ms";

            logger.Info(msgEx);

            if (forceConsoleTarget)
            {
                Console.WriteLine(msgEx);
            }

            g_lastTimeStamp = DateTime.Now;
        }
Beispiel #56
0
        public Logger()
        {
            var config     = new LoggingConfiguration();
            var fileTarget = new FileTarget()
            {
                FileName = "logFile.log", Layout = @"${date:format=HH\:mm\:ss} ${level} ${message} ${exception}"
            };

            var rule = new LoggingRule("*", LogLevel.Trace, fileTarget);

            config.LoggingRules.Add(rule);

            LogManager.Configuration = config;
            _logger = LogManager.GetCurrentClassLogger();
        }
Beispiel #57
0
        private static void NLogTest()
        {
            var path = Path.Combine(Directory.GetCurrentDirectory(), "nlog.config");

            NLog.LogManager.Configuration = new XmlLoggingConfiguration(path, true);
            NLog.Logger nlog = LogManager.GetCurrentClassLogger();

            for (int i = 0; i < 100; i++)
            {
                //      StackifyLib.Logger.Queue("Debug", "Test message");
                //System.Threading.Thread.Sleep(1);
                nlog.Debug("Hello");
                //nlog.Debug(new { color = "red", int1 = 1 });
            }
        }
Beispiel #58
0
        public static void WriteToLog(this NLog.Logger logger, LogLevels level, string message, string loggerName)
        {
            switch (level)
            {
            case LogLevels.Debug: logger.Debug($"{loggerName}||{message}"); break;

            case LogLevels.Info: logger.Info($"{loggerName}|{message}"); break;

            case LogLevels.Warning: logger.Warn($"{loggerName}|{message}"); break;

            case LogLevels.Error: logger.Error($"{loggerName}|{message}"); break;

            default: logger.Debug($"{loggerName}|{message}"); break;
            }
        }
        public static void WriteToLog(this NLog.Logger logger, LogLevels level, string sessionId, string deviceId, string message)
        {
            switch (level)
            {
            case LogLevels.Debug: logger.Debug($"{sessionId}|{deviceId}|{message}"); break;

            case LogLevels.Info: logger.Info($"{sessionId}|{deviceId}|{message}"); break;

            case LogLevels.Warning: logger.Warn($"{sessionId}|{deviceId}|{message}"); break;

            case LogLevels.Error: logger.Error($"{sessionId}|{deviceId}|{message}"); break;

            default: logger.Debug($"{sessionId}|{deviceId}|{message}"); break;
            }
        }
Beispiel #60
0
 public void SetLogger(object logger)
 {
     if (logger != null)
     {
         var loggr = logger as NLog.Logger;
         if (loggr != null)
         {
             _logger = loggr;
         }
     }
     else
     {
         _logger = LogManager.GetLogger(ConfigurationHelper.AppSettingsItem <string>("AppName") ?? "MultiTenancyFramework");
     }
 }