How to use stopThreadLogAppender method of com.qaprosoft.carina.core.foundation.report.ReportContext class

Best Carina code snippet using com.qaprosoft.carina.core.foundation.report.ReportContext.stopThreadLogAppender

Source:ReportContext.java Github

copy

Full Screen

...175 }176 public static void emptyTestDirData() {177 testDirectory.remove();178 isCustomTestDirName.set(Boolean.FALSE);179 stopThreadLogAppender();180 }181 public static synchronized File createTestDir() {182 return createTestDir(UUID.randomUUID().toString());183 }184 private static synchronized File createTestDir(String dirName) {185 File testDir;186 String directory = String.format("%s/%s", getBaseDir(), dirName);187 testDir = new File(directory);188 if (!testDir.exists()) {189 testDir.mkdirs();190 if (!testDir.exists()) {191 throw new RuntimeException("Test Folder(s) not created: " + testDir.getAbsolutePath());192 }193 }194 195 testDirectory.set(testDir);196 return testDir;197 }198 public static synchronized File getArtifactsFolder() {199 File dir = null;200 try {201 // artifacts directory should use canonical path otherwise auto download feature is broken in browsers 202 if (!Configuration.get(Parameter.CUSTOM_ARTIFACTS_FOLDER).isEmpty()) {203 dir = new File(Configuration.get(Parameter.CUSTOM_ARTIFACTS_FOLDER)).getCanonicalFile();204 } else {205 dir = new File(getTestDir().getCanonicalPath() + File.separator + ARTIFACTS_FOLDER);206 }207 if (!dir.exists()) {208 if (!dir.mkdir()) {209 throw new RuntimeException("Artifacts folder not created: " + dir.getAbsolutePath());210 } else {211 LOGGER.debug(("Artifacts folder created: " + dir.getAbsolutePath()));212 }213 } else {214 LOGGER.debug("Artifacts folder already exists: " + dir.getAbsolutePath());215 }216 217 if (!dir.isDirectory()) {218 throw new RuntimeException("Artifacts folder is not a folder: " + dir.getAbsolutePath());219 }220 } catch (IOException e) {221 throw new RuntimeException("Artifacts folder not created!");222 }223 return dir;224 }225 /**226 * Returns consolidated list of auto downloaded filenames from local artifacts folder or from remote Selenium session227 * 228 * @param driver WebDriver229 * @return list of file and directories names230 */231 public static List<String> listArtifacts(WebDriver driver) {232 List<String> artifactNames = Arrays.stream(Objects.requireNonNull(getArtifactsFolder().listFiles()))233 .map(File::getName)234 .collect(Collectors.toList());235 String hostUrl = getUrl(driver, "");236 String username = getField(hostUrl, 1);237 String password = getField(hostUrl, 2);238 239 try {240 HttpURLConnection con = (HttpURLConnection) new URL(hostUrl).openConnection();241 con.setInstanceFollowRedirects(true); //explicitly define as true because default value doesn't work and return 301 status242 con.setRequestMethod("GET");243 if (!username.isEmpty() && !password.isEmpty()) {244 String usernameColonPassword = username + ":" + password;245 String basicAuthPayload = "Basic " + Base64.getEncoder().encodeToString(usernameColonPassword.getBytes());246 con.addRequestProperty("Authorization", basicAuthPayload);247 }248 int responseCode = con.getResponseCode();249 String responseBody = readStream(con.getInputStream());250 if (responseCode == HttpURLConnection.HTTP_NOT_FOUND &&251 responseBody.contains("\"error\":\"invalid session id\",\"message\":\"unknown session")) {252 throw new RuntimeException("Invalid session id. Something wrong with driver");253 }254 if (responseCode == HttpURLConnection.HTTP_OK) {255 String hrefAttributePattern = "href=([\"'])((?:(?!\\1)[^\\\\]|(?:\\\\\\\\)*\\\\[^\\\\])*)\\1";256 Pattern pattern = Pattern.compile(hrefAttributePattern);257 Matcher matcher = pattern.matcher(responseBody);258 while (matcher.find()) {259 if (!artifactNames.contains(matcher.group(2))) {260 artifactNames.add(matcher.group(2));261 }262 }263 }264 } catch (IOException e) {265 LOGGER.debug("Something went wrong when try to get artifacts from remote", e);266 } 267 return artifactNames;268 }269 270 /**271 * Get artifacts from auto download folder of local or remove driver session by pattern272 * 273 * @param driver WebDriver274 * @param pattern String - regex for artifacts 275 * @return list of artifact files276 */277 public static List<File> getArtifacts(WebDriver driver, String pattern) {278 List<String> filteredFilesNames = listArtifacts(driver)279 .stream()280 // ignore directories281 .filter(fileName -> !fileName.endsWith("/"))282 .filter(fileName -> fileName.matches(pattern))283 .collect(Collectors.toList());284 List<File> artifacts = new ArrayList<>();285 for (String fileName : filteredFilesNames) {286 artifacts287 .add(getArtifact(driver, fileName));288 }289 return artifacts;290 } 291 /**292 * Get artifact from auto download folder of local or remove driver session by name293 * 294 * @param driver WebDriver295 * @param name String - filename with extension296 * @return artifact File297 */298 public static File getArtifact(WebDriver driver, String name) {299 File file = new File(getArtifactsFolder() + File.separator + name);300 if (file.exists()) {301 return file;302 }303 304 String path = file.getAbsolutePath();305 LOGGER.debug("artifact file to download: " + path);306 String url = getUrl(driver, name);307 String username = getField(url, 1);308 String password = getField(url, 2);309 310 if (!username.isEmpty() && !password.isEmpty()) {311 Authenticator.setDefault(new CustomAuthenticator(username, password));312 } 313 if (checkArtifactUsingHttp(url, username, password)) {314 try {315 FileUtils.copyURLToFile(new URL(url), file);316 LOGGER.debug("Successfully downloaded artifact: {}", name);317 } catch (IOException e) {318 LOGGER.error("Artifact: " + url + " wasn't downloaded to " + path, e);319 }320 } else {321 Assert.fail("Unable to find artifact: " + name);322 }323 // publish as test artifact to Zebrunner Reporting324 Artifact.attachToTest(name, file); 325 return file;326 }327 /**328 * check if artifact exists using http329 * 330 * @param url String331 * @param username String332 * @param password String333 * @return boolean334 */335 private static boolean checkArtifactUsingHttp(String url, String username, String password) {336 try {337 HttpURLConnection.setFollowRedirects(false);338 // note : you may also need339 // HttpURLConnection.setInstanceFollowRedirects(false)340 HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection();341 con.setRequestMethod("HEAD");342 if (!username.isEmpty() && !password.isEmpty()) {343 String usernameColonPassword = username + ":" + password;344 String basicAuthPayload = "Basic " + Base64.getEncoder().encodeToString(usernameColonPassword.getBytes());345 con.addRequestProperty("Authorization", basicAuthPayload);346 }347 return (con.getResponseCode() == HttpURLConnection.HTTP_OK);348 } catch (Exception e) {349 LOGGER.debug("Artifact doesn't exist: " + url, e);350 return false;351 }352 }353 /**354 * get username or password from url355 * 356 * @param url String357 * @param position int358 * @return String359 */360 private static String getField(String url, int position) {361 Pattern pattern = Pattern.compile(".*:\\/\\/(.*):(.*)@");362 Matcher matcher = pattern.matcher(url);363 return matcher.find() ? matcher.group(position) : "";364 }365 366 /**367 * Generate file in artifacts location and register in Zebrunner Reporting368 * 369 * @param name String370 * @param source InputStream371 */ 372 public static void saveArtifact(String name, InputStream source) throws IOException {373 File artifact = new File(String.format("%s/%s", getArtifactsFolder(), name));374 artifact.createNewFile();375 FileUtils.writeByteArrayToFile(artifact, IOUtils.toByteArray(source));376 377 Artifact.attachToTest(name, IOUtils.toByteArray(source));378 }379 /**380 * Copy file into artifacts location and register in Zebrunner Reporting381 * @param source File382 */ 383 public static void saveArtifact(File source) throws IOException {384 File artifact = new File(String.format("%s/%s", getArtifactsFolder(), source.getName()));385 artifact.createNewFile();386 FileUtils.copyFile(source, artifact);387 388 Artifact.attachToTest(source.getName(), artifact);389 } 390 /**391 * generate url for artifact by name392 * 393 * @param driver WebDriver394 * @param name String395 * @return String396 */397 private static String getUrl(WebDriver driver, String name) {398 String seleniumHost = Configuration.getSeleniumUrl().replace("wd/hub", "download/");399 WebDriver drv = (driver instanceof EventFiringWebDriver) ? ((EventFiringWebDriver) driver).getWrappedDriver() : driver;400 String sessionId = ((RemoteWebDriver) drv).getSessionId().toString();401 String url = seleniumHost + sessionId + "/" + name;402 LOGGER.debug("url: " + url);403 return url;404 }405 private static void stopThreadLogAppender() {406 try {407 LoggerContext loggerContext = (LoggerContext) LogManager.getContext(true);408 ThreadLogAppender appender = loggerContext.getConfiguration().getAppender("ThreadLogAppender");;409 if (appender != null) {410 appender.stop();411 }412 } catch (Exception e) {413 LOGGER.error("Exception while closing thread log appender.", e);414 }415 }416 private static File renameTestDir(String test) {417 File testDir = testDirectory.get();418 initIsCustomTestDir();419 if (testDir != null && !isCustomTestDirName.get()) {420 File newTestDir = new File(String.format("%s/%s", getBaseDir(), test.replaceAll("[^a-zA-Z0-9.-]", "_")));421 if (!newTestDir.exists()) {422 boolean isRenamed = false;423 int retry = 5;424 while (!isRenamed && retry > 0) {425 // close ThreadLogAppender resources before renaming426 stopThreadLogAppender();427 isRenamed = testDir.renameTo(newTestDir);428 if (!isRenamed) {429 CommonUtils.pause(1);430 System.err.println("renaming failed to '" + newTestDir + "'");431 }432 retry--;433 }434 435 if (isRenamed) {436 testDirectory.set(newTestDir);437 System.out.println("Test directory renamed to '" + newTestDir + "'");438 }439 }440 } else {...

Full Screen

Full Screen

stopThreadLogAppender

Using AI Code Generation

copy

Full Screen

1import com.qaprosoft.carina.core.foundation.report.ReportContext2ReportContext.stopThreadLogAppender()3import com.qaprosoft.carina.core.foundation.report.ReportContext4ReportContext.stopThreadLogAppender()5import com.qaprosoft.carina.core.foundation.report.ReportContext6ReportContext.stopThreadLogAppender()7import com.qaprosoft.carina.core.foundation.report.ReportContext8ReportContext.stopThreadLogAppender()9import com.qaprosoft.carina.core.foundation.report.ReportContext10ReportContext.stopThreadLogAppender()11import com.qaprosoft.carina.core.foundation.report.ReportContext12ReportContext.stopThreadLogAppender()13import com.qaprosoft.carina.core.foundation.report.ReportContext14ReportContext.stopThreadLogAppender()15import com.qaprosoft.carina.core.foundation.report.ReportContext16ReportContext.stopThreadLogAppender()17import com.qaprosoft.carina.core.foundation.report.ReportContext18ReportContext.stopThreadLogAppender()19import com.qaprosoft.carina.core.foundation.report.ReportContext20ReportContext.stopThreadLogAppender()21import com.qaprosoft.carina.core.foundation.report.ReportContext22ReportContext.stopThreadLogAppender()23import com.q

Full Screen

Full Screen

stopThreadLogAppender

Using AI Code Generation

copy

Full Screen

1stopThreadLogAppender()2startThreadLogAppender()3flushThreadLogAppender()4getThreadLogAppender()5getThreadLogAppender()6log(message)7log(message, params)8log(message, cause)9log(message, params, cause)10log(message, params, cause, aClass)11log(message, params, cause, aClass, method)12log(message, params, cause, aClass, method, marker)13log(message, params, cause, aClass, method, marker, key, value)14log(message, params, cause, aClass, method,

Full Screen

Full Screen

stopThreadLogAppender

Using AI Code Generation

copy

Full Screen

1import com.qaprosoft.carina.core.foundation.report.ReportContext;2import com.qaprosoft.carina.core.foundation.utils.Configuration;3public class StopLoggingToFile {4 public static void main(String[] args) {5 String path = "C:\\Users\\User\\IdeaProjects\\carina-demo\\log.txt";6 String fileName = "log.txt";7 String folder = "C:\\Users\\User\\IdeaProjects\\carina-demo";8 String logName = "log";9 String extension = "txt";10 String logLevel = "debug";11 String logLayout = "pattern";12 String logPattern = "%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n";13 String logEncoding = "UTF-8";14 String logFileSize = "100MB";15 String logFileCount = "5";16 String logPatternConsole = "%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n";17 String logFileSizeConsole = "100MB";18 String logFileCountConsole = "5";19 String logPatternFile = "%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n";20 String logFileSizeFile = "100MB";21 String logFileCountFile = "5";22 String logPatternHtml = "%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n";

Full Screen

Full Screen

stopThreadLogAppender

Using AI Code Generation

copy

Full Screen

1import java.io.File;2import java.io.FileNotFoundException;3import java.io.IOException;4import java.io.PrintWriter;5import java.util.ArrayList;6import java.util.List;7import java.util.Scanner;8import org.apache.log4j.Logger;9import org.testng.annotations.Test;10import com.qaprosoft.carina.core.foundation.report.ReportContext;11public class Log4jAppenderTest {12 private static final Logger LOGGER = Logger.getLogger(Log4jAppenderTest.class);13 public void testLog4jAppender() throws FileNotFoundException {14 LOGGER.info("This is a test message");15 List<String> lines = new ArrayList<String>();16 Scanner scanner = new Scanner(new File("target/log4j.log"));17 while (scanner.hasNextLine()) {18 lines.add(scanner.nextLine());19 }20 scanner.close();21 System.out.println(lines);22 PrintWriter writer = new PrintWriter("target/log4j.log");23 writer.print("");24 writer.close();25 }26 public void testStopThreadLogAppender() throws IOException {27 LOGGER.info("This is a test message");28 ReportContext.stopThreadLogAppender();29 List<String> lines = new ArrayList<String>();30 Scanner scanner = new Scanner(new File("target/log4j.log"));31 while (scanner.hasNextLine()) {32 lines.add(scanner.nextLine());33 }34 scanner.close();35 System.out.println(lines);36 PrintWriter writer = new PrintWriter("target/log4j.log");37 writer.print("");38 writer.close();39 }40}

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