public static QueryBoostingContext Load(string fileName, ILoader loader, FrameworkLogger logger)
        {
            try
            {
                using (var reader = loader.GetReader(fileName))
                {
                    var serializer = new JsonSerializer();

                    var value = serializer.Deserialize<QueryBoostingContext>(reader);

                    return value;
                }
            }
            catch (Exception ex)
            {
                if (IndexingUtils.IsFatal(ex))
                {
                    throw;
                }

                logger.LogError($"Unable to load {fileName}.", ex);
            }

            return Default;
        }
 public StorageLoader(CloudStorageAccount storageAccount, string containerName, FrameworkLogger logger)
 {
     logger.LogInformation("StorageLoader container: {ContainerName}", containerName);
     _storageAccount = storageAccount;
     _containerName = containerName;
     _logger = logger;
 }
 internal OwinLogger(Microsoft.Extensions.Logging.ILogger logger) 
 {
     if (logger == null)
     {
         throw new ArgumentNullException(nameof(logger));   
     }
     
     _logger = logger;
 }
示例#4
0
文件: Startup.cs 项目: eaardal/slydr
        public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddSerilog();
            _log = loggerFactory.CreateLogger("slydr");

            app.UseIISPlatformHandler();

            app.UseMvc();
        }
        public async Task WriteResponseAsync(IOwinContext context, Exception e, FrameworkLogger logger)
        {
            logger.LogError("Internal server error", e);

            await WriteResponseAsync(context, HttpStatusCode.InternalServerError, JObject.FromObject(new
            {
                error = "Internal server error",
                httpRequestId = context.Get<string>(CorrelationIdMiddleware.CorrelationIdHeaderKey)
            }));
        }
		public StoreController(
			ILoggerFactory loggerfactory, 
			IServiceProvider serviceProvider,
			IGenreQueryService genreQueryService,
			IAlbumQueryService albumQueryService)
		{
			_serviceProvider = serviceProvider;
			_genreQueryService = genreQueryService;
			_albumQueryService = albumQueryService;
			_logger = loggerfactory.CreateLogger(nameof(StoreController));
		}
        public void Load(string name, ILoader loader, FrameworkLogger logger)
        {
            // The data in downloads.v1.json will be an array of Package records - which has Id, Array of Versions and download count.
            // Sample.json : [["AutofacContrib.NSubstitute",["2.4.3.700",406],["2.5.0",137]],["Assman.Core",["2.0.7",138]]....
            using (var jsonReader = loader.GetReader(name))
            {
                try
                {
                    jsonReader.Read();

                    while (jsonReader.Read())
                    {
                        try
                        {
                            if (jsonReader.TokenType == JsonToken.StartArray)
                            {
                                JToken record = JToken.ReadFrom(jsonReader);
                                string id = String.Intern(record[0].ToString().ToLowerInvariant());

                                // The second entry in each record should be an array of versions, if not move on to next entry.
                                // This is a check to safe guard against invalid entries.
                                if (record.Count() == 2 && record[1].Type != JTokenType.Array)
                                {
                                    continue;
                                }

                                if (!_downloads.ContainsKey(id))
                                {
                                    _downloads.Add(id, new DownloadsByVersion());
                                }
                                var versions = _downloads[id];

                                foreach (JToken token in record)
                                {
                                    if (token != null && token.Count() == 2)
                                    {
                                        string version = String.Intern(token[0].ToString().ToLowerInvariant());
                                        versions[version] = token[1].ToObject<int>();
                                    }
                                }
                            }
                        }
                        catch (JsonReaderException ex)
                        {
                            logger.LogInformation("Invalid entry found in downloads.v1.json. Exception Message : {0}", ex.Message);
                        }
                    }
                }
                catch (JsonReaderException ex)
                {
                    logger.LogError("Data present in downloads.v1.json is invalid. Couldn't get download data.", ex);
                }
            }
        }
		public ShoppingCartController(
			ILoggerFactory loggerfactory,
			IServiceProvider serviceProvider,
			IAlbumQueryService albumQueryService,
            ICartQueryService cartQueryService,
            ICartCommandService cartCommandService)
		{
			_serviceProvider = serviceProvider;
			_albumQueryService = albumQueryService;
		    _cartQueryService = cartQueryService;
		    _cartCommandService = cartCommandService;
		    _logger = loggerfactory.CreateLogger(nameof(StoreController));
		}
示例#9
0
        public ControllerBase(HttpContext httpContext, IDataProvider provider)
        {
            HttpContext = httpContext;
            Provider = provider;

            var loggingFactory = (ILoggerFactory)HttpContext.ApplicationServices.GetService(typeof (ILoggerFactory));
            if(loggingFactory != null)
                Logger = loggingFactory.CreateLogger(GetType().Name);

            var libraryManager = (ILibraryManager) HttpContext.ApplicationServices.GetService(typeof (ILibraryManager));
            if (libraryManager != null)
                LibraryManager = libraryManager;
        }
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            // add NLog for logging
            loggerFactory.AddNLog(new LogFactory(new NLog.Config.XmlLoggingConfiguration(logConfigurationFile)));
            _log = loggerFactory.CreateLogger<Startup>();

            // generate some log output
            _log.LogInformation("Happy table logging!");
            _log.LogInformation(string.Format("Log configuration: {0}", logConfigurationFile));

            app.UseIISPlatformHandler();

            app.Run(async (context) =>
            {
                await context.Response.WriteAsync("Hello World!");
            });
        }
        public Program()
        {
            Log.Logger = new LoggerConfiguration()
                .MinimumLevel.Debug()
#if DNXCORE50
                .WriteTo.TextWriter(Console.Out)
#else
                .Enrich.WithMachineName()
                .Enrich.WithProcessId()
                .Enrich.WithThreadId()
                .WriteTo.ColoredConsole()
#endif
                .CreateLogger();

            _logger = new LoggerFactory()
                .AddSerilog()
                .CreateLogger(typeof(Program).FullName);
        }
        public static void Load(string name, ILoader loader, FrameworkLogger logger, IDictionary<string, HashSet<string>> targetDictionary)
        {
            try
            {
                using (var jsonReader = loader.GetReader(name))
                {
                    UpdateDictionary(jsonReader, targetDictionary);
                }
            }
            catch (Exception e)
            {
                if (IsFatal(e))
                {
                    throw;
                }

                logger.LogError($"Unable to load {name}.", e);
            }
        }
        public static IReadOnlyDictionary<string, int> Load(string name, ILoader loader, FrameworkLogger logger)
        {
            try
            {
                using (JsonReader jsonReader = loader.GetReader(name))
                {
                    return CreateDictionary(jsonReader);
                }
            }
            catch (Exception e)
            {
                if (IndexingUtils.IsFatal(e))
                {
                    throw;
                }

                logger.LogInformation("Unable to load {0}. Exception Message : {1}", name, e.Message);

                return new Dictionary<string, int>();
            }
        }
