// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddHttpClient() .AddControllers() .AddXmlSerializerFormatters(); services.AddLogging( logging => { logging.ClearProviders(); logging.AddNLogWeb(); }); _logger = new Logger <Startup>(LoggerFactory.Create(logging => logging.AddNLogWeb(NLogBuilder.ConfigureNLog("NLog.config").Configuration))); // Подключение к БД services.AddScoped(_ => UnitOfWorkFactory.CreateWithoutRoot("Сервис быстрых платежей")); // Конфигурация Nhibernate try { CreateBaseConfig(); } catch (Exception e) { _logger.LogCritical(e, e.Message); throw; } services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "FastPaymentsAPI", Version = "v1" }); }); services.AddHttpClient <IOrderService, OrderService>(c => { c.BaseAddress = new Uri(Configuration.GetSection("OrderService").GetValue <string>("ApiBase")); c.DefaultRequestHeaders.Add("Accept", "application/x-www-form-urlencoded"); }); services.AddHttpClient <IDriverAPIService, DriverAPIService>(c => { c.BaseAddress = new Uri(Configuration.GetSection("DriverAPIService").GetValue <string>("ApiBase")); c.DefaultRequestHeaders.Add("Accept", "application/json"); }); //backgroundServices services.AddHostedService <FastPaymentStatusUpdater>(); services.AddHostedService <CachePaymentManager>(); //repositories services.AddSingleton <IOrderRepository, OrderRepository>(); services.AddSingleton <IFastPaymentRepository, FastPaymentRepository>(); services.AddSingleton <IStandartNomenclatures, BaseParametersProvider>(); services.AddSingleton <IRouteListItemRepository, RouteListItemRepository>(); services.AddSingleton <ISelfDeliveryRepository, SelfDeliveryRepository>(); services.AddSingleton <ICashRepository, CashRepository>(); //providers services.AddSingleton <IParametersProvider, ParametersProvider>(); services.AddSingleton <IOrderParametersProvider, OrderParametersProvider>(); services.AddSingleton <IFastPaymentParametersProvider, FastPaymentParametersProvider>(); services.AddSingleton <IEmailParametersProvider, EmailParametersProvider>(); //factories services.AddSingleton <IFastPaymentAPIFactory, FastPaymentAPIFactory>(); //converters services.AddSingleton <IOrderSumConverter, OrderSumConverter>(); services.AddSingleton <IResponseCodeConverter, ResponseCodeConverter>(); //models services.AddScoped <IFastPaymentOrderModel, FastPaymentOrderModel>(); services.AddScoped <IFastPaymentModel, FastPaymentModel>(); //validators services.AddScoped <IFastPaymentValidator, FastPaymentValidator>(); //helpers services.AddSingleton <IDTOManager, DTOManager>(); services.AddSingleton <ISignatureManager, SignatureManager>(); services.AddSingleton <IFastPaymentManager, FastPaymentManager>(); services.AddSingleton(_ => new FastPaymentFileCache("/tmp/VodovozFastPaymentServiceTemp.txt")); services.AddScoped <IOrderRequestManager, OrderRequestManager>(); }
static void Main(string[] args) { string path = Directory.GetCurrentDirectory() + "\\nlog.config"; // create instance of Logger var logger = NLogBuilder.ConfigureNLog(path).GetCurrentClassLogger(); logger.Info("Program started"); string file = "movies.csv"; // make sure movie file exists if (!File.Exists(file)) { logger.Error("File does not exist: {File}", file); } else { // create parallel lists of movie details // lists are used since we do not know number of lines of data List <UInt64> MovieIds = new List <UInt64>(); List <string> MovieTitles = new List <string>(); List <string> MovieGenres = new List <string>(); // to populate the lists with data, read from the data file try { StreamReader sr = new StreamReader(file); // first line contains column headers sr.ReadLine(); while (!sr.EndOfStream) { string line = sr.ReadLine(); // first look for quote(") in string // this indicates a comma(,) in movie title int idx = line.IndexOf('"'); if (idx == -1) { // no quote = no comma in movie title // movie details are separated with comma(,) string[] movieDetails = line.Split(','); // 1st array element contains movie id MovieIds.Add(UInt64.Parse(movieDetails[0])); // 2nd array element contains movie title MovieTitles.Add(movieDetails[1]); // 3rd array element contains movie genre(s) // replace "|" with ", " MovieGenres.Add(movieDetails[2].Replace("|", ", ")); } else { // quote = comma in movie title // extract the movieId MovieIds.Add(UInt64.Parse(line.Substring(0, idx - 1))); // remove movieId and first quote from string line = line.Substring(idx + 1); // find the next quote idx = line.IndexOf('"'); // extract the movieTitle MovieTitles.Add(line.Substring(0, idx)); // remove title and last comma from the string line = line.Substring(idx + 2); // replace the "|" with ", " MovieGenres.Add(line.Replace("|", ", ")); } } sr.Close(); } catch (Exception ex) { logger.Error(ex.Message); } string choice; do { logger.Info("Movies in file {Count}", MovieIds.Count); // display choices to user Console.WriteLine("1) Add Movie"); Console.WriteLine("2) Display All Movies"); Console.WriteLine("Enter to quit"); // input selection choice = Console.ReadLine(); logger.Info("User choice: {Choice}", choice); if (choice == "1") { // Add Movie // ask user to input movie title Console.WriteLine("Enter the movie title"); // input title string movieTitle = Console.ReadLine(); // check for duplicate title List <string> LowerCaseMovieTitles = MovieTitles.ConvertAll(t => t.ToLower()); if (LowerCaseMovieTitles.Contains(movieTitle.ToLower())) { logger.Info("Duplicate movie title {Title}", movieTitle); } else { // generate movie id - use max value in MovieIds + 1 UInt64 movieId = MovieIds.Max() + 1; // input genres List <string> genres = new List <string>(); string genre; do { // ask user to enter genre Console.WriteLine("Enter genre (or done to quit)"); // input genre genre = Console.ReadLine(); // if user enters "done" // or does not enter a genre do not add it to list if (genre != "done" && genre.Length > 0) { genres.Add(genre); } } while (genre != "done"); // specify if no genres are entered if (genres.Count == 0) { genres.Add("(no genres listed)"); } // use "|" as delimeter for genres string genresString = string.Join("|", genres); // if there is a comma(,) in the title, wrap it in quotes movieTitle = movieTitle.IndexOf(',') != -1 ? $"\"{movieTitle}\"" : movieTitle; // create file from data StreamWriter sw = new StreamWriter(file, true); sw.WriteLine($"{movieId},{movieTitle},{genresString}"); sw.Close(); // add movie details to Lists MovieIds.Add(movieId); MovieTitles.Add(movieTitle); MovieGenres.Add(genresString); // log transaction logger.Info("Movie id {Id} added", movieId); } } else if (choice == "2") { // Display All Movies // loop thru Movie Lists for (int i = 0; i < MovieIds.Count; i++) { // display movie details Console.WriteLine($"Id: {MovieIds[i]}"); Console.WriteLine($"Title: {MovieTitles[i]}"); Console.WriteLine($"Genre(s): {MovieGenres[i]}"); Console.WriteLine(); } } } while (choice == "1" || choice == "2"); } logger.Info("Program ended"); }
public static void Main(string[] args) { NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger(); CreateHostBuilder(args).Build().Run(); }
static Program() { _logger = NLogBuilder.ConfigureNLog(@"Configs\nlog.config").GetCurrentClassLogger(); }
public ErrorLoggingMiddleware(RequestDelegate next) { logger = NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger(); _next = next; }
public NLogLogger(string name, string configFile) { _name = name; _configFile = configFile; _logger = NLogBuilder.ConfigureNLog(_configFile).GetLogger(name); }
public static void Main(string[] args) { // 设置读取指定位置的nlog.config文件 NLogBuilder.ConfigureNLog("Config/NLog.config"); CreateHostBuilder(args).Build().Run(); }
public ExampleService(ILogger logger) { this.logger = logger; this.classLogger = NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger(); }
private static void Main(string[] args) { NLogBuilder.ConfigureNLog("nlog.config"); ServicePointManager.DefaultConnectionLimit = 1; ThreadPool.GetMinThreads(out var a, out var b); Logger.Info($"Current threadpool min threads: worker={a}, completionPort={b}"); if (Environment.ProcessorCount > 0) { if (!ThreadPool.SetMinThreads(64 * Environment.ProcessorCount, 32 * Environment.ProcessorCount)) { throw new Exception("Failed to set minimum thread count"); } ThreadPool.GetMinThreads(out a, out b); Logger.Info($"New threadpool min threads: worker={a}, completionPort={b}"); } else { Logger.Warn("Failed to determine logical processeor count, threadpool threads unchanged"); } var scrapeConfig = ReadCoreConfig(out var readers); var scrapers = new Dictionary <string, SSHLogScraper>(); LoadScrapersConfig(scrapers, scrapeConfig, readers, Startup.Metrics); if (scrapeConfig.Script != null) { var loaderThread = new Thread(() => { while (true) { LoadFromScript(scrapers, scrapeConfig.Script, readers, Startup.Metrics); if (scrapeConfig.ReloadInterval.HasValue) { Thread.Sleep(TimeSpan.FromSeconds(scrapeConfig.ReloadInterval.Value)); } else { Thread.Sleep(-1); } } // ReSharper disable once FunctionNeverReturns }) { Name = "inventory-loader-thread" }; loaderThread.Start(); } WebHost.CreateDefaultBuilder(args) .UseStartup <Startup>() .UseKestrel(options => { options.ListenAnyIP(5000); }) .ConfigureLogging(logging => { logging.ClearProviders(); logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Information); }) .UseNLog() .Build() .Run(); // ReSharper disable once FunctionNeverReturns }
public static void Main(string[] args) { var logger = NLogBuilder.ConfigureNLog("NLog.config").GetCurrentClassLogger(); BuildWebHost(args).Run(); }
public Startup(IConfiguration configuration) { NLogBuilder.ConfigureNLog("nlog.config"); Configuration = configuration; }
static void Main(string[] args) { CommandLineApplication app = new CommandLineApplication(); app.HelpOption("-? | -h | --help"); var UserNameOption = app.Option( "-u | --username <USERNAME>", "The UserName to login to the Covenant API.", CommandOptionType.SingleValue ); var PasswordOption = app.Option( "-p | --password <PASSWORD>", "The Password to login to the Covenant API.", CommandOptionType.SingleValue ); var ComputerNameOption = app.Option( "-c | --computername <COMPUTERNAME>", "The ComputerName (IPAddress or Hostname) to bind the Covenant API to.", CommandOptionType.SingleValue ); app.OnExecute(() => { string username = UserNameOption.Value(); string password = PasswordOption.Value(); if (!UserNameOption.HasValue()) { Console.Write("Username: "******"Password: "******"0.0.0.0"; IPEndPoint CovenantEndpoint = new IPEndPoint(IPAddress.Parse(CovenantBindUrl), Common.CovenantHTTPSPort); string CovenantUri = (CovenantBindUrl == "0.0.0.0" ? "https://127.0.0.1:" + Common.CovenantHTTPSPort : "https://" + CovenantEndpoint); var host = BuildWebHost( CovenantEndpoint, CovenantUri, username, password ); using (var scope = host.Services.CreateScope()) { var services = scope.ServiceProvider; var context = services.GetRequiredService <CovenantContext>(); var userManager = services.GetRequiredService <UserManager <CovenantUser> >(); var roleManager = services.GetRequiredService <RoleManager <IdentityRole> >(); var configuration = services.GetRequiredService <IConfiguration>(); var cancellationTokens = services.GetRequiredService <Dictionary <int, CancellationTokenSource> >(); DbInitializer.Initialize(context, userManager, roleManager, configuration, cancellationTokens); } LoggingConfiguration loggingConfig = new LoggingConfiguration(); var consoleTarget = new ColoredConsoleTarget(); var fileTarget = new FileTarget(); loggingConfig.AddTarget("console", consoleTarget); loggingConfig.AddTarget("file", fileTarget); consoleTarget.Layout = @"${longdate}|${event-properties:item=EventId_Id}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}"; fileTarget.Layout = @"${longdate}|${event-properties:item=EventId_Id}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}"; fileTarget.FileName = Common.CovenantLogDirectory + "covenant.log"; loggingConfig.AddRule(NLog.LogLevel.Warn, NLog.LogLevel.Fatal, "console"); loggingConfig.AddRule(NLog.LogLevel.Debug, NLog.LogLevel.Fatal, "file"); var logger = NLogBuilder.ConfigureNLog(loggingConfig).GetCurrentClassLogger(); try { logger.Debug("Starting Covenant API"); host.Run(); } catch (Exception ex) { logger.Error(ex, "Covenant stopped due to exception"); throw; } finally { NLog.LogManager.Shutdown(); } return(0); }); app.Execute(args); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { var logger = NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger(); services.Configure <Settings> (options => { options.ConnectionString = Configuration.GetSection("MongoConnection:ConnectionString").Value; options.Database = Configuration.GetSection("MongoConnection:Database").Value; }); #region JWT services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, ValidateAudience = true, ValidateLifetime = false, ValidateIssuerSigningKey = true, NameClaimType = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier", ValidIssuer = $"{AppSettingsService.Configuration["AppSettings:Authentication:IssuserName"]}", ValidAudience = $"{AppSettingsService.Configuration["AppSettings:Authentication:AudienceName"]}", IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes($"{AppSettingsService.Configuration["AppSettings:Authentication:Secret"]}")), ClockSkew = TimeSpan.FromMinutes(5) //5 minute tolerance for the expiration date }; options.Events = new JwtBearerEvents { OnAuthenticationFailed = context => { logger.Error("OnAuthenticationFailed: " + context.Exception.Message); return(Task.CompletedTask); }, OnTokenValidated = context => { logger.Info("OnTokenValidated: " + context.SecurityToken); return(Task.CompletedTask); }, // We have to hook the OnMessageReceived event in order to // allow the JWT authentication handler to read the access // token from the query string when a WebSocket or // Server-Sent Events request comes in. OnMessageReceived = context => { var accessToken = context.Request.Query["access_token"]; // If the request is for our hub... var path = context.HttpContext.Request.Path; if (!string.IsNullOrEmpty(accessToken) && (path.StartsWithSegments("/chat"))) { // Read the token out of the query string context.Token = accessToken; } return(Task.CompletedTask); } }; }); services.AddCors(options => { options.AddPolicy("CorsPolicy", builder => builder .AllowAnyOrigin() .AllowAnyMethod() .AllowAnyHeader() .AllowCredentials() .SetPreflightMaxAge(TimeSpan.FromSeconds(2520)) .Build()); }); #endregion services.AddAutoMapper(); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); services.AddSignalR(o => { o.EnableDetailedErrors = true; }); services.AddSingleton <IMongoClient> (new MongoClient(Configuration.GetSection("MongoConnection:ConnectionString").Value)); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new Info { Title = "chatR API", Version = "v1" }); c.DescribeAllEnumsAsStrings(); c.AddSecurityDefinition("Bearer", new ApiKeyScheme { Description = "JWT Authorization header using the Bearer scheme. Example: \"Bearer {token}\"", Name = "Authorization", In = "header", Type = "apiKey" }); c.AddSecurityRequirement(new Dictionary <string, IEnumerable <string> > { { "Bearer", new string[] { } } }); }); #region DI services.AddTransient <ICipherService, CipherService> (); services.AddTransient <IGenerator, Generator> (); services.AddTransient <ITokenService, TokenService> (); services.AddTransient <IAuthenticationService, AuthenticationService> (); #endregion }
public static void Main(string[] args) { // NLog: setup the logger first to catch all errors var logger = NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger(); try { logger.Debug("init main"); CreateWebHostBuilder(args).Build().Run(); } catch (Exception ex) { //NLog: catch setup errors logger.Error(ex, "Stopped program because of exception"); throw; } finally { // Ensure to flush and stop internal timers/threads before application-exit (Avoid segmentation fault on Linux) NLog.LogManager.Shutdown(); } var webHost = CreateWebHostBuilder(args).Build(); using (var scope = webHost.Services.CreateScope()) { using (var db = scope.ServiceProvider.GetRequiredService <CalculatorDbContext>()) { var transaction = db.Database.BeginTransaction(); try { for (int i = 1; i <= 4; i++) { if (!db.Methods.Any(m => m.Id == i)) { db.Methods.Add(new Method { Id = i, INSERT_DATE = DateTime.Now, }); } } db.SaveChanges(); transaction.Commit(); } catch (Exception ex) { transaction.Rollback(); throw ex; } finally { transaction.Dispose(); } } } webHost.Run(); }
public YahooDataManager() { BR = new BaseRepository(); Logger = NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger(); }
static void Main(string[] args) { string path = Directory.GetCurrentDirectory() + "\\nlog.config"; // create instance of Logger var logger = NLogBuilder.ConfigureNLog(path).GetCurrentClassLogger(); logger.Info("Program started"); string file = "ml-latest-small/movies.csv"; string choice = ""; do { if (File.Exists(file)) { Console.WriteLine("1) Read moive data from file."); Console.WriteLine("2) Create new moive."); Console.WriteLine("Enter any other key to exit."); choice = Console.ReadLine(); //reading the moive data if (choice == "1") { StreamReader sr = new StreamReader(file); while (!sr.EndOfStream) { string display = ""; string moiveName = ""; string genres = ""; string[] genreList; string genreDisplay = ""; string line = sr.ReadLine(); string[] arr = line.Split(','); for (int i = 0; i < arr.Length - 2; i++) { if (i == 0) { moiveName = arr[i + 1]; } else { moiveName += "," + arr[i + 1]; } } genres = arr[arr.Length - 1]; // Console.WriteLine(genre); genreList = genres.Split("|"); for (int i = 0; i < genreList.Length; i++) { //this is to check the first one if (genreList.Length > 1 && i != genreList.Length - 1) { genreDisplay += genreList[i] + ", "; } else { genreDisplay += genreList[i]; } } display = "Id: " + arr[0] + " Title: " + moiveName + " Genres: " + genreDisplay; Console.WriteLine(display); } sr.Close(); } //creating a new moive else if (choice == "2") { string newMoive = ""; int genres; string lastId = ""; string moiveName = ""; Boolean isTitleDifferent = true; Console.WriteLine("Enter the Movie Title."); string userInput = Console.ReadLine(); //checking the name to make sure it isn't a duplicate and getting the last id StreamReader sr = new StreamReader(file); while (!sr.EndOfStream) { string line = sr.ReadLine(); string[] arr = line.Split(','); //this is to check the first one for (int i = 0; i < arr.Length - 2; i++) { if (i == 0) { moiveName = arr[i + 1]; } else { moiveName += "," + arr[i + 1]; } if (userInput == moiveName) { isTitleDifferent = false; } } // Console.WriteLine(arr); lastId = arr[0]; } sr.Close(); if (isTitleDifferent) { //starting to write the new moive StreamWriter sw = new StreamWriter(file, true); newMoive += (Convert.ToInt32(lastId) + 1) + ","; newMoive += userInput + ","; Console.WriteLine("How many genres are there for this movie?"); userInput = Console.ReadLine(); genres = Convert.ToInt32(userInput); if (genres == 0) { newMoive += "(no genres listed)"; } else { for (int j = 0; j < genres; j++) { Console.WriteLine("Enter a genres:"); userInput = Console.ReadLine(); newMoive += userInput; if (j != genres - 1) { newMoive += "|"; } } } Console.WriteLine(newMoive); sw.WriteLine(newMoive); sw.Close(); } else { logger.Warn("Error: There is already a moive wih that name"); } } } else { //if else check for file logger.Warn("File does not exist. {file}", file); } } while (choice == "1" || choice == "2"); logger.Info("Program ended"); }
public static void Main(string[] args) { NLogBuilder.ConfigureNLog("nlog.config"); CreateWebHostBuilder(args).Build().Run(); }
/// <summary> /// This method gets called by the runtime. Use this method to add services to the container. /// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 /// </summary> /// <param name="services">a collection of services that can be used throughout the lifecycle of the program</param> public void ConfigureServices(IServiceCollection services) { Logger logger = NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger(); JsonConvert.DefaultSettings = () => { JsonSerializerSettings settings = new JsonSerializerSettings(); settings.Converters.Add(new StringEnumConverter { CamelCaseText = true }); return(settings); }; // add config options services.AddOptions().BindConfiguration <Azure>(this.Configuration) .BindConfiguration <Bot>(this.Configuration).BindConfiguration <ConnectionStrings>(this.Configuration) .BindConfiguration <Data>(this.Configuration).BindConfiguration <Notify>(this.Configuration); // add & configure localization services.AddLocalization(options => options.ResourcesPath = "Resources") .Configure <RequestLocalizationOptions>( options => { var supportedCultures = new[] { new CultureInfo("en-GB") }; options.DefaultRequestCulture = new RequestCulture("en-GB"); options.SupportedCultures = supportedCultures; options.SupportedUICultures = supportedCultures; }); // add services services.AddSingleton <IApprenticeFeedbackResources, ApprenticeFeedbackResourcesV3>() .AddTransient <IApprenticeFeedbackSurvey, ApprenticeFeedbackV3>() .AddSingleton <IDialogFactory <DialogSet>, BotDialogFactory>() .AddSingleton <IConversationLogMiddleware, CosmosConversationLog>() .AddSingleton <ISmsRelayMiddleware, AzureStorageQueueSmsRelay>(); // add & configure bot framework services.AddBot <FeedbackBot>( options => { options.CredentialProvider = new ConfigurationCredentialProvider(this.Configuration); // The CatchExceptionMiddleware provides a top-level exception handler for your bot. // Any exceptions thrown by other Middleware, or by your OnTurn method, will be // caught here. To facilitate debugging, the exception is sent out, via Trace, // to the emulator. Trace activities are NOT displayed to users, so in addition // an "Oops" message is sent. options.Middleware.Add( new CatchExceptionMiddleware <Exception>( async(context, exception) => { await context.TraceActivity($"{nameof(FeedbackBot)} Exception", exception); logger.Error(exception, $"{nameof(FeedbackBot)} Exception"); await context.SendActivity(exception.Message); })); // The Memory Storage used here is for local bot debugging only. When the bot // is restarted, anything stored in memory will be gone. // IStorage dataStore = new MemoryStorage(); // The File data store, shown here, is suitable for bots that run on // a single machine and need durable state across application restarts. // IStorage dataStore = new FileStorage(System.IO.Path.GetTempPath()); // For production bots use the Azure Table Store, Azure Blob, or // Azure CosmosDB storage provides, as seen below. To include any of // the Azure based storage providers, add the Microsoft.Bot.Builder.Azure // Nuget package to your solution. That package is found at: // https://www.nuget.org/packages/Microsoft.Bot.Builder.Azure/ // IStorage dataStore = new AzureTableStorage(Configuration.GetConnectionString("StorageAccount"), "ApprenticeFeedbackBotSessions"); // TODO: build a bot middleware factory IStorage dataStore = ConfigureStateDataStore(this.Configuration); options.Middleware.Add(new ConversationState <SurveyState>(dataStore)); options.Middleware.Add(new UserState <UserState>(dataStore)); options.Middleware.Add <IConversationLogMiddleware>(services); options.Middleware.Add <ISmsRelayMiddleware>(services); }); }
public Startup(IHostingEnvironment env) { _env = env; _logger = NLogBuilder.ConfigureNLog($"{_env.ContentRootPath}/nlog.config").GetCurrentClassLogger(); }
public static void Main(string[] args) { NLogBuilder.ConfigureNLog("NLog.config"); BuildWebHost(args).Run(); }
public static void Main(string[] args) { // NLog: setup the logger first to catch all errors var logger = NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger(); try { NLog.LogManager.LoadConfiguration("nlog.config"); Options commandOptions = null; try { Parser.Default.ParseArguments <Options>(args) .WithParsed(o => { commandOptions = o; }) .WithNotParsed(e => { HandleParseError(e, logger); }); SettingsPath = commandOptions.SettingsPath; } catch (Exception ex) { logger.Error("Failed to parse command line arguments " + ex.ToString()); Shutdown(ShutdownCodes.SettingsParseError); } logger.Info("Initialized Main"); if (!File.Exists(SettingsPath)) { logger.Info("Creating settings at: " + SettingsPath); File.WriteAllText(SettingsPath, Newtonsoft.Json.JsonConvert.SerializeObject(new Models.VSettings(), Newtonsoft.Json.Formatting.Indented)); } WriteoutSchema(SettingsPath); var settings = Newtonsoft.Json.JsonConvert.DeserializeObject <Models.VSettings>(File.ReadAllText(SettingsPath), new Newtonsoft.Json.JsonSerializerSettings() { ObjectCreationHandling = Newtonsoft.Json.ObjectCreationHandling.Replace }); foreach (var library in settings.Libraries) { if (library.SourceHandling.ToLowerInvariant() == "delete" && library.DeleteWithSource) { logger.Warn($"Library {library.Name} is set to SourceHandling:delete and DeleteWithSource:true. This is allowed, but is atypical."); } } // Exit if this is a bootstrap run. if (commandOptions != null && commandOptions.Bootstrap) { logger.Info("This was just a bootstrapping run. Exiting..."); Shutdown(ShutdownCodes.Bootstrap); } CreateWebHostBuilder(args, $"http://{settings.Listen}:{settings.Port}") .Build() .Run(); } catch (Exception ex) { logger.Error(ex, "Top level exception caught. Terminating application."); Shutdown(ShutdownCodes.GeneralError); } }
public LoggerServiceBase(string name) { LayoutRenderer.Register("CustomJson", typeof(CustomJsonLayoutRenderer)); _logger = NLogBuilder.ConfigureNLog("nlog.config").GetLogger(name); }
static void Main(string[] args) { CommandLineApplication app = new CommandLineApplication(); app.HelpOption("-? | -h | --help"); var UserNameOption = app.Option( "-u | --username <USERNAME>", "The UserName to login to the Covenant API.", CommandOptionType.SingleValue ); var PasswordOption = app.Option( "-p | --password <PASSWORD>", "The Password to login to the Covenant API.", CommandOptionType.SingleValue ); var ComputerNameOption = app.Option( "-c | --computername <COMPUTERNAME>", "The ComputerName (IPAddress or Hostname) to bind the Covenant API to.", CommandOptionType.SingleValue ); app.OnExecute(() => { if (!File.Exists(Path.Combine(Common.CovenantSharpSploitDirectory, "SharpSploit.sln")) || !File.Exists(Path.Combine(Common.CovenantRubeusDirectory, "Rubeus.sln"))) { Console.Error.WriteLine("Error: git submodules have not been initialized"); Console.Error.WriteLine("Covenant's submodules can be cloned with: git clone --recurse-submodules https://github.com/cobbr/Covenant"); Console.Error.WriteLine("Or initialized after cloning with: git submodule update --init --recursive"); return(-1); } string username = UserNameOption.Value(); string password = ""; if (UserNameOption.HasValue() && !PasswordOption.HasValue()) { Console.Write("Password: "******"0.0.0.0"; IPAddress address = null; try { address = IPAddress.Parse(CovenantBindUrl); } catch (FormatException) { address = Dns.GetHostAddresses(CovenantBindUrl).FirstOrDefault(); } IPEndPoint CovenantEndpoint = new IPEndPoint(address, Common.CovenantHTTPSPort); string CovenantUri = (CovenantBindUrl == "0.0.0.0" ? "https://127.0.0.1:" + Common.CovenantHTTPSPort : "https://" + CovenantEndpoint); var host = BuildWebHost(CovenantEndpoint, CovenantUri); using (var scope = host.Services.CreateScope()) { var services = scope.ServiceProvider; var context = services.GetRequiredService <CovenantContext>(); var userManager = services.GetRequiredService <UserManager <CovenantUser> >(); var signInManager = services.GetRequiredService <SignInManager <CovenantUser> >(); var roleManager = services.GetRequiredService <RoleManager <IdentityRole> >(); var configuration = services.GetRequiredService <IConfiguration>(); var listenerTokenSources = services.GetRequiredService <ConcurrentDictionary <int, CancellationTokenSource> >(); context.Database.EnsureCreated(); DbInitializer.Initialize(context, roleManager, listenerTokenSources).Wait(); if (!context.Users.Any() && UserNameOption.HasValue() && !string.IsNullOrEmpty(password)) { // TODO: create user CovenantUser user = new CovenantUser { UserName = UserNameOption.Value() }; Task <IdentityResult> task = userManager.CreateAsync(user, password); task.Wait(); IdentityResult userResult = task.Result; if (userResult.Succeeded) { Task t = userManager.AddToRoleAsync(user, "User"); t.Wait(); Task t2 = userManager.AddToRoleAsync(user, "Administrator"); t2.Wait(); } else { Console.Error.WriteLine($"Error creating user: {user.UserName}"); return(-1); } } } LoggingConfiguration loggingConfig = new LoggingConfiguration(); var consoleTarget = new ColoredConsoleTarget(); var fileTarget = new FileTarget(); loggingConfig.AddTarget("console", consoleTarget); loggingConfig.AddTarget("file", fileTarget); consoleTarget.Layout = @"${longdate}|${event-properties:item=EventId_Id}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}"; fileTarget.Layout = @"${longdate}|${event-properties:item=EventId_Id}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}"; fileTarget.FileName = Common.CovenantLogDirectory + "covenant.log"; loggingConfig.AddRule(NLog.LogLevel.Info, NLog.LogLevel.Fatal, "console"); loggingConfig.AddRule(NLog.LogLevel.Info, NLog.LogLevel.Fatal, "file"); var logger = NLogBuilder.ConfigureNLog(loggingConfig).GetCurrentClassLogger(); try { logger.Debug("Starting Covenant API"); host.Run(); } catch (Exception ex) { logger.Error(ex, "Covenant stopped due to exception"); throw; } finally { NLog.LogManager.Shutdown(); } return(0); }); app.Execute(args); }
public LoggerManager(IHostingEnvironment environment) { _logger = NLogBuilder.ConfigureNLog(Path.Combine(environment.ContentRootPath, "nlog.config")).GetCurrentClassLogger(); }
private NLogger() { nLogger = NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger(); }
protected override void LoadLoggingConfiguration(string path) { NLogBuilder.ConfigureNLog(path); }
static void Main(string[] args) { CommandLineApplication app = new CommandLineApplication(); app.HelpOption("-? | -h | --help"); var UserNameOption = app.Option( "-u | --username <USERNAME>", "The initial user UserName to create on launch. (env: COVENANT_USERNAME)", CommandOptionType.SingleValue ); var PasswordOption = app.Option( "-p | --password <PASSWORD>", "The initial user Password to create on launch. (env: COVENANT_PASSWORD)", CommandOptionType.SingleValue ); var ComputerNameOption = app.Option( "-c | --computername <COMPUTERNAME>", "The ComputerName (IPAddress or Hostname) to bind Covenant to. (env: COVENANT_COMPUTER_NAME)", CommandOptionType.SingleValue ); var AdminPortOption = app.Option( "-a | --adminport <PORT>", "The Port number to bind Covenant to. (env: COVENANT_PORT)", CommandOptionType.SingleValue ); app.OnExecute(() => { if (Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") == "Development" && (!File.Exists(Path.Combine(Common.CovenantSharpSploitDirectory, "SharpSploit.sln")) || !File.Exists(Path.Combine(Common.CovenantRubeusDirectory, "Rubeus.sln")))) { Console.Error.WriteLine("Error: git submodules have not been initialized"); Console.Error.WriteLine("Covenant's submodules can be cloned with: git clone --recurse-submodules https://github.com/cobbr/Covenant"); Console.Error.WriteLine("Or initialized after cloning with: git submodule update --init --recursive"); return(-1); } string username = UserNameOption.HasValue() ? UserNameOption.Value() : Environment.GetEnvironmentVariable("COVENANT_USERNAME"); string password = PasswordOption.HasValue() ? PasswordOption.Value() : Environment.GetEnvironmentVariable("COVENANT_PASSWORD"); if (!string.IsNullOrEmpty(username) && string.IsNullOrEmpty(password)) { Console.Write("Password: "******"COVENANT_COMPUTER_NAME");; if (string.IsNullOrEmpty(CovenantBindUrl)) { CovenantBindUrl = "0.0.0.0"; } int CovenantPort = Common.CovenantDefaultAdminPort; string sPort = AdminPortOption.HasValue() ? AdminPortOption.Value() : Environment.GetEnvironmentVariable("COVENANT_PORT"); if (!string.IsNullOrEmpty(sPort) && !int.TryParse(sPort, out CovenantPort)) { CovenantPort = Common.CovenantDefaultAdminPort; } IPAddress address = null; try { address = IPAddress.Parse(CovenantBindUrl); } catch (FormatException) { address = Dns.GetHostAddresses(CovenantBindUrl).FirstOrDefault(); } IPEndPoint CovenantEndpoint = new IPEndPoint(address, CovenantPort); string CovenantUri = CovenantBindUrl == "0.0.0.0" ? "https://127.0.0.1:" + CovenantPort : "https://" + CovenantEndpoint; var host = BuildHost(CovenantEndpoint, CovenantUri); using (var scope = host.Services.CreateScope()) { var services = scope.ServiceProvider; var context = services.GetRequiredService <CovenantContext>(); var service = services.GetRequiredService <ICovenantService>(); var userManager = services.GetRequiredService <UserManager <CovenantUser> >(); var signInManager = services.GetRequiredService <SignInManager <CovenantUser> >(); var roleManager = services.GetRequiredService <RoleManager <IdentityRole> >(); var configuration = services.GetRequiredService <IConfiguration>(); configuration["CovenantPort"] = CovenantPort.ToString(); var listenerTokenSources = services.GetRequiredService <ConcurrentDictionary <int, CancellationTokenSource> >(); context.Database.EnsureCreated(); DbInitializer.Initialize(service, context, roleManager, listenerTokenSources).Wait(); CovenantUser serviceUser = new CovenantUser { UserName = "******" }; if (!context.Users.Any()) { string serviceUserPassword = Utilities.CreateSecretPassword() + "A"; userManager.CreateAsync(serviceUser, serviceUserPassword).Wait(); userManager.AddToRoleAsync(serviceUser, "ServiceUser").Wait(); if (!string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(password)) { CovenantUser user = new CovenantUser { UserName = username }; Task <IdentityResult> task = userManager.CreateAsync(user, password); task.Wait(); IdentityResult userResult = task.Result; if (userResult.Succeeded) { userManager.AddToRoleAsync(user, "User").Wait(); userManager.AddToRoleAsync(user, "Administrator").Wait(); } else { Console.Error.WriteLine($"Error creating user: {user.UserName}"); return(-1); } } } configuration["ServiceUserToken"] = Utilities.GenerateJwtToken( serviceUser.UserName, serviceUser.Id, new string[] { "ServiceUser" }, configuration["JwtKey"], configuration["JwtIssuer"], configuration["JwtAudience"], configuration["JwtExpireDays"] ); } LoggingConfiguration loggingConfig = new LoggingConfiguration(); var consoleTarget = new ColoredConsoleTarget(); var fileTarget = new FileTarget(); loggingConfig.AddTarget("console", consoleTarget); loggingConfig.AddTarget("file", fileTarget); consoleTarget.Layout = @"${longdate}|${event-properties:item=EventId_Id}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}"; fileTarget.Layout = @"${longdate}|${event-properties:item=EventId_Id}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}"; fileTarget.FileName = Common.CovenantLogDirectory + "covenant.log"; loggingConfig.AddRule(NLog.LogLevel.Info, NLog.LogLevel.Fatal, "console"); loggingConfig.AddRule(NLog.LogLevel.Info, NLog.LogLevel.Fatal, "file"); var logger = NLogBuilder.ConfigureNLog(loggingConfig).GetCurrentClassLogger(); try { logger.Debug("Starting Covenant API"); if (!IsElevated()) { Console.Error.WriteLine("WARNING: Running Covenant non-elevated. You may not have permission to start Listeners on low-numbered ports. Consider running Covenant elevated."); } Console.WriteLine($"Covenant has started! Navigate to {CovenantUri} in a browser"); host.Run(); } catch (Exception ex) { logger.Error(ex, "Covenant stopped due to exception"); throw; } finally { NLog.LogManager.Shutdown(); } return(0); }); app.Execute(args); }
public PerfilesController(PAPW2DbContext db) { this.db = db; logger = NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger(); }
static Log() { _transactionlogFormatter = new TransactionLogFormatter(); _exceptionFormatter = new ExceptionFormatter(); Logger = NLogBuilder.ConfigureNLog("NLog.config").GetLogger("DotNetCore.API.Logging"); }
public async Task InvokeAsync(HttpContext context) { Logger _logger = NLogBuilder.ConfigureNLog("NLog.config").GetCurrentClassLogger(); Log log = new Log { Path = context.Request.Path, Method = context.Request.Method, QueryString = context.Request.QueryString.ToString() }; if (context.Request.Method == HttpMethods.Post) { context.Request.EnableBuffering(); string body = await new StreamReader(context.Request.Body) .ReadToEndAsync(); context.Request.Body.Position = 0; log.Payload = body; } log.RequestedOn = DateTime.Now; await _next.Invoke(context); using (Stream originalRequest = context.Response.Body) { try { using (var memStream = new MemoryStream()) { context.Response.Body = memStream; memStream.Position = 0; var response = await new StreamReader(memStream) .ReadToEndAsync(); log.Response = response; log.ResponseCode = context.Response.StatusCode.ToString(); log.IsSuccessStatusCode = ( context.Response.StatusCode == 200 || context.Response.StatusCode == 201); log.RespondedOn = DateTime.Now; JsonSerializerOptions options = new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase }; string json = JsonSerializer.Serialize(log, options); _logger.Debug(json); memStream.Position = 0; await memStream.CopyToAsync(originalRequest); } } catch (Exception ex) { _logger.Error(ex, ex.Message); } finally { context.Response.Body = originalRequest; } } }