Logging from a groovlet - groovy

Is there a way to write into the server log from a groovlet script? I've tried the following to no avail:
Create a class with #Log4j annotation within the groovlet (#Log4j works fine in the rest of the project)
#Log4j('LOGGER')
class Log {
static Logger getLogger() {
LOGGER
}
}
Use ServerContext instance implicit variable application:
application.log('Hello world')
Any ideas welcome, thanks.

The logs didn't appear using the first method because of Log4j filtering on log4j.properties.
I created a separate class GroovletLogger inside one of our unfiltered packages and I can log fine from groovlets.

Related

setting micronaut configuration location

I have an existing groovy micronaut app I'm trying to change where it loads its config from. I don't understand what code to write so I can set the location of the micronaut configuration. I know you can use micronaut.config.files system variable or MICRONAUT_CONFIG_FILES environment variable, but this is a terrible idea because micronaut is built into grails and therefore every grails app you have running in tomcat will pick up the same config and crash.
Nor do I know where in the code to set the config file. There's an Application class with a run() method, but I don't know if this is only called during development, or whether it gets called when deploying in Tomcat. When setting the config in a Grails app, there is an Application class extending EnvironmentAware, and you can override setEnvironment, and load external configs there, but there is no hint of that for micronaut apps.
The micronaut doco says it can load a configuration from "application.{extension}", but it doesn't say what "application" is, or what directory it expects that in, or whether you can change the directory. Is "application" the value of micronaut.application.name in one's application.yml? I couldn't seem to get it to load based on that.
Then the documentation talks about loading from a PropertySource, which is fine and all, but doesn't tell you where you can put that code to load from a PropertySource. There is mention you can pass the PropertySource to ApplicationContext.run(xx), but in this app I inherited, there is no mention of ApplicationContext, and the micronaut documentation isn't very clear what I'm supposed to do with ApplicationContext. This app I've inherited has an Application class with a main() calling Micronaut.run() which apparently returns an ApplicationContext, but it's not clear if main() is called when running in Tomcat, or whether I should be calling run() on that, when it works as is, and I'm just trying to change where it loads its config.
The question is, how do I get my micronaut app to load its config from
where I tell it to, and not from micronaut.config.file system variable
location.
I don't think we have a specific feature in the framework that allows you to tell the framework to ignore micronaut.config.files. If you would like such a feature you can request it at https://github.com/micronaut-projects/micronaut-core/issues. If that is of interest I suggest you open it up for discussion at https://github.com/micronaut-projects/micronaut-core/discussions first.
You can load external config files, from a path not set as micronaut.config.files, in the main method of the Application class before running the application. Take a look at below class which accepts a config folder location as a system property demo.config.path(can be something else) and loads yaml config files from that folder:
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import io.micronaut.context.env.PropertySource;
import io.micronaut.context.env.yaml.YamlPropertySourceLoader;
import io.micronaut.core.io.ResourceLoader;
import io.micronaut.core.io.file.DefaultFileSystemResourceLoader;
import io.micronaut.runtime.Micronaut;
public class Application {
private static final String PROP_CONFIG_LOCATION = "demo.config.path";
public static void main(String[] args) throws IOException {
if (System.getProperty(PROP_CONFIG_LOCATION) != null) {
List<PropertySource> propertySources = new ArrayList<>();
YamlPropertySourceLoader propertySourceLoader = new YamlPropertySourceLoader();
ResourceLoader resourceLoader = new DefaultFileSystemResourceLoader();
Files.newDirectoryStream(Paths.get(System.getProperty(PROP_CONFIG_LOCATION))).forEach(file -> {
String fileName = file.toString();
String fileNameWithoutExtension = fileName.substring(0, fileName.lastIndexOf('.'));
propertySourceLoader.load(fileNameWithoutExtension, resourceLoader).ifPresent(propertySources::add);
});
Micronaut.build(args)
.classes(Application.class)
.propertySources(propertySources.toArray(new PropertySource[1]))
.start();
} else {
Micronaut.run(Application.class, args);
}
}
}
As is, this code works for yaml config files(with snakeyaml in classpath). With minor changes, it can be made to work for properties files and to read config location from environment variable instead of system property. Full sample application present in github

Can I manually run a C# class containing a Main() method from a project that is not a console application project?

