[Jython-checkins] jython: Make logging lazy throughout the import mechanism.

jeff.allen jython-checkins at python.org
Sat Aug 10 15:19:41 EDT 2019


https://hg.python.org/jython/rev/0b15dd7f2572
changeset:   8274:0b15dd7f2572
user:        Jeff Allen <ja.py at farowl.co.uk>
date:        Sat Aug 10 18:13:48 2019 +0100
summary:
  Make logging lazy throughout the import mechanism.

We use logging's ability to accept a template and parameters. As we are
rewritimg the messages, we also make them somewhat more like CPython.

files:
  src/org/python/core/ClasspathPyImporter.java                       |   6 +-
  src/org/python/core/JavaImporter.java                              |  12 +-
  src/org/python/core/PrePy.java                                     |   1 +
  src/org/python/core/Py.java                                        |  37 +++----
  src/org/python/core/SyspathArchive.java                            |   7 +-
  src/org/python/core/imp.java                                       |  46 ++++----
  src/org/python/core/packagecache/CachedJarsPackageManager.java     |  51 +++++----
  src/org/python/core/packagecache/PathPackageManager.java           |  17 +-
  src/org/python/core/packagecache/SysPackageManager.java            |  31 +++--
  src/org/python/core/util/importer.java                             |   9 +-
  src/org/python/modules/_imp.java                                   |  23 ++-
  src/org/python/modules/zipimport/zipimporter.java                  |   6 +-
  tests/java/org/python/core/packagecache/CachedJarsOver64kTest.java |   2 +-
  13 files changed, 139 insertions(+), 109 deletions(-)


diff --git a/src/org/python/core/ClasspathPyImporter.java b/src/org/python/core/ClasspathPyImporter.java
--- a/src/org/python/core/ClasspathPyImporter.java
+++ b/src/org/python/core/ClasspathPyImporter.java
@@ -5,6 +5,7 @@
 import java.io.IOException;
 import java.io.InputStream;
 import java.util.Map;
+import java.util.logging.Level;
 
 import org.python.core.util.FileUtil;
 import org.python.core.util.StringUtil;
@@ -213,9 +214,10 @@
         return null;
     }
 
