1   /*
2    * Logback: the reliable, generic, fast and flexible logging framework.
3    * Copyright (C) 1999-2026, QOS.ch. All rights reserved.
4    *
5    * This program and the accompanying materials are dual-licensed under
6    * either the terms of the Eclipse Public License v2.0 as published by
7    * the Eclipse Foundation
8    *
9    *   or (per the licensee's choosing)
10   *
11   * under the terms of the GNU Lesser General Public License version 2.1
12   * as published by the Free Software Foundation.
13   */
14  package ch.qos.logback.core.util;
15  
16  import java.util.List;
17  import java.util.Map;
18  import java.util.Map.Entry;
19  import java.util.Properties;
20  
21  import ch.qos.logback.core.Context;
22  import ch.qos.logback.core.CoreConstants;
23  import ch.qos.logback.core.hook.ShutdownHook;
24  import ch.qos.logback.core.rolling.helper.FileNamePattern;
25  import ch.qos.logback.core.spi.ContextAwareBase;
26  
27  public class ContextUtil extends ContextAwareBase {
28  
29      static final String GROOVY_RUNTIME_PACKAGE = "org.codehaus.groovy.runtime";
30      // static final String SYSTEM_LOGGER_FQCN = "java.lang.System$Logger";
31  
32      public ContextUtil(Context context) {
33          setContext(context);
34      }
35  
36      public void addProperties(Properties props) {
37          if (props == null) {
38              return;
39          }
40  
41          for (Entry<Object, Object> e : props.entrySet()) {
42              String key = (String) e.getKey();
43              context.putProperty(key, (String) e.getValue());
44          }
45  
46      }
47  
48      public void addGroovyPackages(List<String> frameworkPackages) {
49          addFrameworkPackage(frameworkPackages, GROOVY_RUNTIME_PACKAGE);
50      }
51  
52      public void addFrameworkPackage(List<String> frameworkPackages, String packageName) {
53          if (!frameworkPackages.contains(packageName)) {
54              frameworkPackages.add(packageName);
55          }
56      }
57  
58      /**
59       * Add a shutdown hook thread with the JVM runtime.
60       *
61       * If a previous shutdown hook thread was registered, it is replaced.
62       * @param hook
63       * @since 1.5.7
64       */
65      public void addOrReplaceShutdownHook(ShutdownHook hook) {
66          Runtime runtime = Runtime.getRuntime();
67  
68          Thread oldShutdownHookThread = (Thread) context.getObject(CoreConstants.SHUTDOWN_HOOK_THREAD);
69          if(oldShutdownHookThread != null) {
70              addInfo("Removing old shutdown hook from JVM runtime");
71              runtime.removeShutdownHook(oldShutdownHookThread);
72          }
73  
74          Thread hookThread = new Thread(hook, "Logback shutdown hook [" + context.getName() + "]");
75          addInfo("Registering shutdown hook with JVM runtime.");
76          context.putObject(CoreConstants.SHUTDOWN_HOOK_THREAD, hookThread);
77          runtime.addShutdownHook(hookThread);
78  
79      }
80  
81  }