--- title: Logging & Debugging description: Retrieve active expectations, recorded requests, logs, and metrics from MockServer to diagnose matching failures and integration issues. layout: page pageOrder: 2 section: 'Operations' subsection: true sitemap: priority: 0.7 changefreq: 'monthly' lastmod: 2019-11-10T08:00:00+01:00 ---
If your expectations are not matching requests, see the Troubleshooting Matching guide for a step-by-step debugging checklist and common pitfalls.
MockServer supports the following features to simplify debugging
Retrieve the following items:
Most retrieval endpoints use PUT /mockserver/retrieve with a type query parameter; metrics and configuration are separate GET endpoints (see table). Java client methods take an optional request matcher (pass null to retrieve everything). Click the row to jump to full code examples.
Instead of a request matcher you can send an expectation id — the body {"id": "..."}, or the ...ById client methods — just as you can when clearing or verifying. For ACTIVE_EXPECTATIONS that returns only the expectation with that id; for the other types it returns the entries matching that expectation's request. An id that does not exist is rejected with 400 No expectation found with id ....
| What you retrieve | REST path | Java client method | Returns |
|---|---|---|---|
| Active expectations | PUT /mockserver/retrieve?type=ACTIVE_EXPECTATIONS | retrieveActiveExpectations() | Expectation array |
| Recorded expectations | PUT /mockserver/retrieve?type=RECORDED_EXPECTATIONS | retrieveRecordedExpectations() | Expectation array |
| Recorded requests | PUT /mockserver/retrieve?type=REQUESTS | retrieveRecordedRequests() | HttpRequest array |
| Recorded requests & responses | PUT /mockserver/retrieve?type=REQUEST_RESPONSES | retrieveRecordedRequestsAndResponses() | LogEventRequestAndResponse array |
| Logs | PUT /mockserver/retrieve?type=LOGS | retrieveLogMessagesArray() | String array |
| Metrics | GET /mockserver/metrics | retrieveMetrics() (JSON counter snapshot via PUT /mockserver/retrieve?type=METRICS; the Prometheus text endpoint itself has no client accessor) | Prometheus text format |
| Configuration | GET /mockserver/configuration | retrieveConfiguration() | JSON |
It is possible to retrieve the active expectations, as show below in the code examples.
Expectations are returned in the order they have been added. The expectations are returned can be filter using a request matcher, or narrowed to a single expectation using its expectation id.
Expectation[] activeExpectations = new MockServerClient("localhost", 1080)
.retrieveActiveExpectations(
request()
);
var mockServerClient = require('mockserver-client').mockServerClient;
mockServerClient("localhost", 1080)
.retrieveActiveExpectations({})
.then(
function (activeExpectations) {
console.log(JSON.stringify(activeExpectations));
},
function (error) {
console.log(error);
}
);
See REST API for full JSON specification
from mockserver.client import MockServerClient
from mockserver.models import HttpRequest
client = MockServerClient("localhost", 1080)
active_expectations = client.retrieve_active_expectations(
HttpRequest.request()
)
require 'mockserver-client'
client = MockServer::Client.new('localhost', 1080)
active_expectations = client.retrieve_active_expectations
import mockserver "github.com/mock-server/mockserver-monorepo/mockserver-client-go/v7"
client := mockserver.New("localhost", 1080)
activeExpectations, err := client.RetrieveActiveExpectations(nil)
using MockServer.Client;
using var client = new MockServerClient("localhost", 1080);
var activeExpectations = client.RetrieveActiveExpectations();
use mockserver_client::ClientBuilder;
let client = ClientBuilder::new("localhost", 1080).build().unwrap();
let active_expectations = client.retrieve_active_expectations(None).unwrap();
use MockServer\MockServerClient;
$client = new MockServerClient('localhost', 1080);
$activeExpectations = $client->retrieveActiveExpectations();
curl -v -X PUT "http://localhost:1080/mockserver/retrieve?type=ACTIVE_EXPECTATIONS"
See REST API for full JSON specification
Expectation[] activeExpectations = new MockServerClient("localhost", 1080)
.retrieveActiveExpectations(
request()
.withPath("/some/path")
.withMethod("POST")
);
var mockServerClient = require('mockserver-client').mockServerClient;
mockServerClient("localhost", 1080).retrieveActiveExpectations({
"path": "/some/path",
"method": "POST"
}).then(
function (activeExpectations) {
console.log(JSON.stringify(activeExpectations));
},
function (error) {
console.log(error);
}
);
See REST API for full JSON specification
from mockserver.client import MockServerClient
from mockserver.models import HttpRequest
client = MockServerClient("localhost", 1080)
active_expectations = client.retrieve_active_expectations(
HttpRequest.request(path="/some/path", method="POST")
)
require 'mockserver-client'
client = MockServer::Client.new('localhost', 1080)
active_expectations = client.retrieve_active_expectations(
request: MockServer::HttpRequest.new(path: '/some/path', method: 'POST')
)
import mockserver "github.com/mock-server/mockserver-monorepo/mockserver-client-go/v7"
client := mockserver.New("localhost", 1080)
activeExpectations, err := client.RetrieveActiveExpectations(
mockserver.Request().Path("/some/path").Method("POST"),
)
using MockServer.Client;
using MockServer.Client.Models;
using var client = new MockServerClient("localhost", 1080);
var activeExpectations = client.RetrieveActiveExpectations(
HttpRequest.Request().WithPath("/some/path").WithMethod("POST")
);
use mockserver_client::{ClientBuilder, HttpRequest};
let client = ClientBuilder::new("localhost", 1080).build().unwrap();
let active_expectations = client.retrieve_active_expectations(
Some(&HttpRequest::new().path("/some/path").method("POST"))
).unwrap();
use MockServer\MockServerClient;
use MockServer\HttpRequest;
$client = new MockServerClient('localhost', 1080);
$activeExpectations = $client->retrieveActiveExpectations(
HttpRequest::request()->path('/some/path')->method('POST')
);
curl -v -X PUT "http://localhost:1080/mockserver/retrieve?type=ACTIVE_EXPECTATIONS" -d '{
"path": "/some/path",
"method": "POST"
}'
See REST API for full JSON specification
Retrieving by expectation id returns only the expectation with that id. This differs from retrieving by request matcher, which returns every expectation whose matcher matches that request — often more than one. An id that does not exist is rejected with 400 No expectation found with id ....
The same expectation id can be sent when retrieving recorded requests, recorded request-responses, recorded expectations or log messages; for those it returns the entries matching that expectation's request, exactly as verifying by expectation id matches them.
Expectation[] activeExpectations = new MockServerClient("localhost", 1080)
.retrieveActiveExpectationsById("31e4ca35-66c6-4645-afeb-6e66c4ca0559");
var mockServerClient = require('mockserver-client').mockServerClient;
mockServerClient("localhost", 1080)
.retrieveActiveExpectationsById("31e4ca35-66c6-4645-afeb-6e66c4ca0559")
.then(
function (activeExpectations) {
console.log(JSON.stringify(activeExpectations));
},
function (error) {
console.log(error);
}
);
See REST API for full JSON specification
from mockserver.client import MockServerClient
client = MockServerClient("localhost", 1080)
active_expectations = client.retrieve_active_expectations_by_id("31e4ca35-66c6-4645-afeb-6e66c4ca0559")
require 'mockserver-client'
client = MockServer::Client.new('localhost', 1080)
active_expectations = client.retrieve_active_expectations_by_id('31e4ca35-66c6-4645-afeb-6e66c4ca0559')
import mockserver "github.com/mock-server/mockserver-monorepo/mockserver-client-go/v7"
client := mockserver.New("localhost", 1080)
activeExpectations, err := client.RetrieveActiveExpectationsByID("31e4ca35-66c6-4645-afeb-6e66c4ca0559")
using MockServer.Client;
using var client = new MockServerClient("localhost", 1080);
var activeExpectations = client.RetrieveActiveExpectationsById("31e4ca35-66c6-4645-afeb-6e66c4ca0559");
use mockserver_client::ClientBuilder;
let client = ClientBuilder::new("localhost", 1080).build().unwrap();
let active_expectations = client
.retrieve_active_expectations_by_id("31e4ca35-66c6-4645-afeb-6e66c4ca0559")
.unwrap();
use MockServer\MockServerClient;
$client = new MockServerClient('localhost', 1080);
$activeExpectations = $client->retrieveActiveExpectationsById('31e4ca35-66c6-4645-afeb-6e66c4ca0559');
curl -v -X PUT "http://localhost:1080/mockserver/retrieve?type=ACTIVE_EXPECTATIONS" -d '{
"id": "31e4ca35-66c6-4645-afeb-6e66c4ca0559"
}'
See REST API for full JSON specification
String activeExpectations = new MockServerClient("localhost", 1080)
.retrieveActiveExpectations(
request()
.withPath("/some/path")
.withMethod("POST"),
Format.JAVA
);
var mockServerClient = require('mockserver-client').mockServerClient;
mockServerClient("localhost", 1080).retrieveExpectationsAsCode("java", {
"path": "/some/path",
"method": "POST"
}).then(
function (activeExpectations) {
// activeExpectations is the generated Java setup code as a String
console.log(activeExpectations);
},
function (error) {
console.log(error);
}
);
See REST API for full JSON specification
from mockserver.client import MockServerClient
from mockserver.models import HttpRequest
client = MockServerClient("localhost", 1080)
# returns the expectations rendered as Java setup code
active_expectations = client.retrieve_expectations_as_code(
"java", HttpRequest.request(path="/some/path")
)
require 'mockserver-client'
client = MockServer::Client.new('localhost', 1080)
# returns the expectations rendered as Java setup code
active_expectations = client.retrieve_expectations_as_code(
format: 'java',
request: MockServer::HttpRequest.new(path: '/some/path')
)
import mockserver "github.com/mock-server/mockserver-monorepo/mockserver-client-go/v7"
client := mockserver.New("localhost", 1080)
// returns the expectations rendered as Java setup code
activeExpectations, err := client.RetrieveExpectationsAsCode(
mockserver.Request().Path("/some/path"),
mockserver.FormatJava,
)
using MockServer.Client;
using MockServer.Client.Models;
using var client = new MockServerClient("localhost", 1080);
// returns the expectations rendered as Java setup code
var activeExpectations = client.RetrieveExpectationsAsCode(
"java",
HttpRequest.Request().WithPath("/some/path")
);
use mockserver_client::{ClientBuilder, HttpRequest, RetrieveFormat};
let client = ClientBuilder::new("localhost", 1080).build().unwrap();
// returns the expectations rendered as Java setup code
let active_expectations = client.retrieve_expectations_as_code(
RetrieveFormat::Java,
Some(&HttpRequest::new().path("/some/path"))
).unwrap();
use MockServer\MockServerClient;
use MockServer\HttpRequest;
$client = new MockServerClient('localhost', 1080);
// returns the expectations rendered as Java setup code
$activeExpectations = $client->retrieveExpectationsAsCode(
'java',
HttpRequest::request()->path('/some/path')
);
curl -v -X PUT "http://localhost:1080/mockserver/retrieve?type=ACTIVE_EXPECTATIONS&format=JAVA" -d '{
"path": "/some/path"
}'
See REST API for full JSON specification
String activeExpectations = new MockServerClient("localhost", 1080)
.retrieveActiveExpectations(
request()
.withPath("/some/path")
.withMethod("POST"),
Format.JSON
);
var mockServerClient = require('mockserver-client').mockServerClient;
mockServerClient("localhost", 1080).retrieveActiveExpectations({
"path": "/some/path",
"method": "POST"
}).then(
function (activeExpectations) {
console.log(JSON.stringify(activeExpectations));
},
function (error) {
console.log(error);
}
);
See REST API for full JSON specification
from mockserver.client import MockServerClient
from mockserver.models import HttpRequest
client = MockServerClient("localhost", 1080)
# Python client always returns JSON-deserialized objects
active_expectations = client.retrieve_active_expectations(
HttpRequest.request(path="/some/path", method="POST")
)
require 'mockserver-client'
client = MockServer::Client.new('localhost', 1080)
# Ruby client always returns parsed JSON objects
active_expectations = client.retrieve_active_expectations(
request: MockServer::HttpRequest.new(path: '/some/path')
)
import mockserver "github.com/mock-server/mockserver-monorepo/mockserver-client-go/v7"
client := mockserver.New("localhost", 1080)
// Go client always returns JSON-deserialized structs
activeExpectations, err := client.RetrieveActiveExpectations(
mockserver.Request().Path("/some/path"),
)
using MockServer.Client;
using MockServer.Client.Models;
using var client = new MockServerClient("localhost", 1080);
// .NET client always returns deserialized objects
var activeExpectations = client.RetrieveActiveExpectations(
HttpRequest.Request().WithPath("/some/path")
);
use mockserver_client::{ClientBuilder, HttpRequest};
let client = ClientBuilder::new("localhost", 1080).build().unwrap();
// Rust client always returns deserialized structs
let active_expectations = client.retrieve_active_expectations(
Some(&HttpRequest::new().path("/some/path"))
).unwrap();
use MockServer\MockServerClient;
use MockServer\HttpRequest;
$client = new MockServerClient('localhost', 1080);
// PHP client always returns JSON-deserialized arrays
$activeExpectations = $client->retrieveActiveExpectations(
HttpRequest::request()->path('/some/path')
);
curl -v -X PUT "http://localhost:1080/mockserver/retrieve?type=ACTIVE_EXPECTATIONS&format=JSON" -d '{
"path": "/some/path"
}'
See REST API for full JSON specification
When MockServer forwards a request (in proxy mode or via a forward action), the response includes a timing field containing connection, time-to-first-byte, and total round-trip timing information. This is included in retrieved request-response pairs and can be used to monitor upstream service latency or detect connectivity issues during testing.
The timing object contains:
Example response with timing information (as returned by the retrieve request-response API):
{
"httpRequest": {
"method": "GET",
"path": "/api/users"
},
"httpResponse": {
"statusCode": 200,
"body": "...",
"timing": {
"connectionTimeInMillis": 15,
"timeToFirstByteInMillis": 85,
"totalTimeInMillis": 142
}
}
}
Timings are available when retrieving recorded request-response pairs via the REST API:
curl -v -X PUT "http://localhost:1080/mockserver/retrieve?type=REQUEST_RESPONSES&format=JSON"
For a detailed guide on using these timing fields to diagnose slow or intermittently slow upstream services — including HAR export with timing breakdowns, slow-request flagging, and Prometheus latency percentiles — see Network Latency Debugging.
MockServer and the proxy record log messages for all major actions, including:
Note: When MockServer is used as a proxy (forwarding requests to destination servers), the logs include both the original request and the actual response received from the destination server. These are logged with type FORWARDED_REQUEST and can be filtered in the dashboard or retrieved programmatically.
It is possible to retrieve the recorded log messages, as show below in the code examples.
Log messages are returned in the order they have been recorded, and which log messages are returned can be filter using a request matcher.
String logMessages = new MockServerClient("localhost", 1080)
.retrieveLogMessages(
request()
);
var mockServerClient = require('mockserver-client').mockServerClient;
mockServerClient("localhost", 1080)
.retrieveLogMessages({})
.then(
function (logMessages) {
// logMessages is a String[]
console.log(logMessages);
},
function (error) {
console.log(error);
}
);
See REST API for full JSON specification
from mockserver.client import MockServerClient
from mockserver.models import HttpRequest
client = MockServerClient("localhost", 1080)
log_messages = client.retrieve_log_messages(
HttpRequest.request()
)
require 'mockserver-client'
client = MockServer::Client.new('localhost', 1080)
log_messages = client.retrieve_log_messages
import mockserver "github.com/mock-server/mockserver-monorepo/mockserver-client-go/v7"
client := mockserver.New("localhost", 1080)
logMessages, err := client.RetrieveLogMessages(nil)
using MockServer.Client;
using var client = new MockServerClient("localhost", 1080);
var logMessages = client.RetrieveLogMessages();
use mockserver_client::ClientBuilder;
let client = ClientBuilder::new("localhost", 1080).build().unwrap();
let log_messages = client.retrieve_log_messages(None).unwrap();
use MockServer\MockServerClient;
$client = new MockServerClient('localhost', 1080);
$logMessages = $client->retrieveLogMessages();
curl -v -X PUT "http://localhost:1080/mockserver/retrieve?type=LOGS"
See REST API for full JSON specification
String logMessages = new MockServerClient("localhost", 1080)
.retrieveLogMessages(
request()
.withPath("/some/path")
.withMethod("POST")
);
var mockServerClient = require('mockserver-client').mockServerClient;
mockServerClient("localhost", 1080)
.retrieveLogMessages({
"path": "/some/path",
"method": "POST"
})
.then(
function (logMessages) {
// logMessages is a String[]
console.log(logMessages);
},
function (error) {
console.log(error);
}
);
See REST API for full JSON specification
from mockserver.client import MockServerClient
from mockserver.models import HttpRequest
client = MockServerClient("localhost", 1080)
log_messages = client.retrieve_log_messages(
HttpRequest.request(path="/some/path", method="POST")
)
require 'mockserver-client'
client = MockServer::Client.new('localhost', 1080)
log_messages = client.retrieve_log_messages(
request: MockServer::HttpRequest.new(path: '/some/path', method: 'POST')
)
import mockserver "github.com/mock-server/mockserver-monorepo/mockserver-client-go/v7"
client := mockserver.New("localhost", 1080)
logMessages, err := client.RetrieveLogMessages(
mockserver.Request().Path("/some/path").Method("POST"),
)
using MockServer.Client;
using MockServer.Client.Models;
using var client = new MockServerClient("localhost", 1080);
var logMessages = client.RetrieveLogMessages(
HttpRequest.Request().WithPath("/some/path").WithMethod("POST")
);
use mockserver_client::{ClientBuilder, HttpRequest};
let client = ClientBuilder::new("localhost", 1080).build().unwrap();
let log_messages = client.retrieve_log_messages(
Some(&HttpRequest::new().path("/some/path").method("POST"))
).unwrap();
use MockServer\MockServerClient;
use MockServer\HttpRequest;
$client = new MockServerClient('localhost', 1080);
$logMessages = $client->retrieveLogMessages(
HttpRequest::request()->path('/some/path')->method('POST')
);
curl -v -X PUT "http://localhost:1080/mockserver/retrieve?type=LOGS" -d '{
"path": "/some/path",
"method": "POST"
}'
See REST API for full JSON specification
String[] logMessages = new MockServerClient("localhost", 1080)
.retrieveLogMessagesArray(
request()
.withPath("/some/path")
);
var mockServerClient = require('mockserver-client').mockServerClient;
mockServerClient("localhost", 1080)
.retrieveLogMessages({
"path": "/some/path"
})
.then(
function (logMessages) {
// logMessages is a String[]
console.log(logMessages);
},
function (error) {
console.log(error);
}
);
See REST API for full JSON specification
from mockserver.client import MockServerClient
from mockserver.models import HttpRequest
client = MockServerClient("localhost", 1080)
# returns a list of log message strings
log_messages = client.retrieve_log_messages(
HttpRequest.request(path="/some/path")
)
require 'mockserver-client'
client = MockServer::Client.new('localhost', 1080)
# returns an array of log message strings
log_messages = client.retrieve_log_messages(
request: MockServer::HttpRequest.new(path: '/some/path')
)
import mockserver "github.com/mock-server/mockserver-monorepo/mockserver-client-go/v7"
client := mockserver.New("localhost", 1080)
// returns raw JSON bytes containing log messages
logMessages, err := client.RetrieveLogMessages(
mockserver.Request().Path("/some/path"),
)
using MockServer.Client;
using MockServer.Client.Models;
using var client = new MockServerClient("localhost", 1080);
// returns List<string>
var logMessages = client.RetrieveLogMessages(
HttpRequest.Request().WithPath("/some/path")
);
use mockserver_client::{ClientBuilder, HttpRequest};
let client = ClientBuilder::new("localhost", 1080).build().unwrap();
// returns Vec<String>
let log_messages = client.retrieve_log_messages(
Some(&HttpRequest::new().path("/some/path"))
).unwrap();
use MockServer\MockServerClient;
use MockServer\HttpRequest;
$client = new MockServerClient('localhost', 1080);
// returns an array of log message strings/arrays
$logMessages = $client->retrieveLogMessages(
HttpRequest::request()->path('/some/path')
);
curl -v -X PUT "http://localhost:1080/mockserver/retrieve?type=LOGS" -d '{
"path": "/some/path"
}'
See REST API for full JSON specification
It is possible to retrieve MockServer metrics as a JSON object containing counts for each metric. Metrics must be enabled by setting metricsEnabled to true.
The available metrics include request counts, expectation match counts, action counts, and WebSocket connection counts.
String metrics = new MockServerClient("localhost", 1080)
.retrieveMetrics();
var mockServerClient = require('mockserver-client').mockServerClient;
mockServerClient("localhost", 1080)
.retrieveMetrics()
.then(
function (metrics) {
console.log(JSON.stringify(metrics));
},
function (error) {
console.log(error);
}
);
from mockserver.client import MockServerClient
client = MockServerClient("localhost", 1080)
metrics = client.retrieve_metrics()
require 'mockserver-client'
client = MockServer::Client.new('localhost', 1080)
metrics = client.retrieve_metrics
import mockserver "github.com/mock-server/mockserver-monorepo/mockserver-client-go/v7"
client := mockserver.New("localhost", 1080)
metrics, err := client.RetrieveMetrics()
using MockServer.Client;
using var client = new MockServerClient("localhost", 1080);
var metrics = client.RetrieveMetrics();
use mockserver_client::ClientBuilder;
let client = ClientBuilder::new("localhost", 1080).build().unwrap();
let metrics = client.retrieve_metrics().unwrap();
use MockServer\MockServerClient;
$client = new MockServerClient('localhost', 1080);
$metrics = $client->retrieveMetrics();
curl -X PUT "http://localhost:1080/mockserver/retrieve?type=METRICS"
Metrics are also available in Prometheus format via the GET /mockserver/metrics endpoint when metrics are enabled.
The current runtime configuration can be retrieved and updated via the REST API.
// retrieve current configuration
String config = new MockServerClient("localhost", 1080)
.retrieveConfiguration();
// update configuration (only the properties supplied are changed)
new MockServerClient("localhost", 1080)
.updateConfiguration("{\"logLevel\": \"DEBUG\", \"maxExpectations\": 5000}");
var mockServerClient = require('mockserver-client').mockServerClient;
var client = mockServerClient("localhost", 1080);
// retrieve current configuration
client.retrieveConfiguration().then(
function (config) {
console.log(JSON.stringify(config));
},
function (error) {
console.log(error);
}
);
// update configuration (only the properties supplied are changed)
client.updateConfiguration({
"logLevel": "DEBUG",
"maxExpectations": 5000
});
from mockserver.client import MockServerClient
client = MockServerClient("localhost", 1080)
# retrieve current configuration
config = client.retrieve_configuration()
# update configuration (only the properties supplied are changed)
client.update_configuration('{"logLevel": "DEBUG", "maxExpectations": 5000}')
require 'mockserver-client'
client = MockServer::Client.new('localhost', 1080)
# retrieve current configuration
config = client.retrieve_configuration
# update configuration (only the properties supplied are changed)
client.update_configuration('{"logLevel": "DEBUG", "maxExpectations": 5000}')
import mockserver "github.com/mock-server/mockserver-monorepo/mockserver-client-go/v7"
client := mockserver.New("localhost", 1080)
// retrieve current configuration
config, err := client.RetrieveConfiguration()
// update configuration (only the properties supplied are changed)
_, err = client.UpdateConfiguration(`{"logLevel": "DEBUG", "maxExpectations": 5000}`)
using MockServer.Client;
using var client = new MockServerClient("localhost", 1080);
// retrieve current configuration
var config = client.RetrieveConfiguration();
// update configuration (only the properties supplied are changed)
client.UpdateConfiguration(@"{""logLevel"": ""DEBUG"", ""maxExpectations"": 5000}");
use mockserver_client::ClientBuilder;
let client = ClientBuilder::new("localhost", 1080).build().unwrap();
// retrieve current configuration
let config = client.retrieve_configuration().unwrap();
// update configuration (only the properties supplied are changed)
client.update_configuration(r#"{"logLevel": "DEBUG", "maxExpectations": 5000}"#).unwrap();
use MockServer\MockServerClient;
$client = new MockServerClient('localhost', 1080);
// retrieve current configuration
$config = $client->retrieveConfiguration();
// update configuration (only the properties supplied are changed)
$client->updateConfiguration('{"logLevel": "DEBUG", "maxExpectations": 5000}');
curl -X GET "http://localhost:1080/mockserver/configuration"
curl -X PUT "http://localhost:1080/mockserver/configuration" \
-H "Content-Type: application/json" \
-d '{"logLevel": "DEBUG", "maxExpectations": 5000}'
Only the properties included in the request body are updated; all other properties retain their current values.
All interactions with the MockServer are logged including setting up expectations, matching expectations, clearing expectations and verifying requests. The log can be particularly helpful when trying to debug why a test is failing or expectations are not being matched.
The following information is logged:
The TRACE level logging results in a lot of verbose logging but can be very helpful to debug why a complex matcher (such as the JSON Schema matcher) is not matching.
To disable logging the following options can be used:
-Dmockserver.logLevel=OFF - to disable logging from the MockServer and Proxy classes-Droot.logLevel=OFF - to disable all logging from all other classesThe following sections explain how to configure logging when running MockServer via:
MockServer uses SL4J for logging so if MockSever is being launched using the JUnit 4 @Rule, the JUnit 5 Test Extension, ClientAndServer or directly using the org.mockserver.netty.MockServer the project launching MockServer needs to configure the logging output by configuring SLF4J. MockServer relies on a SLF4J binding being on the classpath for logs to be output. The simplest approach is to use the Java Logger SLF4J binding.
In MockServer the Java Logger SLF4J binding is only an optional dependency. Therefore, when MockServer is added as a dependency to a Maven or Gradle project it does not pull in the Java Logger binding transitively.
If no existing SLF4J logger binding exists no logs will be output and the following error will be displayed by SLF4J:
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
If this happens the simplest way to output logs for MockServer is to add the Java Logger SLF4J binding as a dependency. For example, in Maven this would be as follows:
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-jdk14</artifactId>
<version>1.7.29</version>
</dependency>
It is possible to configure the logger using a configuration file by specifying the java.util.logging.config.file system property, as follows.
-Djava.util.logging.config.file=/path/to/example_logging_configuration.properties
It is possible to configure the logger programmatically, for example, as follows.
ConfigurationProperties.logLevel("DEBUG");
String loggingConfiguration = "" +
"handlers=org.mockserver.logging.StandardOutConsoleHandler\n" +
"org.mockserver.logging.StandardOutConsoleHandler.level=ALL\n" +
"org.mockserver.logging.StandardOutConsoleHandler.formatter=java.util.logging.SimpleFormatter\n" +
"java.util.logging.SimpleFormatter.format=%1$tF %1$tT %3$s %4$s %5$s %6$s%n\n" +
".level=" + javaLoggerLogLevel() + "\n" +
"io.netty.handler.ssl.SslHandler.level=WARNING";
LogManager.getLogManager().readConfiguration(new ByteArrayInputStream(loggingConfiguration.getBytes(UTF_8)));
When running MockServer directly from the command line the command line argument -logLevel can be used to set the log level, as follows:
java -jar ~/Downloads/mockserver-netty-{{ site.mockserver_version }}-no-dependencies.jar -serverPort 1080 -logLevel DEBUG
Alternatively a system property mockserver.logLevel can be used to set the log level, as follows:
java -Dmockserver.logLevel=INFO -jar ~/Downloads/mockserver-netty-{{ site.mockserver_version }}-no-dependencies.jar -serverPort 1080
When running MockServer from the command line it relies on the Java Logger java.util.logging.Logger in addition to controlling the log level of MockServer using -logLevel the underlying logging framework can be configured (overriding the default configuration) by specifying the System Property java.util.logging.config.file or java.util.logging.config.class as detailed in the LogManager JavaDoc.
The MockServer github repository contains an example Java Logger configuration file (which would be configured using java.util.logging.config.file).
The default logging configuration can be overridden as follows:
java -Djava.util.logging.config.file=/path/to/example_logging_configuration.properties -jar ~/Downloads/mockserver-netty-{{ site.mockserver_version }}-no-dependencies.jar -serverPort 1080 -logLevel DEBUG
The mockserver-maven-plugin provides a logLevel settings that can be used to define the log level for all MockServer classes, as follows:
<plugin>
<groupId>org.mock-server</groupId>
<artifactId>mockserver-maven-plugin</artifactId>
<version>{{ site.mockserver_version }}</version>
<configuration>
<serverPort>1080</serverPort>
<logLevel>DEBUG</logLevel>
</configuration>
<executions>
<execution>
<id>process-test-classes</id>
<phase>process-test-classes</phase>
<goals>
<goal>runForked</goal>
</goals>
</execution>
<execution>
<id>verify</id>
<phase>verify</phase>
<goals>
<goal>stopForked</goal>
</goals>
</execution>
</executions>
</plugin>
When running MockServer using the mockserver-node Grunt plugin and Node.js (npm) module the verbose option can be used to enable INFO level logging and the trace option can be used to enable TRACE level logging.
It is generally recommended to enable verbose which should provide the correct amount of information, trace is only required for very low level debugging.
var mockserver = require('mockserver-node');
mockserver
.start_mockserver({
serverPort: 1080,
verbose: true,
trace: true
})
.then(
function () {
console.log("started MockServer");
},
function (error) {
console.log(JSON.stringify(error));
}
);
When running MockServer using the mockserver-node as a Grunt plugin module the verbose option can be used to enable INFO level logging and the trace option can be used to enable TRACE level logging. The --verbose command line flag can also be used to enable the mockserver-node verbose option from the command line.
It is generally recommended to enable verbose which should provide the correct amount of information, trace is only required for very low level debugging.
grunt.initConfig({
start_mockserver: {
options: {
serverPort: 1080,
verbose: true,
trace: true
}
},
stop_mockserver: {
options: {
serverPort: 1080
}
}
});
grunt.loadNpmTasks('mockserver-node');