I am pretty new in .NET\C# (I came from Java) and I have the following doubt.
In my solution I have a project that should be a SharePoint job, something like this in my solution explorer:
I know that this project is deployed as a SharePoint job and it works fine.
Now I have the need to manually perform a specific operation that is in some way related to this job. So my idea was to create this MigrateAttachments class into this project and put a Main() method here, then perform only this class as a script:
namespace XXXMigrationJob
{
class MigrateAttachments
{
static void Main(string[] args)
{
Debug.Print("MigrateAttachments Main() START");
Debug.Print("MigrateAttachments Main() END");
}
}
}
But it seems to me that I can't perform this Main() method as a standalone method and that the only way to do it is to create a brand new Console Application project that will contain this class.
is it true or am I missing something and I can manually run this MigrateAttachements Main() method also into my XXXMigrationJob project?
No you can't really just execute that. It will be in a DLL not an exe. You'll need to bootstrap it somehow.
I would refactor the reusable code into a class library. Then create a console app as you mentioned. Reference the reusable class library and call it.
However if you don't want to create a console app, then the link NineBerry put in discusses calling .net code with PowerShell and Reflection.

How do I specify what would normally be in web.config for an Azure Function?

I'm creating an Azure Function, and I need to set this parameter what would normally go in the web.config file:
<entityFramework codeConfigurationType="xxxxxxxx">
But Azure Functions doesn't have a web.config. How do I configure stuff that isn't a simple key/value app setting?
The entity framework code is in a class library used by lots of other things, so I can't really use code based config without major hassle.
You can place it in your code. Microsoft documentation with all options is here: https://learn.microsoft.com/en-us/ef/ef6/fundamentals/configuring/code-based#moving-dbconfiguration
[DbConfigurationType(typeof(MyDbConfiguration))]
public class MyContextContext : DbContext
{
}
or
[DbConfigurationType("MyNamespace.MyDbConfiguration, MyAssembly")]
public class MyContextContext : DbContext
{
}

Why am I getting "A route named 'swagger_docs' is already in the route collection" after I publish my API App?

