How to push logs to splunk from log4net in .net core 6 - log4net

We are migrating from .net framework to .net core framework for our api.
We are trying to use log4net framework for logging Info and Error and then pushing them all to splunk since it was used in the existing api on .net framework.
But here in .net core im not getting a proper way or documentation to use log4net for logging and pushing the data to splunk. I have tried searching a lot and still not able to complete the implementation.
Can anyone please help me in this regard.
Thank you.
Vishwa
I have added configs for log4net and a logger class with methods, which i can use to log the Info and Error like below
namespace ABC
{
using System.Diagnostics;
using System.Reflection;
using log4net;
public static class Logger
{
private static readonly ILog Log = log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public static void Info(this string className, string message)
{
log4net.LogicalThreadContext.Properties["ActivityId"] = Trace.CorrelationManager.ActivityId;
log4net.LogicalThreadContext.Properties["LogType"] = className;
Log.Info(message);
}
public static void Error(this string className, string message)
{
log4net.LogicalThreadContext.Properties["ActivityId"] = Trace.CorrelationManager.ActivityId;
log4net.LogicalThreadContext.Properties["LogType"] = className;
Log.Error(message);
}
}
}
Now im stuck with the part to push logs to splunk . Any help would be appreciated

Related

How can I add tracing / logging messages for a Blazor Server Side App on Azure? (Preferred with App Service Logs)

I have a Blazor Server Side App that runs on Azure. I want to add tracing / logging messages (_logger.LogInformation()). I would prefer to use Azue App Service Logs. But, I am open to other options.
I was able to get tracing / logging messages working with an API written in .Net Core that runs on Azure. These logs are written to Azure App Service Logs. Their type are Application.
For my Blazor App, I followed the same steps setting up tracing / logging as I did with my API. However, when I check the log files in Cloud Explorer no Application folder, under the LogFiles folder is created.
I made sure I turned Azure App Service Logs and set the correct Level. See below.
My Program.cs uses the default setting. Which I read should automatically set up logging. (It did from my API) See below.
Below is the example of the code I added to do the tracing / logging.
public class VpbDelegateAdminService : IVpbDelegateAdminService
{
private readonly HttpClient _httpClient;
private readonly IJsonSerializerWrapper _jsonSerializerWrapper;
private readonly TokenProvider _tokenProvider;
private readonly ILogger<VpbDelegateAdminService> _logger;
public VpbDelegateAdminService(HttpClient httpClient, IJsonSerializerWrapper jsonSerializerWrapper, TokenProvider tokenProvider, ILogger<VpbDelegateAdminService> logger)
{
_httpClient = httpClient;
_jsonSerializerWrapper = jsonSerializerWrapper;
_tokenProvider = tokenProvider;
_logger = logger;
}
public async Task<VpbDelegateListVm> GetVpbDelegatesAsync(int pageNo, string searchText)
{
_logger.LogInformation($"Argument(s)- pageNo: {pageNo}, searchText: {searchText ?? "null"}");
As I mentioned above, I would prefer to use Azure App Service Logs. But, if that is not possible with Blazor or if someone has had success with other options to use with Blazor, I am interested to hearing about them.
Thanks for your help.
I figured it out myself.
I was able to get Logging / Tracing working with my Blazor server side app using App Service Logs by following the steps here: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/logging/?view=aspnetcore-3.1 Related to steps for: AzureAppServices
Steps: (Note: There steps are only for filesystem / filestream. I didn't set up blob):
1. Update appsetting with:
"AzureAppServicesFile": {
"IncludeScopes": true,
"LogLevel": {
"Default": "Warning"
}
}
2. Install nuget packages for Microsoft.Extensions.Logging.AzureAppServices
3. Update the Program.cs with the following code:
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureLogging(logging => logging.AddAzureWebAppDiagnostics())
.ConfigureServices(serviceCollection => serviceCollection
.Configure<AzureFileLoggerOptions>(options =>
{
options.FileName = "diagnostics-";
options.FileSizeLimit = 50 * 1024;
options.RetainedFileCountLimit = 5;
}))
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
4. Turned on App Service Log for Application Logging (Filesystem)
5. Set the Level to Information
And my logs / tracing (see below) started showing up in Cloud Explorer
_logger.LogInformation($"Argument(s)- pageNo: {pageNo}, searchText: {searchText ?? "null"}");
I hope these steps help someone else.
I would recommend using Application Insights, for .NET based apps it provides an excellent way for you to do complete APM. If you want to use with ILogger then please take a look here. If you want to get started without ILogger then take a look here.

Xamarin.Android Cannot pull table from Azure database in Android 10 Q

I did read that because lack of support for Netcore 2.1 the
myItemsList = await App.MobileServiceAndroid.GetTable<MyTable>().ToListAsync();
does not currently work on Android, and there is a workaround to pass an HttpClientHandler() in the constructor of the MobileServiceClient, and so I did like this:
public static MobileServiceClient MobileServiceAndroid =
new MobileServiceClient(AppConstants.AZURE_PRODUCTION_WEB_API_URL, new HttpClientHandler());
But this is incomplete,its still not working, what exactly do I have to do to make this work, any guidance is much appreciated.
From my understanding, you are using a Forms/PCL project whereas the other solution was implementing this code inside their Android project.
For you, once you add using Xamarin.Android.Net; to the class, you should be able to just do this:
public static MobileServiceClient MobileServiceAndroid =
new MobileServiceClient(AppConstants.AZURE_PRODUCTION_WEB_API_URL, new AndroidClientHandler());
Most likely you might have issues getting that using statement, for that you will have to follow steps shown here, or customized for you in the following steps:
Add the Xamarin Forms project to all your projects.
Create an interface ICustomClientHandler in the Core project
using System;
using System.Net.Http;
namespace Test
{
public interface ICustomClientHandler
{
HttpClientHandler GetHandler();
}
}
Then create a CustomClientHandler in the Droid project, which will be the Android part of the dependency service that will help you retrieve the native AndroidClientHandler
using System.Net.Http;
using Xamarin.Android.Net;
using System.Runtime.CompilerServices;
using Xamarin.Forms;
using Test;
[assembly: Xamarin.Forms.Dependency(typeof(Test.Droid.CustomClientHandler))]
namespace Test.Droid
{
public class CustomClientHandler : ICustomClientHandler
{
public HttpClientHandler GetHandler()
{
return new AndroidClientHandler();
}
}
}
Implement an iOS version as well in a similar way, but it will instead return new HttpClientHandler();
Finally, use the code as shown, in your Core project:
var clientHandler = DependencyService.Get<ICustomClientHandler>().GetHandler();
public static MobileServiceClient MobileServiceAndroid =
new MobileServiceClient(AppConstants.AZURE_PRODUCTION_WEB_API_URL, clientHandler);

Use SAP Cloud SDK to integrate with a custom backend service (oData) based on VDM Generator

I followed Alexander Duemont's blog, trying to implement a Java Spring Boot application that consumes Cloud Foundry Destination. The Destination has a custom OData V2 behind it, coming from an On-Premise ERP system. For local dev, when I perform the Maven build, the Integration-Tests module registers failure due to dependency injection
This is part of my Controller
#RestController
#RequestMapping("/resources")
public class ClassificationsController {
private static final Logger logger = CloudLoggerFactory.getLogger(ClassificationsController.class);
private final ClassificationService service;
public ClassificationsController(#Nonnull final ClassificationService service) {
this.service = service;
}
…..
}
The #Nonnull final ClassificationService Service causes org.springframework.beans.factory.UnsatisfiedDependencyException
I cannot use Spring stereotype annotations on generated Service classes (Fluent) to create Beans!
This question is more likely related to Spring Boot configuration.
I'm assuming ClassificationService is an interface and the implementing class exists in the same package.
Please make sure...
... to add the implementing class of ClassificationService to your component scan / test runtime. Feel free to share the integration test code to setup the test environment. Maybe the additional class reference is missing.
... to correctly annotate the respective Application class of your Spring Boot project. For example, assuming your ClassificationService resides in org.example.services.classification, while the rest of your application uses org.example.app. Your basic Application class would look like this, when following the Cloud SDK guide:
#SpringBootApplication
#ComponentScan({"com.sap.cloud.sdk", "org.example.services.classification", "org.example.app"})
#ServletComponentScan({"com.sap.cloud.sdk", "org.example.app"})
public class Application extends SpringBootServletInitializer
{
#Override
protected SpringApplicationBuilder configure( final SpringApplicationBuilder application )
{
return application.sources(Application.class);
}
public static void main( final String[] args )
{
SpringApplication.run(Application.class, args);
}
}
... to annotate the implementing class of ClassificationService with javax.inject.Named. In case you have multiple implementations of the same interface, make sure to give the not-used class a custom (unique) value for the #Named annotation.
... to look for exceptions (Class not found) in the application log during startup.

Azure Mobile Services - No bootstrapper found

I have a Azure Mobile Services project. When running locally everything works fine, the Application_Start() method gets called which in turn calls my WebApiConfig.Register() method.
However, when published to a live Azure Mobile Services server the Application_Start() does not get called along with the WebApiConfig.Register().
In the servers log I have the following entry:
No bootstrapper found -- using default bootstrapper. A bootstrapper can be specified in one of two ways: Either by defining a public, static class with name 'WebApiConfig' having a public parameter-less member called 'Register', or using the 'IBootstrapper' attribute to define a public class with a default constructor.
Why is Azure Mobile Services not picking up my BootStrapping WebApiConfig?
public static class WebApiConfig
{
public static void Register()
{
Trace.TraceInformation("Hello from WebApiConfig Register().");
// Use this class to set configuration options for your mobile service
ConfigOptions options = new ConfigOptions();
// Use this class to set WebAPI configuration options
HttpConfiguration config = ServiceConfig.Initialize(new ConfigBuilder(options));
// To display errors in the browser during development, uncomment the following
// line. Comment it out again when you deploy your service for production use.
// config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;
}
}
public class WebApiApplication : System.Web.HttpApplication
{
public WebApiApplication()
{
Trace.TraceInformation("Hello from WebApiApplication ctor!");
}
protected void Application_Start()
{
Trace.TraceInformation("Hello from Application_Start()");
//RouteConfig.RegisterRoutes(RouteTable.Routes);
WebApiConfig.Register();
var dataContext = new DataContext();
dataContext.Database.Initialize(false);
}
}
Help is much appreciated!
That is bizarre... It really looks like you got it right. After working with .net backend azure mobile service for few weeks, I might suggest just maybe restart the service in portal and republish. I have hit some weird unexplained stuff just like you are and somehow fix like that.

What is StarterTemplateAppListenerHost in Service Satck?

I am doing some stuff in Service Stack self host in windows service. The link gave me some hint. But in the code, what is StarterTemplateAppListenerHost then?
It is a class which extends AppHostHttpListenerBase (Source here) which is used to provide the http listener and application configuration.
public class StarterTemplateAppListenerHost : AppHostHttpListenerBase
{
static readonly IAppSettings AppSettings = new AppSettings();
public StarterTemplateAppListenerHost()
: base(AppSettings.GetString("ServiceName") ?? "StarterTemplate HttpListener", typeof(HelloService).Assembly) { }
public override void Configure(Funq.Container container)
{
container.Register(new TodoRepository());
}
}
This is demonstrated also in the official documentation here.
I just wonder why the link doesn't have OnStart() etc
The example has two different compilation modes. When it's run in debug, it will not run as a service, and solely uses StarterTemplateAppListenerHost.
When it is run in release mode then it will create a service around the instance of StarterTemplateAppListenerHost. The WinService class provides the OnStart and OnStop methods which are expected of Windows Services by extending System.ServiceProcess.ServiceBase.
So to get it running as a Windows Service you will need to include these 3 files:
Program.cs
WinService.cs
StarterTemplateAppListenerHost.cs

Resources