示例#14
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        // Configure is called after ConfigureServices is called.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            //loggerFactory.MinimumLevel = LogLevel.Information;
            // root min level: you have to set this the most detailed, because if not ASPlog will not pass it to the NLogExtension
            loggerFactory.MinimumLevel = Microsoft.Extensions.Logging.LogLevel.Debug;

            // A. ASP.NET5 LogLevels can come from appsettings.json or set here programmatically. But Configuration.GetSection("") returns text from the file,
            // and not the file itself, so ConsoleLogger is not able to reload config when appsettings.json file is changed.
            // For that you need a FileSystem watcher manually, which is not OK on Linux systems I guess or not on DNXCore
            // Therefore logging level cannot be changed by modifying that file (at least, not without extra FileSystemWatcher programming)
            // B. On the other hand Nlog is based on DNX, not DNXCore, and implements FileSystemWatcher properly, and I tested it and
            // when the app.nlog file is changed by Notepad nLog under Asp.NET notices the LogLevelChange.
            loggerFactory.AddConsole(Configuration.GetSection("LoggingToConsole"));
            //loggerFactory.AddConsole(LogLevel.Debug);     // write to the Console  (if available) window as Colorful multiline (in Kestrel??) . MinLevel can be specified. by default it is LogLevel.Information
            loggerFactory.AddDebug(Microsoft.Extensions.Logging.LogLevel.Debug);       // write to the Debug output window (in VS). MinLevel can be specified. by default it is LogLevel.Information
            #if !DNXCORE50
            #if NlogInternalLoggingNeeded
            // nLog searches these config files in GetCandidateFileNames() (version nLog 3.1), later renamed to GetCandidateConfigFileNames()
            // NLog.config from application directory, "C:\\Users\\gyantal\\.dnx\\runtimes\\dnx-clr-win-x86.1.0.0-rc1-update1\\bin\\NLog.config"
            string standardCandidate = Path.Combine(NLog.LogFactory.CurrentAppDomain.BaseDirectory, "NLog.config");   // myExeFolder/Nlog.config
            // current config file with (EXE) .config renamed to .nlog, "g:\\work\\Archi-data\\GitHubRepos\\SQHealthMonitor\\src\\SQHealthMonitor\\app.nlog"
            string appDotNlog = Path.ChangeExtension(NLog.LogFactory.CurrentAppDomain.ConfigurationFile, ".nlog"); //myExeFolder/MyExe
            // get path to NLog.dll.nlog only if the assembly is not in the GAC, "C:\\Users\\gyantal\\.dnx\\packages\\NLog\\4.2.2\\lib\\net45\\NLog.dll.nlog"
            string dllDotNlog = typeof(NLog.LogFactory).Assembly.Location + ".nlog";

            NLog.Common.InternalLogger.LogLevel = NLog.LogLevel.Trace;  // this sets up from the default highLevel Info to detailed Trace; in order for Internal NLog logging to be Verbose
            NLog.Common.InternalLogger.LogToConsole = true;
            NLog.Common.InternalLogger.LogFile = @"g:\temp\nlogKestrel_InternalLogger.log";
            #endif
            //NLog.ILogger tempNlogLogger = LogManager.GetCurrentClassLogger();   //https://github.com/nlog/NLog/wiki/Configuration-file
            //SetNLogTableStorageConnectionString();
            //// when nlog.config is rewritten while the exe is running, AzureTableStorageConnectionString is lost
            //LogManager.ConfigurationReloaded += (sender, args) => { SetNLogTableStorageConnectionString(); };
            //tempNlogLogger.Info("This Logger created by LogManager() works properly under ASP.NET5. Writes proper AzuteStorageTable");

            //During Webserver runtime(Debugging in VS), file modification of app.nlog should not be done in VS2015, because
            //VS has a trick that it doesn't change file's Time under Debug, and so NLog.dll will not notice that this config file has been changed.
            //So, change this config file in NotePad.exe or TotalCommander, etc.
            NLog.LogFactory nlogLogFactory = new global::NLog.LogFactory();
            SetNLogTableStorageConnectionStringAndEmailSmtp(nlogLogFactory);
            // when nlog.config is rewritten while the exe is running, AzureTableStorageConnectionString is lost
            nlogLogFactory.ConfigurationReloaded += (sender, args) => { SetNLogTableStorageConnectionStringAndEmailSmtp(nlogLogFactory); };

            loggerFactory.AddProvider(new NLogLoggerProvider(nlogLogFactory));

            //nlogLogFactory.ConfigurationReloaded += (sender, args) => { SetNLogTableStorageConnectionString(); };
            //loggerFactory.AddNLog(nlogLogFactory);

            //loggerFactory.AddEventLog();  // probably Windows Eventlogs, implemented in Microsoft.Extensions.Logging.EventLog

            System.AppDomain.CurrentDomain.DomainUnload += (sender, args) => {
                Thread.Sleep(1);
                nlogLogFactory.Flush();
                LogManager.Flush();
            };
            System.AppDomain.CurrentDomain.ProcessExit += (sender, args) => {
                //Checked: when I shutdown the Webserver, by typing Ctrl-C, saying Initiate Webserver shutdown, this is called second after calling Dispose() of all IDispose objects
                Thread.Sleep(1);
                nlogLogFactory.Flush();
                LogManager.Flush();
            };
            System.AppDomain.CurrentDomain.UnhandledException += (sender, args) => {
                Thread.Sleep(1);
                nlogLogFactory.Flush();
                LogManager.Flush();
            };
            #endif

            mStartupLogger = loggerFactory.CreateLogger(typeof(Program).FullName);
            mStartupLogger.LogInformation("****START: Loggers are initialized in Startup.Configure()"); // high Level UserInfo
            #if !DNXCORE50

            ////Logger = LogManager.GetCurrentClassLogger();   //https://github.com/nlog/NLog/wiki/Configuration-file
            //SetNLogTableStorageConnectionString();
            //// when nlog.config is rewritten while the exe is running, AzureTableStorageConnectionString is lost
            //LogManager.ConfigurationReloaded += (sender, args) => { SetNLogTableStorageConnectionString(); };

            //var mStartupLogger2 = loggerFactory.CreateLogger(typeof(Program).FullName + "2");
            //mStartupLogger2.LogInformation("****creating mStartupLogger2 after setting ConnString."); // high Level UserInfo
            #endif

            //gStartupLogger.LogDebug("This is LogDebug() log info");  // most detailed, Trace in nLog
            //gStartupLogger.LogVerbose("This is LogVerbose() log info");  // normal-detailed, Debug in nLog
            //gStartupLogger.LogInformation("This is LogInformation() log info"); // high Level UserInfo

            // Add the platform handler to the request pipeline.
            app.UseIISPlatformHandler();    // : it is needed to resolve the Windows identity corresponding to the token flowed by IIS.

            if (env.IsDevelopment())
            {
                //app.UseDeveloperExceptionPage();
            }

            //Utils.InitSt();
            // Agy: I think this ASP5 solution is token based too. Just stores token in Cookies, which is perfect for a Browser based app like AngularJS
            //A. Conclusion: Storage user-token(not proper bearer token, but token) in cookies is good (in an AngularJS webApp, cookie storage is ideal.)
            //https://stormpath.com/blog/where-to-store-your-jwts-cookies-vs-html5-web-storage/
            //Conclusion: "Stormpath recommends that you store your JWT in cookies for web applications, because of the additional security they provide, and the simplicity of protecting against CSRF with modern web frameworks. HTML5 Web Storage (from here to Authentication Header) is vulnerable to XS"
            //> Basically, the caller of webServiceApi has to provide the userInfo.So, it has to store somewhere.
            //This article says: always use JWT Tokens. (ASP5 uses that, because it always send the full user info in the Cookies)
            //0.Browser based: Storing in Browser RAM in Javascript variable (from here to the "HTML Authentication header") is not good.Restart Browser Tab/Refresh will result => use has to log-in again.
            //1.Browser based: HTML5 WebStorage and from here to the "HTML Authentication header"
            //2.Browser based: cookie storage persistent too. Better.
            //3.Native App based: store in App memory, or in a file, etc. however you want.And use "HTML Authentication header" with the tokens.
            //B. ASP5 don't support yet the proper bearer tokens, but it doesn't matter.
            //https://en.wikipedia.org/wiki/Basic_access_authentication
            //https://developers.google.com/gmail/markup/actions/verifying-bearer-tokens
            //Bearer Tokens are part of the OAuth V2 standard and widely adopted by Google APIs.
            //// Agy: They will support it later. For now, I should forget it.
            //https://github.com/aspnet/Identity/search?q=Bearer&type=Issues&utf8=%E2%9C%93
            //https://github.com/aspnet/Identity/issues/495
            //In case anyone needs bearer tokens earlier.Basic example of Identity with Bearer tokens.
            //https://github.com/bigfont/AspNet.Security.OpenIdConnect.Server/tree/bigfont/samples/ResourceOwnerPasswordFlow
            //Probably later, this is a style how you should do it (for API calls, user-data should come from HTML header, from Browser user data should come from Cookie:
            //app.UseWhen(context => context.Request.Path.StartsWithSegments(new PathString("/api")), branch =>
            //{ branch.UseOAuthBearerAuthentication(options =>

            //string cId = Configuration["A:G:CId"], cSe = Configuration["A:G:CSe"];
            //string cId = Configuration["AppSettings:A_G_CId"], cSe = Configuration["AppSettings:A_G_CSe"];
            string cId = Configuration["A_G_CId"], cSe = Configuration["A_G_CSe"];
            if (!String.IsNullOrEmpty(cId) && !String.IsNullOrEmpty(cSe))
            {
                mStartupLogger.LogInformation("A_G_CId and A_G_CSe from Config has been found. Initializing GoogelAuthentication.");
                app.UseCookieAuthentication(options =>
                {
                    //options.LoginPath = "/account/login";
                    options.AuthenticationScheme = "Cookies";
                    options.AutomaticAuthenticate = true;
                    //options.ExpireTimeSpan = TimeSpan.FromMinutes(5);
                    options.ExpireTimeSpan = TimeSpan.FromDays(10);
                    options.SlidingExpiration = false;
                });

                //// from official sample; name suggest it is token based, albeit it is not named Bearer; feeling: app.UseCookieAuthentication() is exactly this
                //app.UseOAuthAuthentication("Google-AccessToken", options =>
                //{
                //    options.AuthenticationScheme = "Google-AccessToken";
                //    //options.DisplayName = "Google-AccessToken",
                //    options.ClientId = Utils.g_YmVsYUJlbG92aXRz[0];
                //    options.ClientSecret = Utils.g_YmVsYUJlbG92aXRz[1];
                //    options.CallbackPath = new PathString("/signin-google-token");
                //    options.AuthorizationEndpoint = GoogleAuthenticationDefaults.AuthorizationEndpoint;
                //    options.TokenEndpoint = GoogleAuthenticationDefaults.TokenEndpoint;
                //    options.Scope.Add("https://www.googleapis.com/auth/plus.profile.emails.read");
                //});

                // this is from the official GitHub sample https://github.com/aspnet/Identity/blob/b9be30c6cdf055394eb5ca9cd95d02419fcdf4b4/samples/IdentitySample.Mvc/Startup.cs
                app.UseGoogleAuthentication(options =>
                {
                    options.ClientId = Encoding.UTF8.GetString(Convert.FromBase64String(cId));
                    options.ClientSecret = Encoding.UTF8.GetString(Convert.FromBase64String(cSe));

                    //options.SignInScheme = null; // by default, which doesn't work itself. It needs UseCookieAuthentication()
                    //options.SignInScheme = "Google-AccessToken"; // 2015-10-02: "System.NotSupportedException"; I guess later they will support it
                    options.SignInScheme = "Cookies";
                    options.AutomaticAuthenticate = true;  // this is false by default; if it is true, all [Authorize] Actions try to log-in to Google

                    // don't touch CallbackPath then: The CallbackPath is the google middleware callback, not the application callback. You set the application callback path on the RedirectUri property on the AuthenticationProperties that you pass when you call Challenge on the IAuthenticationManager
                    //options.CallbackPath = new PathString("/TestAuth/oauthcallback");   //new PathString("/signin-google"); is the default

                    // Scopes: Official Google page is here: https://developers.google.com/+/web/api/rest/oauth
                    // Robert uses this: { "scope", "https://www.googleapis.com/auth/plus.profile.emails.read" },  // as per stackoverflow.com/a/23764783 . Despite the docs (e.g. developers.google.com/+/api/oauth#login-scopes) suggest "email", that resulted in "this app would like to have offline access" after a couple of days
                    // http://stackoverflow.com/questions/24410179/is-there-a-way-to-only-get-a-users-email-address-with-googles-oauth2-impleme
                    // Conclusion: the First item: "Know who you are on Google" is always there. Cannot make it disappear. It is Google's policy.
                    options.Scope.Add("https://www.googleapis.com/auth/plus.profile.emails.read"); // George: Robert thinks it is better then "email", but it asked ""this app would like to have offline access"" too

                    //options.AuthenticationScheme = "Google"; // this is by default
                    //options.AuthorizationEndpoint = "https://accounts.google.com/o/oauth2/auth"; // suggest token based, not cookie based
                });
            }
            else
            {
                mStartupLogger.LogWarning("A_G_CId and A_G_CSe from Config has NOT been found. Cannot initialize GoogelAuthentication.");
            }

            // Configure the HTTP request pipeline.
            app.UseStaticFiles();   // without it, the Server will not return static HTML files
            //app.UseDefaultFiles();
            //app.UseDefaultFiles(new Microsoft.AspNet.StaticFiles.DefaultFilesOptions() { DefaultFileNames = new[] { "Index.html" } });

            // Add MVC to the request pipeline.
            //app.UseMvc();
            //app.UseMvcWithDefaultRoute();  // following template: '{controller=Home}/{action=Index}/{id?}'.
            app.UseMvc(routes =>
             {
                 //routes.IgnoreRoute("");    //ignore empty routes //Re: Is there a workaround for routes.IgnoreRoute() in ASP.NET 5? (Method not implemented [yet])

                 // http://stackoverflow.com/questions/28017193/how-to-ignore-routes-in-mvc6
                 //routes.MapRoute(
                 //   name: "RootHomepage",
                 //   template: "",   // empty Route Should go to Index.html
                 //   defaults: new { controller = "RootHomepageRedirect", action = "Index" });

                 routes.MapRoute(
                    name: "route1",
                    template: "DeveloperDashboardForLocalDevelopment",
                    defaults: new { controller = "RootHomepageRedirect", action = "DeveloperDashboardForLocalDevelopment" }
                );
                routes.MapRoute(
                    name: "route2",
                    template: "UserDashboardForLocalDevelopment",
                    defaults: new { controller = "RootHomepageRedirect", action = "UserDashboardForLocalDevelopment" }
                );

                 routes.MapRoute(
                    name: "route3",
                    template: "DeveloperDashboard",
                    defaults: new { controller = "RootHomepageRedirect", action = "DeveloperDashboard" }
                );
                 routes.MapRoute(
                     name: "default",
                     template: "{controller}/{action}/{id?}",   // this is needed for Controller methods as Actions to be subPath items in URL
                     defaults: new { controller = "RootHomepageRedirect", action = "Index" });
             });

            // Add the following route for porting Web API 2 controllers.
            // routes.MapWebApiRoute("DefaultApi", "api/{controller}/{id?}");
        }
        private static void LogConfiguration(IServiceProvider serviceProvider, ILogger logger)
        {
            var settings = serviceProvider.GetRequiredService <IAzureBlobStorageSettings>();

            logger.LogInformation("Configuration:\n{0}", settings);
        }
示例#16
0
        async static Task Main()
        {
            Console.WriteLine("SIPSorcery SIP to WebRTC example.");
            Console.WriteLine("Press ctrl-c to exit.");

            // Plumbing code to facilitate a graceful exit.
            CancellationTokenSource exitCts = new CancellationTokenSource(); // Cancellation token to stop the SIP transport and RTP stream.

            Log = AddConsoleLogger();

            // Start web socket.
            Console.WriteLine("Starting web socket server...");
            var webSocketServer = new WebSocketServer(IPAddress.Any, WEBSOCKET_PORT);

            webSocketServer.AddWebSocketService <WebRTCWebSocketPeer>("/", (peer) => peer.CreatePeerConnection = CreatePeerConnection);
            webSocketServer.Start();

            // Set up a default SIP transport.
            var sipTransport = new SIPTransport();

            sipTransport.AddSIPChannel(new SIPUDPChannel(new IPEndPoint(IPAddress.Any, SIP_LISTEN_PORT)));

            //EnableTraceLogs(sipTransport);

            // Create a SIP user agent to receive a call from a remote SIP client.
            // Wire up event handlers for the different stages of the call.
            var userAgent = new SIPUserAgent(sipTransport, null, true);

            // We're only answering SIP calls, not placing them.
            userAgent.OnCallHungup += (dialog) =>
            {
                Log.LogInformation($"Call hungup by remote party.");
                exitCts.Cancel();
            };
            userAgent.ServerCallCancelled += (uas) => Log.LogInformation("Incoming call cancelled by caller.");
            userAgent.OnIncomingCall      += async(ua, req) =>
            {
                Log.LogInformation($"Incoming call request from {req.RemoteSIPEndPoint}: {req.StatusLine}.");
                var incomingCall = userAgent.AcceptCall(req);

                var rtpSession = new RTPSession(false, false, false);
                rtpSession.AcceptRtpFromAny = true;
                MediaStreamTrack audioTrack = new MediaStreamTrack(new List <AudioFormat> {
                    new AudioFormat(SDPWellKnownMediaFormatsEnum.PCMU)
                });
                rtpSession.addTrack(audioTrack);
                MediaStreamTrack videoTrack = new MediaStreamTrack(new VideoFormat(VideoCodecsEnum.VP8, 100));
                rtpSession.addTrack(videoTrack);

                await userAgent.Answer(incomingCall, rtpSession);

                rtpSession.OnRtpPacketReceived  += ForwardAudioToPeerConnection;
                rtpSession.OnVideoFrameReceived += ForwardVideoFrameToPeerConnection; // ForwardVideoFrameToSIP;

                Log.LogInformation($"Answered incoming call from {req.Header.From.FriendlyDescription()} at {req.RemoteSIPEndPoint}.");

                _rtpSession = rtpSession;
                RequestPeerConnectionKeyFrame(_peerConnection);
            };

            Console.WriteLine($"Waiting for browser web socket connection to {webSocketServer.Address}:{webSocketServer.Port}...");
            var contactURI = new SIPURI(SIPSchemesEnum.sip, sipTransport.GetSIPChannels().First().ListeningSIPEndPoint);

            Console.WriteLine($"Waiting for incoming SIP call to {contactURI}.");
            Console.WriteLine("NOTE: Once SIP and WebRTC parties are connected and if the video does not start press 'k' to request a key frame.");

            // Ctrl-c will gracefully exit the call at any point.
            Console.CancelKeyPress += delegate(object sender, ConsoleCancelEventArgs e)
            {
                e.Cancel = true;
                exitCts.Cancel();
            };

            // Wait for a signal saying the call failed, was cancelled with ctrl-c or completed.
            await Task.Run(() => OnKeyPress(exitCts.Token));

            #region Cleanup.

            Log.LogInformation("Exiting...");

            _rtpSession?.Close("app exit");

            if (userAgent != null)
            {
                if (userAgent.IsCallActive)
                {
                    Log.LogInformation($"Hanging up call to {userAgent?.CallDescriptor?.To}.");
                    userAgent.Hangup();
                }

                // Give the BYE or CANCEL request time to be transmitted.
                Log.LogInformation("Waiting 1s for call to clean up...");
                Task.Delay(1000).Wait();
            }

            if (sipTransport != null)
            {
                Log.LogInformation("Shutting down SIP transport...");
                sipTransport.Shutdown();
            }

            #endregion
        }
