How to use followLogs method of org.testcontainers.containers.DockerComposeContainer class

Best Testcontainers-java code snippet using org.testcontainers.containers.DockerComposeContainer.followLogs

Source:DockerComposeContainer.java Github

copy

Full Screen

...192 final ComposeServiceWaitStrategyTarget containerInstance = new ComposeServiceWaitStrategyTarget(container,193 ambassadorContainer, ambassadorPortMappings.getOrDefault(serviceName, new HashMap<>()));194 String containerId = containerInstance.getContainerId();195 if (tailChildContainers) {196 followLogs(containerId, new Slf4jLogConsumer(log).withPrefix(container.getNames()[0]));197 }198 //follow logs using registered consumers for this service199 logConsumers.getOrDefault(serviceName, Collections.emptyList()).forEach(consumer -> followLogs(containerId, consumer));200 serviceInstanceMap.putIfAbsent(serviceName, containerInstance);201 }202 private void waitUntilServiceStarted(String serviceName, ComposeServiceWaitStrategyTarget serviceInstance) {203 final WaitAllStrategy waitAllStrategy = waitStrategyMap.get(serviceName);204 if(waitAllStrategy != null) {205 waitAllStrategy.waitUntilReady(serviceInstance);206 }207 }208 private String getServiceNameFromContainer(Container container) {209 final String containerName = container.getLabels().get("com.docker.compose.service");210 final String containerNumber = container.getLabels().get("com.docker.compose.container-number");211 return String.format("%s_%s", containerName, containerNumber);212 }213 private void runWithCompose(String cmd) {214 checkNotNull(composeFiles);215 checkArgument(!composeFiles.isEmpty(), "No docker compose file have been provided");216 final DockerCompose dockerCompose;217 if (localCompose) {218 dockerCompose = new LocalDockerCompose(composeFiles, project);219 } else {220 dockerCompose = new ContainerisedDockerCompose(composeFiles, project);221 }222 dockerCompose223 .withCommand(cmd)224 .withEnv(env)225 .invoke();226 }227 private void registerContainersForShutdown() {228 ResourceReaper.instance().registerFilterForCleanup(Arrays.asList(229 new SimpleEntry<>("label", "com.docker.compose.project=" + project)230 ));231 }232 private List<Container> listChildContainers() {233 return dockerClient.listContainersCmd()234 .withShowAll(true)235 .exec().stream()236 .filter(container -> Arrays.stream(container.getNames()).anyMatch(name ->237 name.startsWith("/" + project)))238 .collect(toList());239 }240 private void startAmbassadorContainers() {241 if (!ambassadorPortMappings.isEmpty()) {242 ambassadorContainer.start();243 }244 }245 @Override246 public void stop() {247 synchronized (MUTEX) {248 try {249 // shut down the ambassador container250 ambassadorContainer.stop();251 // Kill the services using docker-compose252 String cmd = "down -v";253 if (removeImages != null) {254 cmd += " --rmi " + removeImages.dockerRemoveImagesType();255 }256 runWithCompose(cmd);257 } finally {258 project = randomProjectId();259 }260 }261 }262 public SELF withExposedService(String serviceName, int servicePort) {263 return withExposedService(serviceName, servicePort, Wait.defaultWaitStrategy());264 }265 public DockerComposeContainer withExposedService(String serviceName, int instance, int servicePort) {266 return withExposedService(serviceName + "_" + instance, servicePort);267 }268 public DockerComposeContainer withExposedService(String serviceName, int instance, int servicePort, WaitStrategy waitStrategy) {269 return withExposedService(serviceName + "_" + instance, servicePort, waitStrategy);270 }271 public SELF withExposedService(String serviceName, int servicePort, @NonNull WaitStrategy waitStrategy) {272 String serviceInstanceName = getServiceInstanceName(serviceName);273 /*274 * For every service/port pair that needs to be exposed, we register a target on an 'ambassador container'.275 *276 * The ambassador container's role is to link (within the Docker network) to one of the277 * compose services, and proxy TCP network I/O out to a port that the ambassador container278 * exposes.279 *280 * This avoids the need for the docker compose file to explicitly expose ports on all the281 * services.282 *283 * {@link GenericContainer} should ensure that the ambassador container is on the same network284 * as the rest of the compose environment.285 */286 // Ambassador container will be started together after docker compose has started287 int ambassadorPort = nextAmbassadorPort.getAndIncrement();288 ambassadorPortMappings.computeIfAbsent(serviceInstanceName, __ -> new ConcurrentHashMap<>()).put(servicePort, ambassadorPort);289 ambassadorContainer.withTarget(ambassadorPort, serviceInstanceName, servicePort);290 ambassadorContainer.addLink(new FutureContainer(this.project + "_" + serviceInstanceName), serviceInstanceName);291 addWaitStrategy(serviceInstanceName, waitStrategy);292 return self();293 }294 private String getServiceInstanceName(String serviceName) {295 String serviceInstanceName = serviceName;296 if (!serviceInstanceName.matches(".*_[0-9]+")) {297 serviceInstanceName += "_1"; // implicit first instance of this service298 }299 return serviceInstanceName;300 }301 /*302 * can have multiple wait strategies for a single container, e.g. if waiting on several ports303 * if no wait strategy is defined, the WaitAllStrategy will return immediately.304 * The WaitAllStrategy uses an long timeout, because timeouts should be handled by the inner strategies.305 */306 private void addWaitStrategy(String serviceInstanceName, @NonNull WaitStrategy waitStrategy) {307 final WaitAllStrategy waitAllStrategy = waitStrategyMap.computeIfAbsent(serviceInstanceName, __ ->308 new WaitAllStrategy(WaitAllStrategy.Mode.WITH_MAXIMUM_OUTER_TIMEOUT).withStartupTimeout(Duration.ofMinutes(30)));309 waitAllStrategy.withStrategy(waitStrategy);310 }311 /**312 Specify the {@link WaitStrategy} to use to determine if the container is ready.313 *314 * @see org.testcontainers.containers.wait.strategy.Wait#defaultWaitStrategy()315 * @param serviceName the name of the service to wait for316 * @param waitStrategy the WaitStrategy to use317 * @return this318 */319 public SELF waitingFor(String serviceName, @NonNull WaitStrategy waitStrategy) {320 String serviceInstanceName = getServiceInstanceName(serviceName);321 addWaitStrategy(serviceInstanceName, waitStrategy);322 return self();323 }324 /**325 * Get the host (e.g. IP address or hostname) that an exposed service can be found at, from the host machine326 * (i.e. should be the machine that's running this Java process).327 * <p>328 * The service must have been declared using DockerComposeContainer#withExposedService.329 *330 * @param serviceName the name of the service as set in the docker-compose.yml file.331 * @param servicePort the port exposed by the service container.332 * @return a host IP address or hostname that can be used for accessing the service container.333 */334 public String getServiceHost(String serviceName, Integer servicePort) {335 return ambassadorContainer.getContainerIpAddress();336 }337 /**338 * Get the port that an exposed service can be found at, from the host machine339 * (i.e. should be the machine that's running this Java process).340 * <p>341 * The service must have been declared using DockerComposeContainer#withExposedService.342 *343 * @param serviceName the name of the service as set in the docker-compose.yml file.344 * @param servicePort the port exposed by the service container.345 * @return a port that can be used for accessing the service container.346 */347 public Integer getServicePort(String serviceName, Integer servicePort) {348 Map<Integer, Integer> portMap = ambassadorPortMappings.get(getServiceInstanceName(serviceName));349 if (portMap == null) {350 throw new IllegalArgumentException("Could not get a port for '" + serviceName + "'. " +351 "Testcontainers does not have an exposed port configured for '" + serviceName + "'. "+352 "To fix, please ensure that the service '" + serviceName + "' has ports exposed using .withExposedService(...)");353 } else {354 return ambassadorContainer.getMappedPort(portMap.get(servicePort));355 }356 }357 public SELF withScaledService(String serviceBaseName, int numInstances) {358 scalingPreferences.put(serviceBaseName, numInstances);359 return self();360 }361 public SELF withEnv(String key, String value) {362 env.put(key, value);363 return self();364 }365 public SELF withEnv(Map<String, String> env) {366 env.forEach(this.env::put);367 return self();368 }369 /**370 * Use a local Docker Compose binary instead of a container.371 *372 * @return this instance, for chaining373 */374 public SELF withLocalCompose(boolean localCompose) {375 this.localCompose = localCompose;376 return self();377 }378 /**379 * Whether to pull images first.380 *381 * @return this instance, for chaining382 */383 public SELF withPull(boolean pull) {384 this.pull = pull;385 return self();386 }387 /**388 * Whether to tail child container logs.389 *390 * @return this instance, for chaining391 */392 public SELF withTailChildContainers(boolean tailChildContainers) {393 this.tailChildContainers = tailChildContainers;394 return self();395 }396 /**397 * Attach an output consumer at container startup, enabling stdout and stderr to be followed, waited on, etc.398 * <p>399 * More than one consumer may be registered.400 *401 * @param serviceName the name of the service as set in the docker-compose.yml file402 * @param consumer consumer that output frames should be sent to403 * @return this instance, for chaining404 */405 public SELF withLogConsumer(String serviceName, Consumer<OutputFrame> consumer) {406 String serviceInstanceName = getServiceInstanceName(serviceName);407 final List<Consumer<OutputFrame>> consumers = this.logConsumers.getOrDefault(serviceInstanceName, new ArrayList<>());408 consumers.add(consumer);409 this.logConsumers.putIfAbsent(serviceInstanceName, consumers);410 return self();411 }412 /**413 * Whether to always build images before starting containers.414 *415 * @return this instance, for chaining416 */417 public SELF withBuild(boolean build) {418 this.build = build;419 return self();420 }421 /**422 * Remove images after containers shutdown.423 *424 * @return this instance, for chaining425 */426 public SELF withRemoveImages(RemoveImages removeImages) {427 this.removeImages = removeImages;428 return self();429 }430 public Optional<ContainerState> getContainerByServiceName(String serviceName) {431 return Optional.ofNullable(serviceInstanceMap.get(serviceName));432 }433 private void followLogs(String containerId, Consumer<OutputFrame> consumer) {434 LogUtils.followOutput(DockerClientFactory.instance().client(), containerId, consumer);435 }436 private SELF self() {437 return (SELF) this;438 }439 private String randomProjectId() {440 return identifier + Base58.randomString(6).toLowerCase();441 }442 public enum RemoveImages {443 /**444 * Remove all images used by any service.445 */446 ALL("all"),447 /**...