After publishing my API App I'm getting the yellow error screen of ASP.NET. The error message says "A route named 'swagger_docs' is already in the route collection".
How can I fix this?
This is not related to API Apps per se but more around Web API. What triggers the error is pretty simple:
You publish the API App which is based on Web API.
You discard your project and start working on a new API App based on Web API
You want to publish the new API App instead of the old API App you created at step 1.
You select the API App during "Publish.." and you get the publishing profile of the existing API App we deployed at step 1.
You deploy using Web Deploy and the publishing profile, the new API App on top of the old one.
That will trigger the issue I've explained before. That happens because there are two routes being registered by Swashbuckle when you try to start the app. One of the old one and one of the new one. That's because the old files are still present at the destination.
To solve this, during Web Deploy, click on the Settings tab and then expand the "File Publish Options". There is a checkbox there, called "Remove additional files from destination". This will fix the issue as it will only leave the files you deploy at the destination and not the old ones as well.
Hope it helps.
What if it happens when trying to debug the app locally ?
This happened for me, and the reason was, I renamed my assembly name. So the bin folder had two dlls for the same project with different names which caused this error. Once I deleted the old named dll all is well. Hope this helps.
This happens because You probally are configuring you route in your WebApiConfig class and SwaggerConfig class, as explained below:
WebApiConfig file:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
SwaggerConfig.Register();
}
}
SwaggerConfig file:
using Swashbuckle.Application;
[assembly: PreApplicationStartMethod(typeof(SwaggerConfig), "Register")]
namespace NEOH.Api
{
public class SwaggerConfig
{
public static void Register()
{
What you should do is remove the assembly call on SwaggerConfig file.
It should work.
My Solution & Cause:
I had the same problem when I renamed NamesSpaces,Refactored,etc.
After reading what everyone else did here's what I tried:
Cleaned the Solution in Visual Studio
Cleaned the Bin folder manually
Checked the nameSpace in the Project Properties (copied it just in case) >> Build tab >> Scrolldown to Output and ensure the XML documentation file is correct. You will need this name later.
Opened up: SwaggerConfig.cs >> fixed the name space in here (copy,paste) c.SingleApiVersion("vX","NameSpace")
Scrolled down until I found: GetXmlCommentsPath() copied and pasted the correct name space in the .xml file path.
Ran, smoke tested, finished this post.
My issue was that I was referencing another project that had the Swashbuckle extension.
Here is how I kept both projects without changing the anything in project that was referenced:
Remove the routes created by the project referenced under SwaggerConfig.cs > Register right before GlobalConfiguration.Configuration.EnableSwagger(...).EnableSwaggerUi(...);:
// Clears the previous routes as this solution references another Swagger ASP.NET project which adds the swagger routes.
// Trying to add the Swagger routes more than once will prevent the application from starting
GlobalConfiguration.Configuration.Routes.Clear();
Then, the application will be able to start, but you will see the operations/functions that are in both projects. To remove the operations from the project being referenced...
Create the following class
using Swashbuckle.Swagger;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http.Description;
namespace yournamespace.Models
{
/// <summary>
/// This class allows to manage the Swagger document filters.
/// </summary>
public class SwaggerCustomOperationsFilter : IDocumentFilter
{
/// <summary>
/// Applies the Swagger operation filter to exclude the Swagger operations/functions
/// that are inherited by the other Swagger projects referenced.
/// </summary>
///
/// <param name="p_swaggerDoc">Swagger document</param>
/// <param name="p_schemaRegistry">Swagger schema registry</param>
/// <param name="p_apiExplorer">Api description collection</param>
public void Apply(SwaggerDocument p_swaggerDoc, SchemaRegistry p_schemaRegistry, IApiExplorer p_apiExplorer)
{
IEnumerable<ApiDescription> externalApiDescriptions = p_apiExplorer.ApiDescriptions
.Where(d => d.ActionDescriptor.ControllerDescriptor.ControllerType.Module.Name != GetType().Module.Name);
IEnumerable<int> externalApiDescriptionIndexes = externalApiDescriptions
.Select(d => p_apiExplorer.ApiDescriptions.IndexOf(d))
.OrderByDescending(i => i);
IEnumerable<string> externalPaths = externalApiDescriptions.Select(d => $"/{d.RelativePathSansQueryString()}");
foreach (string path in externalPaths)
{
p_swaggerDoc.paths.Remove(path);
}
foreach (int apiDescriptionIndex in externalApiDescriptionIndexes)
{
p_apiExplorer.ApiDescriptions.RemoveAt(apiDescriptionIndex);
}
}
}
}
And add the following in SwaggerConfig.cs > Register > GlobalConfiguration.Configuration.EnableSwagger(...)
c.DocumentFilter<SwaggerCustomOperationsFilter>();
Alternative cause of this problem:
Seems like a lot of people have this issue resolved by deleting their "bin" and "obj" folders as per the other answers.
However the cause of the issue might be that you are configuring your Swagger Config in a referenced project, as per this comment: https://github.com/domaindrivendev/Swashbuckle/issues/364#issuecomment-226013593
I received this error when one project with Swagger referenced another
project with Swagger. Removing the reference fixed the problem.
This caused me to split some core functionality out into a Third project that both of my API's could reference, rather than them referencing each other.

How to configure a default target in NLog

I am trying to convert existing logging library used by a bunch of apps to use NLog. The existing logging code has no indirection, logging calls go straight from the caller to a webservice call. The existing logging code is implemented as a static singleton. I need to do this in such a way that existing applications that use this library do not need configuration or code changes when they pick up the changed logging library. Later I can go update applications on an as needed basis, configuring a new logging target or changing the code to log to NLog directly.
To do this, I was going to make the static logging code go through NLog. Existing logging calls will be routed through NLog, and the existing webservice call will be wrapped in a custom NLog target.
To make this work on legacy apps without changing them, I need to programmatically set the custom target as the default (when none are configured in a config file). I'd like to do this without making config changes on the numerous existing applications, so I need to do this programmatically.
The problem is... its not working. Any thoughts on this approach? Below is the code I tried to add to hook in the existing logger class to create the default target.
I wouldn't mind going to log4net either. Just looking at the APIs I chose NLog initially as the names made more sense to me.
public static class LegacyLogger
{
static LegacyLogger()
{
if (LogManager.Configuration == null
|| LogManager.Configuration.GetConfiguredNamedTargets().Count == 0)
{
if (LogManager.Configuration == null)
{
LogManager.Configuration = new LoggingConfiguration();
}
//LogManager.Configuration.AddTarget("LegacyLogger", new NLog.Targets.DebuggerTarget());
LogManager.Configuration.AddTarget("LegacyLogger", new LegacyLoggerTarget());
}
_logger = LogManager.GetCurrentClassLogger();
}
Ok, if you're new to NLog, as I was, be advised the examples installed with the installer cover about everything. In this case, I needed:
public static class LegacyLogger
{
static LegacyLogger()
{
if (LogManager.Configuration == null
|| LogManager.Configuration.GetConfiguredNamedTargets().Count == 0)
{
NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(new LegacyLoggerTarget(), LogLevel.Trace);
}
_logger = LogManager.GetCurrentClassLogger();
}

Resources