示例#17
0
 public SIPStreamConnectionUnitTest(Xunit.Abstractions.ITestOutputHelper output)
 {
     logger = SIPSorcery.UnitTests.TestLogHelper.InitTestLogger(output);
 }
 public SIPContactHeaderUnitTest(Xunit.Abstractions.ITestOutputHelper output)
 {
     logger = SIPSorcery.UnitTests.TestLogHelper.InitTestLogger(output);
 }
示例#19
0
 public WeaponNameParser(ILogger <WeaponNameParser> logger, IConfigurationHandler <StatsConfiguration> config)
 {
     _logger = logger;
     _config = config.Configuration();
 }
        public static async Task OnGetLeagueSummaryQueryHandler(
            [EventGridTrigger] EventGridEvent eventGridEvent,
            [OrchestrationClient] DurableOrchestrationClient getLeagueSummaryQueryHandlerOrchestrationClient,
            Microsoft.Extensions.Logging.ILogger log
            )
        {
            #region Logging
            if (null != log)
            {
                log.LogDebug("Function triggered in OnGetLeagueSummaryQuery");
            }

            if (null == eventGridEvent)
            {
                // This function should not proceed if there is no event data
                if (null != log)
                {
                    log.LogError("Missing event grid trigger data in OnGetLeagueSummaryQuery");
                }
                return;
            }
            else
            {
                if (null != log)
                {
                    log.LogDebug($"Event grid topic: {eventGridEvent.Topic}");
                    log.LogDebug($"Event grid subject: {eventGridEvent.Subject }");
                    log.LogDebug($"Event grid metadata version: {eventGridEvent.MetadataVersion }");
                    log.LogDebug($"Event grid event type: {eventGridEvent.EventType }");
                    log.LogDebug($"Event Grid Data : {eventGridEvent.Data }");
                }
            }
            #endregion

            try
            {
                #region Logging
                if (null != log)
                {
                    log.LogDebug($"Get the query parameters in OnGetLeagueSummaryQuery");
                    if (null == eventGridEvent.Data)
                    {
                        log.LogError($"The query parameter has no values in OnGetLeagueSummaryQuery");
                        return;
                    }
                }
                #endregion

                // Get the query request details out of the event grid data request
                var jsondata = JsonConvert.SerializeObject(eventGridEvent.Data);
                QueryRequest <Get_League_Summary_Definition> queryRequest = null;
                if (!string.IsNullOrWhiteSpace(jsondata))
                {
                    queryRequest = JsonConvert.DeserializeObject <QueryRequest <Get_League_Summary_Definition> >(jsondata);
                }

                if (null != queryRequest)
                {
                    log.LogInformation($"Running query handler with durable functions orchestration");
                    log.LogInformation($"{queryRequest.QueryName} with league {queryRequest.GetParameters().League_Name}");

                    // Using Azure Durable functions to do the query chaining
                    string instanceId = await getLeagueSummaryQueryHandlerOrchestrationClient.StartNewAsync("OnGetLeagueSummaryQueryHandlerOrchestrator", queryRequest);

                    log.LogInformation($"Started OnGetLeagueSummaryQueryHandlerOrchestrator orchestration with ID = '{instanceId}'.");
                }
                else
                {
                    if (null != log)
                    {
                        log.LogError($"Unable to read query request from eventgrid data: {eventGridEvent.Data} Type: {eventGridEvent.Data.GetType()} ");
                    }
                }
            }
            catch (Exception ex)
            {
                if (null != log)
                {
                    log.LogError(ex.ToString(), ex);
                }
                throw;
            }
        }
        public static async Task <Get_League_Summary_Definition_Return> OnGetLeagueSummaryQueryHandlerOrchestrator
            ([OrchestrationTrigger] DurableOrchestrationContext context,
            Microsoft.Extensions.Logging.ILogger log)
        {
            // Get the query definition form the context...
            QueryRequest <Get_League_Summary_Definition> queryRequest = context.GetInput <QueryRequest <Get_League_Summary_Definition> >();

            if (null != queryRequest)
            {
                queryRequest.QueryName = "get-league-summary";

                // Log the query request in its own own query event stream
                Guid queryId = await context.CallActivityAsync <Guid>("GetLeagueSummaryCreateQueryRequestActivity", queryRequest);

                if (queryId.Equals(Guid.Empty))
                {
                    #region Logging
                    if (null != log)
                    {
                        // Unable to get the request details from the orchestration
                        log.LogError("OnGetLeagueSummaryQueryHandlerOrchestrator : Unable to create the query event stream");
                    }
                    #endregion

                    return(null);
                }
                else
                {
                    queryRequest.QueryUniqueIdentifier = queryId;
                    // Save the parameters to the event stream
                    ActivityResponse resp = await context.CallActivityAsync <ActivityResponse>("GetLeagueSummaryLogParametersActivity", queryRequest);

                    #region Logging
                    if (null != log)
                    {
                        if (null != resp)
                        {
                            log.LogInformation($"{resp.FunctionName} complete: {resp.Message } ");
                        }
                    }
                    #endregion


                    if (null != resp)
                    {
                        context.SetCustomStatus(resp);
                    }

                    // next validate the query
                    bool valid = await context.CallActivityAsync <bool>("GetLeagueSummaryValidateActivity", queryRequest);

                    if (!valid)
                    {
                        if (null != log)
                        {
                            // Could not run the query as the parameters don't make sense
                            log.LogError($"OnGetLeagueSummaryQueryHandlerOrchestrator : Query parameters are invalid {queryId}");
                        }
                        return(null);
                    }
                    else
                    {
                        // Request all the projections needed to answer this query
                        resp = await context.CallActivityAsync <ActivityResponse>("GetLeagueSummaryQueryProjectionRequestActivity", queryRequest);

                        #region Logging
                        if (null != log)
                        {
                            if (null != resp)
                            {
                                log.LogInformation($"{resp.FunctionName} complete: {resp.Message } ");
                            }
                        }
                        #endregion
                        if (null != resp)
                        {
                            context.SetCustomStatus(resp);
                        }

                        // Run all the outstanding projections for this query
                        resp = await context.CallActivityAsync <ActivityResponse>("GetLeagueSummaryQueryProjectionProcessActivity", queryRequest);

                        #region Logging
                        if (null != log)
                        {
                            if (null != resp)
                            {
                                log.LogInformation($"{resp.FunctionName} complete: {resp.Message } ");
                            }
                        }
                        #endregion
                        if (null != resp)
                        {
                            context.SetCustomStatus(resp);
                        }

                        // Output the results
                        resp = await context.CallActivityAsync <ActivityResponse>("GetLeagueSummaryOutputResultsActivity", queryRequest);

                        #region Logging
                        if (null != log)
                        {
                            if (null != resp)
                            {
                                log.LogInformation($"{resp.FunctionName} complete: {resp.Message } ");
                            }
                        }
                        #endregion
                        if (null != resp)
                        {
                            context.SetCustomStatus(resp);
                        }

                        // Get the results for ourselves to return...to do this the query must be complete...
                        return(await context.CallActivityAsync <Get_League_Summary_Definition_Return>("GetLeagueSummaryGetResultsActivity", queryRequest));
                    }
                }
            }
            else
            {
                if (null != log)
                {
                    // Unable to get the request details from the orchestration
                    log.LogError("OnGetLeagueSummaryQueryHandlerOrchestrator : Unable to get the query request from the context");

                    string contextAsString = context.GetInput <string>();
                    if (!string.IsNullOrWhiteSpace(contextAsString))
                    {
                        log.LogError($"Context was {contextAsString} ");
                    }
                    else
                    {
                        log.LogError($"Context was blank ");
                    }
                }

                return(null);
            }
        }