Full Screen

Full Screen

followLogs

Using AI Code Generation

copy

Full Screen

1import org.testcontainers.containers.DockerComposeContainer2import org.testcontainers.containers.output.Slf4jLogConsumer3import org.testcontainers.containers.output.ToStringConsumer4def compose = new DockerComposeContainer(new File("docker-compose.yml"))5 .withLocalCompose(true)6 .withExposedService("db", 5432)7 .withExposedService("app", 8080)8 .withLogConsumer("app", new Slf4jLogConsumer(log))9 .withLogConsumer("db", new ToStringConsumer())10compose.start()11compose.followLogs("app")12compose.stop()13[INFO] --- maven-failsafe-plugin:3.0.0-M4:integration-test (default) @ testcontainers ---

Full Screen

Full Screen

followLogs

Using AI Code Generation

copy

Full Screen

1DockerComposeContainer container = new DockerComposeContainer(new File("docker-compose.yml"))2 .withLocalCompose(true)3 .withExposedService("app_1", 8080);4container.start();5container.followOutput(new Slf4jLogConsumer(logger));6container.followLogs("app_1", new Slf4jLogConsumer(logger));7container.followLogs("app_1", new Slf4jLogConsumer(logger).withSeparateOutputStreams());8container.followLogs("app_1", new Slf4jLogConsumer(logger).withPrefix("app_1"));9container.followLogs("app_1", new Slf4jLogConsumer(logger).withTimestamps());10container.followLogs("app_1", new Slf4jLogConsumer(logger).withStdErrSeparatePrefix("app_1_err"));11container.followLogs("app_1", new Slf4jLogConsumer(logger).withStdOutSeparatePrefix("app_1_out"));12container.followLogs("app_1", new Slf4jLogConsumer(logger).withStdErrConsumer(new Slf4jLogConsumer(logger).withPrefix("app_1_err")));13container.followLogs("app_1", new Slf4jLogConsumer(logger).withStdOutConsumer(new Slf4jLogConsumer(logger).withPrefix("app_1_out")));14container.followLogs("app_1", new Slf4jLogConsumer(logger).withStdErrConsumer(new Slf4jLogConsumer(logger).withPrefix("app_1_err")).withStdOutConsumer(new Slf4jLogConsumer(logger).withPrefix("app_1_out")));15container.followLogs("app_1", new Slf4jLogConsumer(logger).withStdErrConsumer(new Slf4jLogConsumer(logger).withPrefix("app_1_err")).withStdOutConsumer(new Slf4jLogConsumer(logger).withPrefix("app_1_out")));16container.followLogs("app_1", new Slf4jLogConsumer(logger).withStdErrConsumer(new Slf4jLogConsumer(logger).withPrefix("app_1_err")).withStdOutConsumer(new Slf4jLogConsumer(logger).withPrefix("app_1_out")));17container.followLogs("app_1", new Slf4jLogConsumer(logger).withStdErrConsumer(new Slf4jLogConsumer(logger).withPrefix("app_1_err")).withStdOutConsumer(new Slf4jLogConsumer

Full Screen

Full Screen

followLogs

Using AI Code Generation

copy

Full Screen

1import org.testcontainers.containers.DockerComposeContainer2import org.testcontainers.containers.wait.strategy.Wait3import org.testcontainers.containers.wait.strategy.WaitAllStrategy4import org.testcontainers.containers.wait.strategy.WaitStrategy5def composeFile = new File("docker-compose.yml")6def compose = new DockerComposeContainer(composeFile)7compose.start()8compose.followLogs(new File("logs/compose.log"))9compose.stop()10compose = new DockerComposeContainer(composeFile)11compose.withExposedService("web", 8080, Wait.forHttp("/"))12compose.withExposedService("db", 5432, Wait.forListeningPort())13compose.withExposedService("adminer", 8081, Wait.forHttp("/"))14compose.start()15compose.followLogs(new File("logs/compose.log"))16compose.stop()17compose = new DockerComposeContainer(composeFile)18compose.withExposedService("web", 8080, Wait.forHttp("/"))19compose.withExposedService("db", 5432, Wait.forListeningPort())20compose.withExposedService("adminer", 8081, Wait.forHttp("/"))21compose.start()22compose.followLogs(new File("logs/compose.log"))

Full Screen

Full Screen

followLogs

Using AI Code Generation

copy

Full Screen

1DockerComposeContainer dockerComposeContainer = new DockerComposeContainer(new File("docker-compose.yml"));2dockerComposeContainer.followOutput(new Slf4jLogConsumer(log));3dockerComposeContainer.start();4DockerComposeContainer dockerComposeContainer = new DockerComposeContainer(new File("docker-compose.yml"));5dockerComposeContainer.followOutput(new Slf4jLogConsumer(log));6dockerComposeContainer.start();7DockerComposeContainer dockerComposeContainer = new DockerComposeContainer(new File("docker-compose.yml"));8dockerComposeContainer.followOutput(new Slf4jLogConsumer(log));9dockerComposeContainer.start();10DockerComposeContainer dockerComposeContainer = new DockerComposeContainer(new File("docker-compose.yml"));11dockerComposeContainer.followOutput(new Slf4jLogConsumer(log));12dockerComposeContainer.start();13DockerComposeContainer dockerComposeContainer = new DockerComposeContainer(new File("docker-compose.yml"));14dockerComposeContainer.followOutput(new Sl

Full Screen

Full Screen

followLogs

Using AI Code Generation

copy

Full Screen

1import org.testcontainers.containers.DockerComposeContainer2import org.testcontainers.containers.output.OutputFrame3import org.testcontainers.containers.output.ToStringConsumer4import org.testcontainers.containers.output.WaitingConsumer5import org.testcontainers.containers.wait.strategy.Wait6import org.testcontainers.containers.wait.strategy.WaitAllStrategy7import org.testcontainers.containers.wait.strategy.WaitStrategy8import org.testcontainers.utility.MountableFile9import java.io.File10import java.time.Duration11File.createTempFile("docker-compose", ".yml").apply {12 writeText("""13 command: /bin/sh -c "while true; do echo 'service1'; sleep 1; done"14 command: /bin/sh -c "while true; do echo 'service2'; sleep 1; done"15 """.trimIndent())16}17File.createTempFile("docker-compose", ".yml").apply {18 writeText("""19 command: /bin/sh -c "while true; do echo 'service1'; sleep 1; done"20 command: /bin/sh -c "while true; do echo 'service2'; sleep 1; done"

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful