I am trying to log an INFO message as follows:
LOGGER.logp(Level.INFO, "class", "method", "foo {0}",
new Object[] { "bar" });
This is using this version of logp, using the parameter insertion technique outlined here. Doing this, the logger instead outputs an error:
java.util.logging.ErrorManager: WRITE_FAILURE
Error message - Exception occurred when writing to the output stream.
Exception - java.lang.NullPointerException
If I instead do this:
LOGGER.logp(Level.INFO, "class", "method", "foo",
new Object[] {});
I get no error, and "foo" is printed out correctly. This makes it seem like something is going wrong with the insertion of the parameters into the string.
Why am I seeing write errors when I try to use the logp method with parameters?
Related
I have a Feign client which I use to get information from SonarQube and when I'm trying to test request with wrong component name I have an issue with displaying apostrophes as unicode (/u0027).
Here's the test code:
void measuresSearchHistoryUnknownTest() {
assertThatExceptionOfType(FeignException.NotFound.class)
.isThrownBy(() -> sonarFeignClient.measuresSearchHistory(
"badProject",
String.join(",",
EnumUtils.getJsonValue(SonarMetric.BLOCKER_VIOLATIONS),
EnumUtils.getJsonValue(SonarMetric.CRITICAL_VIOLATIONS)
),
1,
10
)).withMessageContaining("Component key 'badProject' not found");
// )).withMessageContaining("Component key \\u0027badProject\\u0027 not found");
}
This test works only if use last line (commented line with "\u0027badProject\u0027"), but it fails if I use previous line (with common apostrophes):
Expecting throwable message:
<"[404] during [GET] to [*******/sonar/api/measures/search_history?component=badProject&metrics=blocker_violations%2Ccritical_violations&p=1&ps=10] [SonarFeignClient#measuresSearchHistory(String,String,int,int)]: [{"errors":[{"msg":"Component key \u0027badProject\u0027 not found"}]}]">
to contain:
<"Component key 'badProject' not found">
but did not.
Throwable that failed the check:
feign.FeignException$NotFound: [404] during [GET] to [*******/sonar/api/measures/search_history?component=badProject&metrics=blocker_violations%2Ccritical_violations&p=1&ps=10] [SonarFeignClient#measuresSearchHistory(String,String,int,int)]: [{"errors":[{"msg":"Component key \u0027badProject\u0027 not found"}]}]
If I look this link in a browser SonarQube shows me JSON with error message and common apostrophes (not unicode), so I think an issue somewhere in Feign.
I use "spring-cloud-starter-openfeign:3.0.1"
Maybe someone can help me with that? How can I prevent parsing of apostrophes to Unicode?
The code in Nashorn is to parse a very simple JSON string into a JSONObject (com.alibaba.fastjson.JSONObject), simply going as:
var jso = Java.type('com.alibaba.fastjson.JSONObject').parseObject('{"name": "nothing"}');
But when ran the Java project, I received below error message:
Exception in thread "main" javax.script.ScriptException: TypeError: Java.type("com.alibaba.fastjson.JSONObject").parseObject is not a function in <eval> at line number 1
at jdk.nashorn.api.scripting.NashornScriptEngine.throwAsScriptException(NashornScriptEngine.java:470)
at jdk.nashorn.api.scripting.NashornScriptEngine.evalImpl(NashornScriptEngine.java:454)
at jdk.nashorn.api.scripting.NashornScriptEngine.evalImpl(NashornScriptEngine.java:406)
at jdk.nashorn.api.scripting.NashornScriptEngine.evalImpl(NashornScriptEngine.java:402)
at jdk.nashorn.api.scripting.NashornScriptEngine.eval(NashornScriptEngine.java:155)
at javax.script.AbstractScriptEngine.eval(AbstractScriptEngine.java:233)
...
I tried to print(Java.type('com.alibaba.fastjson.JSONObject')), and the class is obviously there with output [JavaClass com.alibaba.fastjson.JSONObject]
Anybody knows what's the root cause of this error, and how to fix it?
I have my ELK stack configured and running using log4j and everything is working fine. What I would like to be able to do is group all exceptions by their type, for example - create a terms graph and have a term for each exception type like FileNotFound, NullPointerException and so on. I already have a stack_trace field which includes the exception type at the first line, and then the complete stack trace. I found something online like this:
filter{
mutate {
gsub => [
"stack_trace", "\n.*", ""
]
}
}
but this would just override the stack_trace field with it's first line, which is not what I want. I want to add a new field that takes out the first line, the exception type, of the stack_trace field.
Make a copy of the stack trace field and perform your gsub on that
filter{
mutate {
add_field => {
"exception" => "%{stack_trace}"
}
}
mutate {
gsub => [
"exception", "\n.*", ""
]
}
}
EDIT: Thanks to #Alpha for pointing out this question, you may need to use two separate mutates.
My code is like below
#Test
public void testMyMethod(){
MyClass mc = new MyClass();
String exeVal="sometext some text";
String x=mc.exampleMethod();
// Assertion type 1
Assert.assertEquals(exeVal,x);
//Assertion Type 2
Assert.assertTrue(exeVal.equals(x));
}
I want to know which is the best approach.
Type 1 is preferred because of the assertion message you will receive when they do not match.
org.junit.ComparisonFailure: expected: <[foo]> but was: <[bar]>
vs
java.lang.AssertionError
Type 1 is preferred because of the following reasons.
It gives you a better error message.
ex:- "expected [3] but found [4]" . The second approach will evaluate the condition and will give you a message like "expected [true] but found [false]" and the user will not get the values evaluated.
AssertEquals is null safe and assertTrue isn't
What is the correct approach to log both a populated message and a stack trace of the exception?
logger.error(
"\ncontext info one two three: {} {} {}\n",
new Object[] {"1", "2", "3"},
new Exception("something went wrong"));
I'd like to produce an output similar to this:
context info one two three: 1 2 3
java.lang.Exception: something went wrong
stacktrace 0
stacktrace 1
stacktrace ...
My SLF4J version is 1.6.1.
As of SLF4J 1.6.0, in the presence of multiple parameters and if the last argument in a logging statement is an exception, then SLF4J will presume that the user wants the last argument to be treated as an exception and not a simple parameter. See also the relevant FAQ entry.
So, writing (in SLF4J version 1.7.x and later)
logger.error("one two three: {} {} {}", "a", "b",
"c", new Exception("something went wrong"));
or writing (in SLF4J version 1.6.x)
logger.error("one two three: {} {} {}", new Object[] {"a", "b",
"c", new Exception("something went wrong")});
will yield
one two three: a b c
java.lang.Exception: something went wrong
at Example.main(Example.java:13)
at java.lang.reflect.Method.invoke(Method.java:597)
at ...
The exact output will depend on the underlying framework (e.g. logback, log4j, etc) as well on how the underlying framework is configured. However, if the last parameter is an exception it will be interpreted as such regardless of the underlying framework.
In addition to #Ceki 's answer, If you are using logback and setup a config file in your project (usually logback.xml), you can define the log to plot the stack trace as well using
<encoder>
<pattern>%date |%-5level| [%thread] [%file:%line] - %msg%n%ex{full}</pattern>
</encoder>
the %ex in pattern is what makes the difference
The accepted answer is great. I'm just adding here my case that is now working thanks for the answer. This may help someone else.
I'm using SLF4J and logback with a JSON encoder. Furthermore, I use marker and arguments to enrich my output.
logger.error(getMarker("errorEvent"),
"An error occurred",
entries(mapOf("someKey" to "someValue")),
new Exception())
The output:
{
"level": "ERROR",
"event": "errorEvent",
"eventData": {
"someKey": "someValue"
},
"stacktrace": "...omitted...",
"message": "An error occurred"
}
Of course there is a lot of configuration of logstash behind the scenes, but I just wanted to show that the arguments passed as entries are shown in the configured eventData tag.