示例#22
0
 public HostLogger(string name, Microsoft.Extensions.Logging.ILogger logger)
 {
     Name    = name;
     _logger = logger;
 }
示例#23
0
 public Logger(Microsoft.Extensions.Logging.ILogger logger)
 {
     this.logger = logger;
 }
示例#24
0
 public MyTraceListener(ILogger logger)
 {
     this.logger = logger;
 }
示例#25
0
 public MusicRequestController(IMusicRequestEngine engine, IVoteEngine voteEngine, ILogger <MusicRequestController> log)
 {
     _engine     = engine;
     _voteEngine = voteEngine;
     _log        = log;
 }
 public RTCSessionDescriptionInitUnitTest(Xunit.Abstractions.ITestOutputHelper output)
 {
     logger = SIPSorcery.UnitTests.TestLogHelper.InitTestLogger(output);
 }
示例#27
0
 public PgsOcr(Microsoft.Extensions.Logging.ILogger logger)
 {
     _logger = logger;
 }
示例#28
0
        /// <summary>
        /// Add services for authentication, including Identity model, IdentityServer4 and external providers
        /// </summary>
        /// <typeparam name="TIdentityDbContext">DbContext for Identity</typeparam>
        /// <typeparam name="TUserIdentity">User Identity class</typeparam>
        /// <typeparam name="TUserIdentityRole">User Identity Role class</typeparam>
        /// <typeparam name="TConfigurationDbContext"></typeparam>
        /// <typeparam name="TPersistedGrantDbContext"></typeparam>
        /// <param name="services"></param>
        /// <param name="hostingEnvironment"></param>
        /// <param name="configuration"></param>
        /// <param name="logger"></param>
        public static void AddAuthenticationServices <TConfigurationDbContext, TPersistedGrantDbContext, TIdentityDbContext, TUserIdentity, TUserIdentityRole>(this IServiceCollection services, IHostingEnvironment hostingEnvironment, IConfiguration configuration, ILogger logger)
            where TPersistedGrantDbContext : DbContext, IPersistedGrantDbContext
            where TConfigurationDbContext : DbContext, IConfigurationDbContext
            where TIdentityDbContext : DbContext
            where TUserIdentity : class
            where TUserIdentityRole : class
        {
            var loginConfiguration        = GetLoginConfiguration(configuration);
            var registrationConfiguration = GetRegistrationConfiguration(configuration);

            services
            .AddSingleton(registrationConfiguration)
            .AddSingleton(loginConfiguration)
            .AddScoped <UserResolver <TUserIdentity> >()
            .AddIdentity <TUserIdentity, TUserIdentityRole>(options =>
            {
                options.User.RequireUniqueEmail = true;
            })
            .AddEntityFrameworkStores <TIdentityDbContext>()
            .AddDefaultTokenProviders();

            services.Configure <IISOptions>(iis =>
            {
                iis.AuthenticationDisplayName = "Windows";
                iis.AutomaticAuthentication   = false;
            });

            var authenticationBuilder = services.AddAuthentication();

            AddExternalProviders(authenticationBuilder, configuration);

            AddIdentityServer <TConfigurationDbContext, TPersistedGrantDbContext, TUserIdentity>(services, configuration, logger, hostingEnvironment);
        }