-    private InputStream tryClassLoader(String fullFilename, ClassLoader loader, String name) {
+    private InputStream tryClassLoader(String fullFilename, ClassLoader loader, String place) {
         if (loader != null) {
-            Py.writeDebug("import", "trying " + fullFilename + " in " + name + " class loader");
+            logger.log(Level.FINE, "# trying {0} in {1} class loader",
+                    new Object[] {fullFilename, place});
             return loader.getResourceAsStream(fullFilename);
         }
         return null;
diff --git a/src/org/python/core/JavaImporter.java b/src/org/python/core/JavaImporter.java
--- a/src/org/python/core/JavaImporter.java
+++ b/src/org/python/core/JavaImporter.java
@@ -1,5 +1,8 @@
 package org.python.core;
 
+import java.util.logging.Logger;
+import java.util.logging.Level;
+
 /**
  * Load Java classes.
  */
@@ -7,7 +10,9 @@
 public class JavaImporter extends PyObject {
 
     public static final String JAVA_IMPORT_PATH_ENTRY = "__classpath__";
+    private static Logger log = Logger.getLogger("org.python.import");
 
+    @Override
     public PyObject __call__(PyObject args[], String keywords[]) {
         if(args[0].toString().endsWith(JAVA_IMPORT_PATH_ENTRY)){
             return this;
@@ -35,11 +40,11 @@
      *         otherwise
      */
     public PyObject find_module(String name, PyObject path) {
-        Py.writeDebug("import", "trying " + name
-                + " in packagemanager for path " + path);
+        log.log(Level.FINE, "# trying {0} in package manager for path {1}",
+                new Object[] {name, path});
         PyObject ret = PySystemState.packageManager.lookupName(name.intern());
         if (ret != null) {
-            Py.writeComment("import", "'" + name + "' as java package");
+            log.log(Level.CONFIG, "import {0} # as java package", name);
             return this;
         }
         return Py.None;
@@ -54,6 +59,7 @@
      *
      * @return a string representation of the object.
      */
+    @Override
     public String toString() {
         return this.getType().toString();
     }
diff --git a/src/org/python/core/PrePy.java b/src/org/python/core/PrePy.java
--- a/src/org/python/core/PrePy.java
+++ b/src/org/python/core/PrePy.java
@@ -36,6 +36,7 @@
 
     /** Our name-spaced root logger is "org.python". */
     protected static final Logger logger = Logger.getLogger("org.python");
+    protected static final Logger importLogger = Logger.getLogger("org.python.import");
 
     /** {@link Options#verbose} level indicating an error that prevents correct results. */
     public static final int ERROR = -1;
diff --git a/src/org/python/core/Py.java b/src/org/python/core/Py.java
--- a/src/org/python/core/Py.java
+++ b/src/org/python/core/Py.java
@@ -4,7 +4,6 @@
 import java.io.ByteArrayOutputStream;
 import java.io.CharArrayWriter;
 import java.io.File;
-import java.io.FileDescriptor;
 import java.io.FileNotFoundException;
 import java.io.FileOutputStream;
 import java.io.IOException;
@@ -22,6 +21,7 @@
 import java.util.ArrayList;
 import java.util.Calendar;
 import java.util.List;
+import java.util.logging.Level;
 
 import org.python.antlr.base.mod;
 import org.python.core.adapter.ClassicPyObjectAdapter;
@@ -33,8 +33,6 @@
 import jline.console.UserInterruptException;
 import jnr.constants.Constant;
 import jnr.constants.platform.Errno;
-import jnr.posix.POSIX;
-import jnr.posix.POSIXFactory;
 import jnr.posix.util.Platform;
 
 public final class Py extends PrePy {
@@ -1074,19 +1072,14 @@
 
         ClassLoader classLoader = Py.getSystemState().getClassLoader();
         if (classLoader != null) {
-            if (reason != null) {
-                writeDebug("import", "trying " + name + " as " + reason + " in sys.classLoader");
-            }
+            findClassTrying(name, reason, classLoader, "sys.classLoader");
             return loadAndInitClass(name, classLoader);
         }
 
         if (!syspathJavaLoaderRestricted) {
             try {
                 classLoader = imp.getSyspathJavaLoader();
-                if (classLoader != null && reason != null) {
-                    writeDebug("import",
-                            "trying " + name + " as " + reason + " in SysPathJavaLoader");
-                }
+                findClassTrying(name, reason, classLoader, "SysPathJavaLoader");
             } catch (SecurityException e) {
                 syspathJavaLoaderRestricted = true;
             }
@@ -1094,10 +1087,7 @@
 
         if (syspathJavaLoaderRestricted) {
             classLoader = imp.getParentClassLoader();
-            if (classLoader != null && reason != null) {
-                writeDebug("import",
-                        "trying " + name + " as " + reason + " in Jython's parent class loader");
-            }
+            findClassTrying(name, reason, classLoader, "Jython's parent class loader");
         }
 
         if (classLoader != null) {
@@ -1115,12 +1105,17 @@
             }
         }
 
-        if (reason != null) {
-            writeDebug("import", "trying " + name + " as " + reason
-                    + " in context class loader, for backwards compatibility");
+        classLoader = Thread.currentThread().getContextClassLoader();
+        findClassTrying(name, reason, classLoader,
+                "context class loader, for backwards compatibility");
+        return loadAndInitClass(name, classLoader);
+    }
+
+    private static void findClassTrying(String name, String reason, ClassLoader cl, String place) {
+        if (cl != null && reason != null && importLogger.isLoggable(Level.FINE)) {
+            importLogger.log(Level.FINE, "# trying {0} as {1} in {2}",
+                    new Object[] {name, reason, place});
         }
-
-        return loadAndInitClass(name, Thread.currentThread().getContextClassLoader());
     }
 
     /**
@@ -1160,11 +1155,11 @@
     // An alias to express intent (since boolean flags aren't exactly obvious).
     // We *need* to initialize classes on findClass/findClassEx, so that import
     // statements can trigger static initializers
-    private static Class<?> loadAndInitClass(String name, ClassLoader loader) throws ClassNotFoundException {
+    private static Class<?> loadAndInitClass(String name, ClassLoader loader)
+            throws ClassNotFoundException {
         return Class.forName(name, true, loader);
     }
 
-
     public static void initProxy(PyProxy proxy, String module, String pyclass, Object[] args)
     {
         if (proxy._getPyInstance() != null) {
diff --git a/src/org/python/core/SyspathArchive.java b/src/org/python/core/SyspathArchive.java
--- a/src/org/python/core/SyspathArchive.java
+++ b/src/org/python/core/SyspathArchive.java
@@ -1,5 +1,6 @@
 package org.python.core;
 import java.io.*;
+import java.util.logging.Logger;
 import java.util.zip.*;
 
 @Untraversable
@@ -87,8 +88,9 @@
         int off = 0;
         while (len > 0) {
             int l = istream.read(buffer, off, buffer.length - off);
-            if (l < 0)
+            if (l < 0) {
                 return null;
+            }
             off += l;
             len -= l;
         }
@@ -97,12 +99,13 @@
     }
 
 /*
+    private static Logger logger = Logger.getLogger("org.python.import");
     protected void finalize() {
         System.out.println("closing zip file " + toString());
         try {
             zipFile.close();
         } catch (IOException e) {
-            Py.writeDebug("import", "closing zipEntry failed");
+            logger.log(Level.FINE, "closing zipEntry failed");
         }
     }
 */
diff --git a/src/org/python/core/imp.java b/src/org/python/core/imp.java
--- a/src/org/python/core/imp.java
+++ b/src/org/python/core/imp.java
@@ -13,6 +13,8 @@
 import java.io.InputStream;
 import java.util.Map;
 import java.util.concurrent.locks.ReentrantLock;
+import java.util.logging.Logger;
+import java.util.logging.Level;
 
 /**
  * Utility functions for "import" support.
@@ -24,7 +26,7 @@
  */
 public class imp {
 
-    private static final String IMPORT_LOG = "import";
+    private static Logger logger = Logger.getLogger("org.python.import");
 
     private static final String UNKNOWN_SOURCEFILE = "<unknown>";
 
@@ -304,8 +306,8 @@
         }
 
         // Execute the PyCode object (run the module body) to populate the module __dict__
-        Py.writeComment(IMPORT_LOG,
-                String.format("import %s # precompiled from %s", name, compiledName));
+        logger.log(Level.CONFIG, "import {0} # precompiled from {1}",
+                new Object[] {name, compiledName});
         return createFromCode(name, code, compiledName);
     }
 
@@ -482,23 +484,18 @@
             fop.write(compiledSource);
             fop.close();
             return compiledFilename;
-        } catch (IOException exc) {
-            // If we can't write the cache file, just log and continue
-            Py.writeDebug(IMPORT_LOG, "Unable to write to source cache file '" + compiledFilename
-                    + "' due to " + exc);
-            return null;
-        } catch (SecurityException exc) {
-            // If we can't write the cache file, just log and continue
-            Py.writeDebug(IMPORT_LOG, "Unable to write to source cache file '" + compiledFilename
-                    + "' due to " + exc);
+        } catch (IOException | SecurityException exc) {
+            // If we can't write the cache file, just logger and continue
+            logger.log(Level.FINE, "Unable to write to source cache file ''{0}'' due to {1}",
+                    new Object[] {compiledFilename, exc});
             return null;
         } finally {
             if (fop != null) {
                 try {
                     fop.close();
                 } catch (IOException e) {
-                    Py.writeDebug(IMPORT_LOG, "Unable to close source cache file '"
-                            + compiledFilename + "' due to " + e);
+                    logger.log(Level.FINE, "Unable to close source cache file ''{0}'' due to {1}",
+                            new Object[] {compiledFilename, e});
                 }
             }
         }
@@ -573,7 +570,7 @@
             outFilename = cacheCompiledSource(filename, outFilename, bytes);
         }
 
-        Py.writeComment(IMPORT_LOG, "'" + name + "' as " + filename);
+        logger.log(Level.CONFIG, "import {0} # from {1}", new Object[]{name, filename});
 
         PyCode code = BytecodeLoader.makeCode(name + "$py", bytes, filename);
         return createFromCode(name, code, filename);
@@ -616,7 +613,7 @@
         } else if (module.__findattr__("__file__") == null) {
             // Should probably never happen (but maybe with an odd custom builtins, or
             // Java Integration)
-            Py.writeDebug(IMPORT_LOG, String.format("Warning: %s __file__ is unknown", name));
+            logger.log(Level.WARNING, "{0} __file__ is unknown", name);
         }
 
         ReentrantLock importLock = Py.getSystemState().getImportLock();
@@ -778,19 +775,20 @@
      * @return
      */
     private static PyObject loadBuiltin(String name) {
+        final String MSG = "import {0} # builtin";
         if (name == "sys") {
-            Py.writeComment(IMPORT_LOG, "'" + name + "' as sys in builtin modules");
+            logger.log(Level.CONFIG, MSG, name);
             return Py.java2py(Py.getSystemState());
         }
         if (name == "__builtin__") {
-            Py.writeComment(IMPORT_LOG, "'" + name + "' as __builtin__ in builtin modules");
+            logger.log(Level.CONFIG, MSG, new Object[] {name, name});
             return new PyModule("__builtin__", Py.getSystemState().builtins);
         }
         String mod = PySystemState.getBuiltin(name);
         if (mod != null) {
-            Class<?> c = Py.findClassEx(mod, "builtin modules");
+            Class<?> c = Py.findClassEx(mod, "builtin module");
             if (c != null) {
-                Py.writeComment(IMPORT_LOG, "'" + name + "' as " + mod + " in builtin modules");
+                logger.log(Level.CONFIG, "import {0} # builtin {1}", new Object[] {name, mod});
                 try {
                     if (PyObject.class.isAssignableFrom(c)) { // xxx ok?
                         return PyType.fromClass(c);
@@ -917,7 +915,7 @@
 
                 if (haveCompiled) {
                     // We have the compiled file and will use that if it is not out of date
-                    Py.writeDebug(IMPORT_LOG, "trying precompiled " + compiledFile.getPath());
+                    logger.log(Level.FINE, "# trying precompiled {0}", compiledFile.getPath());
                     long classTime = compiledFile.lastModified();
                     if (classTime >= pyTime) {
                         // The compiled file does not appear out of date relative to the source.
@@ -931,14 +929,14 @@
                 }
 
                 // The compiled class is not present, is out of date, or using it failed somehow.
-                Py.writeDebug(IMPORT_LOG, "trying source " + sourceFile.getPath());
+                logger.log(Level.FINE, "# trying source {0}", sourceFile.getPath());
                 return createFromSource(modName, makeStream(sourceFile), displaySourceName,
                         compiledFile.getPath(), pyTime);
 
             } else if (haveCompiled) {
                 // There is no source, try loading compiled
-                Py.writeDebug(IMPORT_LOG,
-                        "trying precompiled with no source " + compiledFile.getPath());
+                logger.log(Level.FINE, "# trying precompiled with no source {0}",
+                        compiledFile.getPath());
                 return createFromPyClass(modName, makeStream(compiledFile), //
                         false, // throw ImportError here if this fails
                         displaySourceName, displayCompiledName, NO_MTIME, CodeImport.compiled_only);
diff --git a/src/org/python/core/packagecache/CachedJarsPackageManager.java b/src/org/python/core/packagecache/CachedJarsPackageManager.java
--- a/src/org/python/core/packagecache/CachedJarsPackageManager.java
+++ b/src/org/python/core/packagecache/CachedJarsPackageManager.java
@@ -32,6 +32,7 @@
 import java.util.List;
 import java.util.Map;
 import java.util.Map.Entry;
+import java.util.logging.Logger;
 import java.util.zip.ZipEntry;
 import java.util.zip.ZipInputStream;
 
@@ -42,33 +43,39 @@
  */
 public abstract class CachedJarsPackageManager extends PackageManager {
 
+    protected static Logger logger = Logger.getLogger("org.python.import");
+
     /**
      * Message log method - hook. This default implementation does nothing.
      *
-     * @param msg message text
+     * @param msg message template (see java.text.MessageFormat)
+     * @param params parameters to insert
      */
-    protected void message(String msg) {}
+    protected void message(String msg, Object... params) {}
 
     /**
      * Warning log method - hook. This default implementation does nothing.
      *
-     * @param warn warning text
+     * @param msg message template (see java.text.MessageFormat)
+     * @param params parameters to insert
      */
-    protected void warning(String warn) {}
+    protected void warning(String msg, Object... params) {}
 
     /**
      * Comment log method - hook. This default implementation does nothing.
      *
-     * @param msg message text
+     * @param msg message template (see java.text.MessageFormat)
+     * @param params parameters to insert
      */
-    protected void comment(String msg) {}
+    protected void comment(String msg, Object... params) {}
 
     /**
      * Debug log method - hook. This default implementation does nothing.
      *
-     * @param msg message text
+     * @param msg message template (see java.text.MessageFormat)
+     * @param params parameters to insert
      */
-    protected void debug(String msg) {}
+    protected void debug(String msg, Object... params) {}
 
     /**
      * Filter class/pkg by name helper method - hook. The default implementation is used by
@@ -338,7 +345,7 @@
 
                 if (writeCache && (entry == null || !(new File(entry.cachefile).exists()))) {
                     // We intend to use a cache but there is no valid existing file.
-                    comment("processing new jar, '" + jarcanon + "'");
+                    comment("processing new jar ''{0}''", jarcanon);
 
                     // Create a base-name for the cache file
                     String jarname;
@@ -377,7 +384,7 @@
                     // Update the index entry for the cache file we shall eventually write.
                     this.indexModified = true;
                     if (entry.mtime != 0) {
-                        comment("processing modified jar, '" + jarcanon + "'");
+                        comment("processing modified jar ''{0}''", jarcanon);
                     }
                     entry.mtime = mtime;
                 }
@@ -415,8 +422,7 @@
 
         } catch (IOException ioe) {
             // Skip the bad JAR with a message
-            warning("skipping bad jar, '"
-                    + (jarfile != null ? jarfile.toString() : jarurl.toString()) + "'");
+            warning("skipping bad jar ''{0}''", (jarfile != null ? jarfile : jarurl).toString());
         }
     }
 
@@ -450,7 +456,7 @@
         String cachefile = entry.cachefile;
         long mtime = entry.mtime;
 
-        debug("reading cache, '" + jarcanon + "'");
+        debug("reading cache of ''{0}''", jarcanon);
 
         DataInputStream istream = null;
         try {
@@ -458,8 +464,8 @@
             String old_jarcanon = istream.readUTF();
             long old_mtime = istream.readLong();
             if ((!old_jarcanon.equals(jarcanon)) || (old_mtime != mtime)) {
-                comment("invalid cache file: " + cachefile + ", " + jarcanon + ":" + old_jarcanon
-                        + ", " + mtime + ":" + old_mtime);
+                comment("invalid cache file: {0} for new:{1}({3}), old:{2}({4})", cachefile, jarcanon,
+                        old_jarcanon, mtime, old_mtime);
                 deleteCacheFile(cachefile);
                 return null;
             }
@@ -512,7 +518,7 @@
             ostream = outCreateCacheFile(entry, brandNew);
             ostream.writeUTF(jarcanon);
             ostream.writeLong(entry.mtime);
-            comment("rewriting cachefile for '" + jarcanon + "'");
+            comment("rewriting cache for ''{0}''", jarcanon);
 
             for (Entry<String, String> kv : zipPackages.entrySet()) {
                 String classes = kv.getValue();
@@ -524,7 +530,7 @@
                 }
             }
         } catch (IOException ioe) {
-            warning("can't write cache file for '" + jarcanon + "'");
+            warning("failed to write cache for ''{0}'' ({1})", jarcanon, ioe.getMessage());
         } finally {
             if (ostream != null) {
                 try {
@@ -539,11 +545,11 @@
     /** Scan a Java module, creating package objects. */
     protected void addModuleToPackages(Path modulePath) {
         try {
-            comment("reading packages from " + modulePath);
+            comment("reading packages from ''{0}''", modulePath);
             Map<String, String> packages = getModularPackages(modulePath);
             addPackages(packages, modulePath.toUri().toString());
         } catch (IOException ioe) {
-            warning("skipping bad module, '" + modulePath + "'" + ioe);
+            warning("skipping bad module ''{0}'' ({1})", modulePath, ioe.getMessage());
         }
     }
 
@@ -708,7 +714,7 @@
                 ostream.writeLong(xentry.mtime);
             }
         } catch (IOException ioe) {
-            warning("can't write index file");
+            warning("failed to write index file ({0})", ioe.getMessage());
         } finally {
             if (ostream != null) {
                 try {
@@ -841,12 +847,11 @@
 
         try {
             if (!aCachedir1.isDirectory() && aCachedir1.mkdirs() == false) {
-                warning("can't create package cache dir, '" + aCachedir1 + "'");
+                warning("failed to create cache dir ''{0}''", aCachedir1);
                 return false;
             }
         } catch (AccessControlException ace) {
-            warning("The java security manager isn't allowing access to the package cache dir, '"
-                    + aCachedir1 + "'");
+            warning("Not permitted to access cache ''{0}'' ({1})", aCachedir1, ace.getMessage());
             return false;
         }
 
diff --git a/src/org/python/core/packagecache/PathPackageManager.java b/src/org/python/core/packagecache/PathPackageManager.java
--- a/src/org/python/core/packagecache/PathPackageManager.java
+++ b/src/org/python/core/packagecache/PathPackageManager.java
@@ -3,6 +3,13 @@
 
 package org.python.core.packagecache;
 
+import java.io.BufferedInputStream;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FilenameFilter;
+import java.io.IOException;
+import java.util.logging.Level;
+
 import org.python.core.Py;
 import org.python.core.PyJavaPackage;
 import org.python.core.PyList;
@@ -11,12 +18,6 @@
 import org.python.core.imp;
 import org.python.core.util.RelativeFile;
 
-import java.io.BufferedInputStream;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FilenameFilter;
-import java.io.IOException;
-
 /**
  * Path package manager. Gathering classes info dynamically from a set of directories in path
  * {@link #searchPath}, and statically from a set of jars, like {@link CachedJarsPackageManager}.
@@ -56,7 +57,7 @@
                     f.listFiles(m);
                     boolean exists = m.packageExists();
                     if (exists) {
-                        Py.writeComment("import", "java package as '" + f.getAbsolutePath() + "'");
+                        logger.log(Level.CONFIG, "# trying {0}", f.getAbsolutePath());
                     }
                     return exists;
                 }
@@ -186,7 +187,7 @@
                 this.searchPath.append(Py.newStringOrUnicode(dir.getCanonicalPath()));
             }
         } catch (IOException e) {
-            warning("skipping bad directory, '" + dir + "'");
+            warning("# skipping bad directory {0} ({1})", dir, e.getMessage());
         }
     }
 
diff --git a/src/org/python/core/packagecache/SysPackageManager.java b/src/org/python/core/packagecache/SysPackageManager.java
--- a/src/org/python/core/packagecache/SysPackageManager.java
+++ b/src/org/python/core/packagecache/SysPackageManager.java
@@ -24,30 +24,34 @@
 import java.util.Properties;
 import java.util.Set;
 import java.util.StringTokenizer;
+import java.util.logging.Level;
+import java.util.logging.Logger;
 
 /**
  * System package manager. Used by org.python.core.PySystemState.
  */
 public class SysPackageManager extends PathPackageManager {
 
+    private static Logger pkglog = Logger.getLogger("org.python.package");
+
     @Override
-    protected void message(String msg) {
-        Py.writeMessage("*sys-package-mgr*", msg);
+    protected void message(String msg, Object... params) {
+        pkglog.log(Level.INFO, msg, params);
     }
 
     @Override
-    protected void warning(String warn) {
-        Py.writeWarning("*sys-package-mgr*", warn);
+    protected void warning(String msg, Object... params) {
+        pkglog.log(Level.WARNING, msg, params);
     }
 
     @Override
-    protected void comment(String msg) {
-        Py.writeComment("*sys-package-mgr*", msg);
+    protected void comment(String msg, Object... params) {
+        pkglog.log(Level.CONFIG, msg, params);
     }
 
     @Override
-    protected void debug(String msg) {
-        Py.writeDebug("*sys-package-mgr*", msg);
+    protected void debug(String msg, Object... params) {
+        pkglog.log(Level.FINE, msg, params);
     }
 
     public SysPackageManager(File cachedir, Properties registry) {
@@ -142,7 +146,7 @@
             Files.walkFileTree(moduleDir, visitor);
 
         } catch (IOException e) {
-            warning("error enumerating Java modules in " + moduleDir + ": " + e.getMessage());
+            warning("error enumerating Java modules in {0}: {1}", moduleDir, e.getMessage());
         }
     }
 
@@ -185,7 +189,7 @@
 
         Set<String> directories =
                 split(registry.getProperty(
-                            RegistryKey.PYTHON_PACKAGES_DIRECTORIES, 
+                            RegistryKey.PYTHON_PACKAGES_DIRECTORIES,
                             defaultDirectories));
         for (String name : directories) {
             // Each property defines a path string containing directories
@@ -206,16 +210,17 @@
     @Override
     public void notifyPackageImport(String pkg, String name) {
         if (pkg != null && pkg.length() > 0) {
-            name = pkg + '.' + name;
+            comment("import {0} # as java package {1}.{0}", name);
+        } else {
+            comment("import {0} # as java package", name);
         }
-        Py.writeComment("import", "'" + name + "' as java package");
     }
 
     @Override
     public Class findClass(String pkg, String name) {
         Class c = super.findClass(pkg, name);
         if (c != null) {
-            Py.writeComment("import", "'" + name + "' as java class");
+            comment("import {0} # as java class", name);
         }
         return c;
     }
diff --git a/src/org/python/core/util/importer.java b/src/org/python/core/util/importer.java
--- a/src/org/python/core/util/importer.java
+++ b/src/org/python/core/util/importer.java
@@ -4,6 +4,8 @@
 import java.io.IOException;
 import java.io.InputStream;
 import java.util.EnumSet;
+import java.util.logging.Logger;
+import java.util.logging.Level;
 
 import org.python.core.BytecodeLoader;
 import org.python.core.Py;
@@ -20,6 +22,8 @@
  */
 public abstract class importer<T> extends PyObject {
 
+    protected static Logger logger = Logger.getLogger("org.python.import");
+
     static enum EntryType {
         IS_SOURCE, IS_BYTECODE, IS_PACKAGE
     };
@@ -114,7 +118,8 @@
             mod.__dict__.__setitem__("__path__", pkgpath);
         }
         imp.createFromCode(fullname, moduleCodeData.code, moduleCodeData.path);
-        Py.writeDebug("import", "import " + fullname + " # loaded from " + moduleCodeData.path);
+        logger.log(Level.FINE, "import {0} # loaded from {1}",
+                new Object[] {fullname, moduleCodeData.path});
         return mod;
     }
 
@@ -199,7 +204,7 @@
             String searchPath = path + suffix;
             String fullSearchPath = fullPath + suffix;
 
-            Py.writeDebug("import", "# trying " + searchPath);
+            logger.log(Level.FINE, "# trying {0}", searchPath);
             T tocEntry = makeEntry(searchPath);
             if (tocEntry == null) {
                 continue;
diff --git a/src/org/python/modules/_imp.java b/src/org/python/modules/_imp.java
--- a/src/org/python/modules/_imp.java
+++ b/src/org/python/modules/_imp.java
@@ -1,8 +1,13 @@
 
 package org.python.modules;
 
-import org.python.core.__builtin__;
-import org.python.core.imp;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
 import org.python.core.Py;
 import org.python.core.PyFile;
 import org.python.core.PyList;
@@ -11,10 +16,8 @@
 import org.python.core.PyString;
 import org.python.core.PySystemState;
 import org.python.core.PyTuple;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.IOException;
-import java.io.InputStream;
+import org.python.core.__builtin__;
+import org.python.core.imp;
 
 /*
  * A bogus implementation of the CPython builtin module "imp".
@@ -37,6 +40,8 @@
     public static final int PY_FROZEN = 7;
     public static final int IMP_HOOK = 9;
 
+    private static Logger logger = Logger.getLogger("org.python.import");
+
     private static class ModuleInfo {
         PyObject file;
         String filename;
@@ -95,7 +100,7 @@
                 return new ModuleInfo(Py.None, new File(displayDirName, name).getPath(),
                                       "", "", PKG_DIRECTORY);
             } else {
-                Py.writeDebug("import", "trying source " + dir.getPath());
+                logger.log(Level.FINE, "# trying directory {0}", dir.getPath());
                 sourceName = name + ".py";
                 compiledName = imp.makeCompiledFilename(sourceName);
                 sourceFile = new File(directoryName, sourceName);
@@ -105,7 +110,7 @@
 
         if (sourceFile.isFile() && caseok(sourceFile, sourceName)) {
             if (!preferSource && compiledFile.isFile() && caseok(compiledFile, compiledName)) {
-                Py.writeDebug("import", "trying precompiled " + compiledFile.getPath());
+                logger.log(Level.FINE, "# trying precompiled {0}", compiledFile.getPath());
                 long pyTime = sourceFile.lastModified();
                 long classTime = compiledFile.lastModified();
                 if (classTime >= pyTime) {
@@ -120,7 +125,7 @@
         }
 
         // If no source, try loading precompiled
-        Py.writeDebug("import", "trying " + compiledFile.getPath());
+        logger.log(Level.FINE, "# trying precompiled {0}", compiledFile.getPath());
         if (compiledFile.isFile() && caseok(compiledFile, compiledName)) {
             return new ModuleInfo(newFile(compiledFile),
                     new File(displayDirName, compiledName).getPath(),
diff --git a/src/org/python/modules/zipimport/zipimporter.java b/src/org/python/modules/zipimport/zipimporter.java
--- a/src/org/python/modules/zipimport/zipimporter.java
+++ b/src/org/python/modules/zipimport/zipimporter.java
@@ -6,6 +6,8 @@
 import java.io.InputStream;
 import java.util.Date;
 import java.util.Enumeration;
+import java.util.logging.Level;
+import java.util.logging.Logger;
 import java.util.zip.ZipEntry;
 import java.util.zip.ZipFile;
 
@@ -49,6 +51,8 @@
         "a zipfile. ZipImportError is raised if 'archivepath' doesn't point to\n" +
         "a valid Zip archive.");
 
+    private static Logger log = Logger.getLogger("org.python.import");
+
     /** Path to the Zip archive */
     public String archive;
 
@@ -315,7 +319,7 @@
         try {
             return new ZipBundle(zipArchive, zipArchive.getInputStream(dataEntry));
         } catch (IOException ioe) {
-            Py.writeDebug("import", "zipimporter.getDataStream exception: " + ioe.toString());
+            log.log(Level.FINE, "zipimporter.getDataStream exception: {0}", ioe.toString());
             throw zipimport.ZipImportError("zipimport: can not open file: " + archive);
         }
     }
diff --git a/tests/java/org/python/core/packagecache/CachedJarsOver64kTest.java b/tests/java/org/python/core/packagecache/CachedJarsOver64kTest.java
--- a/tests/java/org/python/core/packagecache/CachedJarsOver64kTest.java
+++ b/tests/java/org/python/core/packagecache/CachedJarsOver64kTest.java
@@ -41,7 +41,7 @@
         }
 
         @Override
-        protected void warning(String msg){
+        protected void warning(String msg, Object... params) {
             failed = true;
         }
 

-- 
Repository URL: https://hg.python.org/jython


More information about the Jython-checkins mailing list