示例#29
0
        static void Main()
        {
            Console.WriteLine("SIPSorcery Call Hold and Blind Transfer example.");
            Console.WriteLine("Press 'c' to initiate a call to the default destination.");
            Console.WriteLine("Press 'h' to place an established call on and off hold.");
            Console.WriteLine("Press 'H' to hangup an established call.");
            Console.WriteLine("Press 't' to request a blind transfer on an established call.");
            Console.WriteLine("Press 'q' or ctrl-c to exit.");

            // Plumbing code to facilitate a graceful exit.
            CancellationTokenSource exitCts = new CancellationTokenSource(); // Cancellation token to stop the SIP transport and RTP stream.

            Log = AddConsoleLogger();

            // Set up a default SIP transport.
            var sipTransport = new SIPTransport();

            sipTransport.AddSIPChannel(new SIPUDPChannel(new IPEndPoint(IPAddress.Any, SIP_LISTEN_PORT)));

            Console.WriteLine($"Listening for incoming calls on: {sipTransport.GetSIPChannels().First().ListeningEndPoint}.");

            EnableTraceLogs(sipTransport);

            var winAudio = new WindowsAudioEndPoint(new AudioEncoder());

            winAudio.RestrictFormats(formats => formats.Codec == AudioCodecsEnum.PCMU);

            // Create a client/server user agent to place a call to a remote SIP server along with event handlers for the different stages of the call.
            var userAgent = new SIPUserAgent(sipTransport, null, true);

            userAgent.RemotePutOnHold   += () => Log.LogInformation("Remote call party has placed us on hold.");
            userAgent.RemoteTookOffHold += () => Log.LogInformation("Remote call party took us off hold.");
            userAgent.OnIncomingCall    += async(ua, req) =>
            {
                Log.LogInformation($"Incoming call from {req.Header.From.FriendlyDescription()} at {req.RemoteSIPEndPoint}.");
                var uas = userAgent.AcceptCall(req);

                if (userAgent?.IsCallActive == true)
                {
                    // If we are already on a call return a busy response.
                    Log.LogWarning($"Busy response returned for incoming call request.");
                    uas.Reject(SIPResponseStatusCodesEnum.BusyHere, null);
                }
                else
                {
                    var voipSession = new VoIPMediaSession(winAudio.ToMediaEndPoints());
                    voipSession.AcceptRtpFromAny = true;
                    var answerResult = await userAgent.Answer(uas, voipSession);
                }
            };

            // At this point the call has been initiated and everything will be handled in an event handler.
            Task.Run(async() =>
            {
                try
                {
                    while (!exitCts.Token.WaitHandle.WaitOne(0))
                    {
                        var keyProps = Console.ReadKey();

                        if (keyProps.KeyChar == 'c')
                        {
                            if (!userAgent.IsCallActive)
                            {
                                var voipSession = new VoIPMediaSession(winAudio.ToMediaEndPoints());
                                voipSession.AcceptRtpFromAny = true;
                                bool callResult = await userAgent.Call(DEFAULT_DESTINATION_SIP_URI, SIP_USERNAME, SIP_PASSWORD, voipSession);

                                Log.LogInformation($"Call attempt {((callResult) ? "successfull" : "failed")}.");
                            }
                            else
                            {
                                Log.LogWarning("There is already an active call.");
                            }
                        }
                        else if (keyProps.KeyChar == 'h')
                        {
                            // Place call on/off hold.
                            if (userAgent.IsCallActive)
                            {
                                if (userAgent.IsOnLocalHold)
                                {
                                    Log.LogInformation("Taking the remote call party off hold.");
                                    (userAgent.MediaSession as VoIPMediaSession).TakeOffHold();
                                    userAgent.TakeOffHold();
                                }
                                else
                                {
                                    Log.LogInformation("Placing the remote call party on hold.");
                                    await(userAgent.MediaSession as VoIPMediaSession).PutOnHold();
                                    userAgent.PutOnHold();
                                }
                            }
                            else
                            {
                                Log.LogWarning("There is no active call to put on hold.");
                            }
                        }
                        else if (keyProps.KeyChar == 'H')
                        {
                            if (userAgent.IsCallActive)
                            {
                                Log.LogInformation("Hanging up call.");
                                userAgent.Hangup();
                            }
                        }
                        else if (keyProps.KeyChar == 't')
                        {
                            // Initiate a blind transfer to the remote call party.
                            if (userAgent.IsCallActive)
                            {
                                var transferURI = SIPURI.ParseSIPURI(TRANSFER_DESTINATION_SIP_URI);
                                bool result     = await userAgent.BlindTransfer(transferURI, TimeSpan.FromSeconds(TRANSFER_TIMEOUT_SECONDS), exitCts.Token);
                                if (result)
                                {
                                    // If the transfer was accepted the original call will already have been hungup.
                                    // Wait a second for the transfer NOTIFY request to arrive.
                                    await Task.Delay(1000);
                                    exitCts.Cancel();
                                }
                                else
                                {
                                    Log.LogWarning($"Transfer to {TRANSFER_DESTINATION_SIP_URI} failed.");
                                }
                            }
                            else
                            {
                                Log.LogWarning("There is no active call to transfer.");
                            }
                        }
                        else if (keyProps.KeyChar == 'q')
                        {
                            // Quit application.
                            exitCts.Cancel();
                        }
                    }
                }
                catch (Exception excp)
                {
                    Log.LogError($"Exception Key Press listener. {excp.Message}.");
                }
            });

            // Ctrl-c will gracefully exit the call at any point.
            Console.CancelKeyPress += delegate(object sender, ConsoleCancelEventArgs e)
            {
                e.Cancel = true;
                exitCts.Cancel();
            };

            // Wait for a signal saying the call failed, was cancelled with ctrl-c or completed.
            exitCts.Token.WaitHandle.WaitOne();

            #region Cleanup.

            Log.LogInformation("Exiting...");

            if (userAgent != null)
            {
                if (userAgent.IsCallActive)
                {
                    Log.LogInformation($"Hanging up call to {userAgent?.CallDescriptor?.To}.");
                    userAgent.Hangup();
                }

                // Give the BYE or CANCEL request time to be transmitted.
                Log.LogInformation("Waiting 1s for call to clean up...");
                Task.Delay(1000).Wait();
            }

            if (sipTransport != null)
            {
                Log.LogInformation("Shutting down SIP transport...");
                sipTransport.Shutdown();
            }

            #endregion
        }
示例#30
0
 public Program(ME.ILogger logger) : base(logger)
 {
 }
示例#31
0
        private static async Task StartSilo(ISiloHost siloHost, ILogger logger)
        {
            await siloHost.StartAsync();

            logger.LogInformation("Silo started.");
        }
示例#32
0
 /// <summary>
 /// Initializes a new instance of the <see cref="Shared.Logger" /> class.
 /// </summary>
 /// <param name="loggerObject">The logger object.</param>
 /// <param name="fileName">Name of the scenario.</param>
 public void Initialise(Microsoft.Extensions.Logging.ILogger loggerObject)
 {
     this.LoggerObject  = loggerObject;
     this.IsInitialised = true;
 }
 public AzureFunctionHandler(Microsoft.Extensions.Logging.ILogger logger, ExecutionContext context)
 {
     this.log     = logger;
     this.context = context;
 }
示例#34
0
        static void Main()
        {
            Console.WriteLine("SIPSorcery Getting Started Video Call Demo");
            Console.WriteLine("Press ctrl-c to exit.");

            Log = AddConsoleLogger();
            ManualResetEvent exitMRE = new ManualResetEvent(false);

            _sipTransport = new SIPTransport();

            EnableTraceLogs(_sipTransport);

            // Open a window to display the video feed from the remote SIP party.
            _form = new Form();
            _form.AutoSize = true;
            _form.BackgroundImageLayout = ImageLayout.Center;
            _picBox = new PictureBox
            {
                Size = new Size(640, 480),
                Location = new Point(0, 0),
                Visible = true
            };
            _form.Controls.Add(_picBox);

            Application.EnableVisualStyles();
            ThreadPool.QueueUserWorkItem(delegate { Application.Run(_form); });

            ManualResetEvent formMre = new ManualResetEvent(false);
            _form.Activated += (object sender, EventArgs e) => formMre.Set();

            Console.WriteLine("Waiting for form activation.");
            formMre.WaitOne();

            _sipTransport.SIPTransportRequestReceived += OnSIPTransportRequestReceived;

            string executableDir = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);

            var userAgent = new SIPUserAgent(_sipTransport, null);
            userAgent.OnCallHungup += (dialog) => exitMRE.Set();
            var windowsAudioEndPoint = new WindowsAudioEndPoint(new AudioEncoder());
            windowsAudioEndPoint.RestrictFormats(format => format.Codec == AudioCodecsEnum.PCMU);
            var windowsVideoEndPoint = new WindowsVideoEndPoint();
            //windowsVideoEndPoint.OnVideoSourceError += (err) =>
            //{
            //    Log.LogError($"Video source error. {err}");
            //    if (userAgent.IsCallActive)
            //    {
            //        userAgent.Hangup();
            //    }
            //};

            // Fallback to a test pattern source if accessing the Windows webcam fails.
            var testPattern = new VideoTestPatternSource(new VideoEncoder());

            MediaEndPoints mediaEndPoints = new MediaEndPoints
            {
                AudioSink = windowsAudioEndPoint,
                AudioSource = windowsAudioEndPoint,
                VideoSink = windowsVideoEndPoint,
                VideoSource = windowsVideoEndPoint,
            };

            var voipMediaSession = new VoIPMediaSession(mediaEndPoints, testPattern);
            voipMediaSession.AcceptRtpFromAny = true;

            // Place the call and wait for the result.
            Task<bool> callTask = userAgent.Call(DESTINATION, null, null, voipMediaSession);
            callTask.Wait(CALL_TIMEOUT_SECONDS * 1000);

            if (callTask.Result)
            {
                Log.LogInformation("Call attempt successful.");
                windowsVideoEndPoint.OnVideoSinkDecodedSample += (byte[] bmp, uint width, uint height, int stride, VideoPixelFormatsEnum pixelFormat) =>
                {
                    if (_form?.Handle != null && _picBox != null)
                    {
                        _picBox.BeginInvoke(new Action(() =>
                        {
                            unsafe
                            {
                                fixed (byte* s = bmp)
                                {
                                    System.Drawing.Bitmap bmpImage = new System.Drawing.Bitmap((int)width, (int)height, stride, System.Drawing.Imaging.PixelFormat.Format24bppRgb, (IntPtr)s);
                                    _picBox.Image = bmpImage;
                                }
                            }
                        }));
                    }
                };

                windowsAudioEndPoint.PauseAudio().Wait();
                voipMediaSession.AudioExtrasSource.SetSource(AudioSourcesEnum.Music);
            }
            else
            {
                Log.LogWarning("Call attempt failed.");
                Console.WriteLine("Press ctrl-c to exit.");
            }

            Console.CancelKeyPress += delegate (object sender, ConsoleCancelEventArgs e)
            {
                e.Cancel = true;
                Log.LogInformation("Exiting...");
                exitMRE.Set();
            };
            exitMRE.WaitOne();

            if (userAgent.IsCallActive)
            {
                Log.LogInformation("Hanging up.");
                userAgent.Hangup();

                Task.Delay(1000).Wait();
            }

            // Clean up.
            _form.BeginInvoke(new Action(() => _form.Close()));
            _sipTransport.Shutdown();
        }
示例#35
0
 public IndexModel(ILogger <IndexModel> logger)
 {
     _logger = logger;
 }
示例#36
0
        private static AggregateApplicationProcessor CreateApplicationProcessor(ReplicaRegistry replicaRegistry, HostOptions options, Microsoft.Extensions.Logging.ILogger logger)
        {
            var diagnosticsCollector = new DiagnosticsCollector(logger)
            {
                // Local run always uses metrics for the dashboard
                MetricSink = new MetricSink(logger),
            };

            if (options.LoggingProvider != null &&
                DiagnosticsProvider.TryParse(options.LoggingProvider, out var logging))
            {
                diagnosticsCollector.LoggingSink = new LoggingSink(logger, logging);
            }

            if (options.DistributedTraceProvider != null &&
                DiagnosticsProvider.TryParse(options.DistributedTraceProvider, out var tracing))
            {
                diagnosticsCollector.TracingSink = new TracingSink(logger, tracing);
            }

            // Print out what providers were selected and their values
            DumpDiagnostics(options, logger);

            var processors = new List <IApplicationProcessor>
            {
                new EventPipeDiagnosticsRunner(logger, diagnosticsCollector),
                new PortAssigner(logger),
                new ProxyService(logger),
                new HttpProxyService(logger),
                new DockerImagePuller(logger),
                new FuncFinder(logger),
                new ReplicaMonitor(logger),
                new DockerRunner(logger, replicaRegistry),
                new ProcessRunner(logger, replicaRegistry, ProcessRunnerOptions.FromHostOptions(options))
            };

            // If the docker command is specified then transform the ProjectRunInfo into DockerRunInfo
            if (options.Docker)
            {
                processors.Insert(0, new TransformProjectsIntoContainers(logger));
            }

            return(new AggregateApplicationProcessor(processors));
        }
 /// <summary>
 ///     create new instance with the given ILogger
 /// </summary>
 /// <param name="logger"></param>
 public EventStoreLogger(ILogger <IEventStoreConnection> logger)
 {
     _logger = logger;
 }
 protected DownloadLookup(FrameworkLogger logger)
 {
     _logger = logger;
 }
示例#39
0
        public static Microsoft.Extensions.Logging.ILogger GetLogger(string name = "PowerShell")
        {
            lock(s_syncLock)
            {
                if (s_rootLogger == null)
                {
                    s_rootLogger = GetFactory().CreateLogger(name);
                   
                }

                return s_rootLogger;
            }
        }
示例#40
0
        public static void Run([CosmosDBTrigger(
                                    databaseName: "recruit-subscriptions",
                                    collectionName: "subscriptions",
                                    ConnectionStringSetting = "SubscriptionsCosmosDb",
                                    LeaseCollectionName = "leases",
                                    CreateLeaseCollectionIfNotExists = true)] IReadOnlyList <Document> input, ILogger log,
                               [Queue("subscriptions", Connection = "AzureWebJobsStorage")] ICollector <string> output,
                               ExecutionContext context)
        {
            var logger = CreateLogger(context);

            if (input != null && input.Count > 0)
            {
                log.LogInformation("Documents modified " + input.Count);
                logger.Debug("Documents modified {count}", input.Count);

                log.LogInformation("First document Id " + input[0].Id);

                //var myItem = JsonConvert.DeserializeObject<MyItem>(input[0].ToString());

                foreach (var change in input)
                {
                    logger.Debug("Adding change to queue for subscription id {subscriptionId}", change.Id);
                    output.Add(new SubscriptionItem(change.Id));
                }
            }
        }
 public SIPTransactionEngineUnitTest(Xunit.Abstractions.ITestOutputHelper output)
 {
     logger = SIPSorcery.UnitTests.TestLogHelper.InitTestLogger(output);
 }
示例#42
0
 public PluginInformation(Microsoft.Extensions.Logging.ILogger logger = null)
 {
     Logger = logger ?? XplorerMainWindow.LoggerFactory.CreateLogger <PluginInformation>();
 }
 public RTSPMessageUnitTest(Xunit.Abstractions.ITestOutputHelper output)
 {
     logger = SIPSorcery.UnitTests.TestLogHelper.InitTestLogger(output);
 }
示例#44
0
 public AppLoggerSerilog(IAppLoggerConfig config, IEnumerable <IAppLoggerExtension> loggerExtensions)
 {
     _loggerExtensions = loggerExtensions;
     _logger           = CreateLogger(config);
 }
 public RequestUrlLoggerMiddleware(RequestDelegate next, ILoggerFactory loggerFactory) 
 {
     _next = next;
     _logger = loggerFactory.CreateLogger<RequestUrlLoggerMiddleware>();
 }
示例#46
0
 public AppLoggerSerilog(IAppLoggerConfig config)
 {
     _logger = CreateLogger(config);
 }
示例#47
0
        public AppLoggerSerilog()
        {
            var config = new AppLoggerSerilogConfig();

            _logger = CreateLogger(config);
        }
示例#48
-1
        public Program()
        {
            // a DI based application would get ILoggerFactory injected instead
            var factory = new LoggerFactory();

            // getting the logger immediately using the class's name is conventional
            _logger = factory.CreateLogger<Program>();

            // providers may be added to an ILoggerFactory at any time, existing ILoggers are updated
#if !DNXCORE50
            factory.AddNLog(new global::NLog.LogFactory());
            factory.AddEventLog();
#endif

            // How to configure the console logger to reload based on a configuration file.
            //
            //
            var loggingConfiguration = new ConfigurationBuilder().AddJsonFile("logging.json").Build();
            factory.AddConsole(loggingConfiguration);
            loggingConfiguration.ReloadOnChanged("logging.json");

            // How to configure the console logger to use settings provided in code.
            //
            //
            //var settings = new ConsoleLoggerSettings()
            //{
            //    IncludeScopes = true,
            //    Switches =
            //    {
            //        ["Default"] = LogLevel.Verbose,
            //        ["Microsoft"] = LogLevel.Information,
            //    }
            //};
            //factory.AddConsole(settings);

            // How to manually wire up file-watching without a configuration file
            //
            //
            //factory.AddConsole(new RandomReloadingConsoleSettings());
        }