Struts2, JPA (hibernate backed), Spring ... Как Struts2, так и Spring работают через log4j, но не hibernate - PullRequest
5 голосов
/ 26 июля 2011

Редактировать 3 : Это работает! Короче говоря: в папке lib Glassfish были: slf4j-api-1.5.8.jar и jlf4j-jdk14-1.5.8.jar! В любом случае я переместил их в «старую» папку, созданную в lib, а затем скопировал в папку следующее:

SLF4J-апи-1.6.1.jar
SLF4J-log4j12-1.6.1.jar JCL-над-SLF4J-1.6.1.jar log4j-1.2.16.jar (только то, что у меня было в моем пути к классам, но теперь к серверу приложений, и все работает как положено)

Я мог бы также поместить файл log4j.xml в glassfish, но я просто оставлю его вместе с моим приложением, чтобы иметь возможность ведения журнала для конкретного приложения.

Я дам ответ, переработаю вопрос, чтобы он был более полезным (слишком много информации, которая сейчас бесполезна).

Обновление : Я собирался ответить сам, но долго ждал. Приму ответ Стивенса, так как он был самым полезным при выяснении этого.

То, что следует историческому ...

<Ч />

Редактировать 2: Я не знаю почему, но это может иметь какое-то отношение к развертыванию на Glassfish v3. Glassfish использует Java Utility Logging, вот картинка http://blog.saddey.net/2010/03/27/how-to-deploy-a-grails-application-to-glassfish/ и описание того, что некоторые Grails люди делают для того, чтобы запустить регистрацию (не то, что я использую grails), может быть, использование jul имеет больше смысла, как предлагает эта диаграмма?

Я также получаю эти ошибки, если я заново разверну, не удаляя приложение:

SEVERE: log4j:ERROR log4j called after unloading, see http://logging.apache.org/log4j/1.2/faq.html#unload.
SEVERE: java.lang.IllegalStateException: Class invariant violation

Редактировать , ну я все еще застрял:

Ведение журнала работает для Spring и Struts2, но я не могу заставить hibernate распечатать SQL (или что-нибудь еще), используя log4j, и это важно, потому что, хотя я могу получить hibernate для печати SQL, используя <property name="hibernate.show_sql" value="true"/> в постоянном режиме. xml единственный способ показать параметры SQL - это ведение журнала, что сейчас очень важно для меня.

Для большей ясности, при запуске приложения есть некоторые информационные сообщения, связанные с гибернацией, но пока я выполняю запросы к БД, ничего не отображается.

Так как я схожу с ума, я перечислю свой pom, log4j.xml, applicationContext.xml, и, если у меня будет время, я предоставлю ссылки на многие сайты, которые я посетил (включая SO Q & A) .

pom.xml

Очевидный вопрос: какие банки для регистрации находятся на месте, и ответ: jcl-over-slf4j-1.6.1.jar, slf4j-log4j12-1.6.1.jar, log4j-1.2.16.jar и slf4j-api-1.6.1 (я также исключил использование общего журнала) ... также пытался версия 1.5.8 для jcl-over-slf4j, slf4j-api.

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.test</groupId>
    <artifactId>PartGroupMaster</artifactId>
    <version>2011.04.12</version>
    <packaging>war</packaging>

    <name>PartGroupMaster Web App</name>

    <properties>
        <endorsed.dir>${project.build.directory}/endorsed</endorsed.dir>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <netbeans.hint.deploy.server>gfv3ee6</netbeans.hint.deploy.server>
    </properties>

    <repositories>
        <repository>
            <id>JBoss Repo</id>
            <url>http://repository.jboss.com/maven2</url>
            <name>JBoss Repo</name>
        </repository>
        <repository>
            <id>ibiblio mirror</id>
            <url>http://mirrors.ibiblio.org/pub/mirrors/maven2/</url>
        </repository>
        <repository>
            <id>jboss-public-repository-group</id>
            <name>JBoss Public Maven Repository Group</name>
            <url>https://repository.jboss.org/nexus/content/groups/public/</url>
            <layout>default</layout>
            <releases>
                <enabled>true</enabled>
                <updatePolicy>never</updatePolicy>
            </releases>
            <snapshots>
                <enabled>true</enabled>
                <updatePolicy>never</updatePolicy>
            </snapshots>
        </repository>
        <repository>
            <url>http://ftp.ing.umu.se/mirror/eclipse/rt/eclipselink/maven.repo</url>
            <id>eclipselink</id>
            <layout>default</layout>
            <name>Repository for library Library[eclipselink]</name>
        </repository>
    </repositories>

    <dependencies>
        <dependency>
            <groupId>org.apache.struts</groupId>
            <artifactId>struts2-core</artifactId>
            <version>2.2.3</version>
        </dependency>
        <dependency>
            <groupId>org.apache.struts</groupId>
            <artifactId>struts2-convention-plugin</artifactId>
            <version>2.2.3</version>
        </dependency>
        <dependency>
            <groupId>org.apache.struts</groupId>
            <artifactId>struts2-spring-plugin</artifactId>
            <version>2.2.3</version>
            <exclusions>
                <exclusion>
                    <artifactId>spring-beans</artifactId>
                    <groupId>org.springframework</groupId>
                </exclusion>
                <exclusion>
                    <artifactId>spring-context</artifactId>
                    <groupId>org.springframework</groupId>
                </exclusion>
                <exclusion>
                    <artifactId>spring-core</artifactId>
                    <groupId>org.springframework</groupId>
                </exclusion>
                <exclusion>
                    <artifactId>spring-web</artifactId>
                    <groupId>org.springframework</groupId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>3.0.5.RELEASE</version>
            <exclusions>
                <exclusion>
                    <artifactId>commons-logging</artifactId>
                    <groupId>commons-logging</groupId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>3.0.5.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>3.0.5.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.15</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>3.6.6.Final</version>
        </dependency>
        <dependency>
            <groupId>org.apache.struts</groupId>
            <artifactId>struts2-config-browser-plugin</artifactId>
            <version>2.2.3</version>
        </dependency>
        <dependency>
            <groupId>org.eclipse.persistence</groupId>
            <artifactId>javax.persistence</artifactId>
            <version>2.0.3</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.struts</groupId>
            <artifactId>struts2-json-plugin</artifactId>
            <version>2.2.3</version>
        </dependency>
        <dependency>
            <groupId>commons-beanutils</groupId>
            <artifactId>commons-beanutils</artifactId>
            <version>1.8.0</version>
            <exclusions>
                <exclusion>
                    <artifactId>commons-logging</artifactId>
                    <groupId>commons-logging</groupId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.6.1</version>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.16</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>jcl-over-slf4j</artifactId>
            <version>1.6.1</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
            <version>4.2.0.Final</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-jpamodelgen</artifactId>
            <version>1.1.1.Final</version>
        </dependency>
            <dependency>
                    <groupId>org.slf4j</groupId>
                    <artifactId>slf4j-api</artifactId>
                    <version>1.6.1</version>
            </dependency>
            <dependency>
            <groupId>javax</groupId>
            <artifactId>javaee-web-api</artifactId>
            <version>6.0</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.8.1</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.3.2</version>
                <configuration>
                    <source>1.6</source>
                    <target>1.6</target>
                    <compilerArguments>
                        <endorseddirs>${endorsed.dir}</endorseddirs>
                    </compilerArguments>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>2.1</version>
                <configuration>
                    <failOnMissingWebXml>false</failOnMissingWebXml>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-dependency-plugin</artifactId>
                <version>2.1</version>
                <executions>
                    <execution>
                        <phase>validate</phase>
                        <goals>
                            <goal>copy</goal>
                        </goals>
                        <configuration>
                            <outputDirectory>${endorsed.dir}</outputDirectory>
                            <silent>true</silent>
                            <artifactItems>
                                <artifactItem>
                                    <groupId>javax</groupId>
                                    <artifactId>javaee-endorsed-api</artifactId>
                                    <version>6.0</version>
                                    <type>jar</type>
                                </artifactItem>
                            </artifactItems>
                        </configuration>
                    </execution>
                </executions>
            </plugin>

            <plugin>
                <artifactId>maven-antrun-plugin</artifactId>
                <executions>
                    <execution>
                        <phase>process-classes</phase>
                        <goals>
                            <goal>run</goal>
                        </goals>
                    </execution>
                </executions>
                <configuration>
                    <tasks>
                        <taskdef name="instrument" classname="org.hibernate.tool.instrument.javassist.InstrumentTask">
                            <classpath>
                                <path refid="maven.runtime.classpath" />
                                <path refid="maven.plugin.classpath" />
                            </classpath>
                        </taskdef>
                        <instrument verbose="false">
                            <fileset dir="${project.build.outputDirectory}">
                                <include name="**/mz/db/**/*.class" />
                            </fileset>
                        </instrument>
                    </tasks>
                </configuration>
            </plugin>
        </plugins>
        <finalName>PartGroupMaster</finalName>
    </build>
</project>

log4j.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration PUBLIC "-//log4j/log4j Configuration//EN" "log4j.dtd">

<log4j:configuration debug="true" xmlns:log4j="http://jakarta.apache.org/log4j/">
    <appender name="STDOUT" class="org.apache.log4j.ConsoleAppender">
        <param name="Target" value="System.out"/>
        <layout class="org.apache.log4j.PatternLayout"> 
            <param name="ConversionPattern" value="%d{ABSOLUTE} %5p %c{1}:%L - %m%n"/> 
        </layout> 
    </appender>

    <!-- specify the logging level for loggers from other libraries -->
    <logger name="com.opensymphony">
        <level value="ERROR" />
        <appender-ref ref="STDOUT" /> 
    </logger>

    <logger name="org.apache.struts2">
        <level value="ERROR" />
        <appender-ref ref="STDOUT" /> 
    </logger>

    <logger name="org.hibernate">
        <level value="TRACE" />
        <appender-ref ref="STDOUT" /> 
    </logger>

  <!-- log SQL statements (same as show_sql=true) -->
    <logger name="org.hibernate.hql">
        <level value="TRACE"/>
        <appender-ref ref="STDOUT" /> 
    </logger>

    <logger name="org.hibernate.SQL">
        <level value="TRACE"/>
        <appender-ref ref="STDOUT" /> 
    </logger>

    <logger name="org.hibernate.type">
        <level value="TRACE" />
        <appender-ref ref="STDOUT" /> 
    </logger>

    <logger name="org.springframework">
        <level value="WARN" />
        <appender-ref ref="STDOUT" /> 
    </logger> 
   <!-- for all other loggers log only info and above log messages -->
    <root>
        <priority value="INFO"/> 
        <appender-ref ref="STDOUT" /> 
    </root> 
</log4j:configuration> 

applicationContext.xml (обрезано)

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:jdbc="http://www.springframework.org/schema/jdbc"
       xmlns:jee="http://www.springframework.org/schema/jee"
       xsi:schemaLocation="
            http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans.xsd
            http://www.springframework.org/schema/aop
            http://www.springframework.org/schema/aop/spring-aop.xsd
            http://www.springframework.org/schema/tx
            http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
            http://www.springframework.org/schema/jdbc
            http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context-3.0.xsd
            http://www.springframework.org/schema/jee 
            http://www.springframework.org/schema/jee/spring-jee-3.0.xsd">
    <context:annotation-config/>            
    <context:component-scan base-package="com.aerose" />
    <jee:jndi-lookup id="dataSource" jndi-name="jdbc/MySQLDataSource" />

    <bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/>

    <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="persistenceUnitName" value="co05in" />
    </bean>

    <bean id="transactionManager" class="org.springframework.transaction.jta.JtaTransactionManager"/>

    ... removed service beans... 

    <tx:annotation-driven  transaction-manager="transactionManager"/>
</beans>

Что выводится на консоль при запуске:

INFO: Instantiated an instance of org.hibernate.validator.engine.resolver.JPATraversableResolver.
INFO: Hibernate Annotations 3.5.0-Final
INFO: Hibernate 3.5.0-Final
INFO: hibernate.properties not found
INFO: Bytecode provider name : javassist
INFO: using JDK 1.4 java.sql.Timestamp handling
INFO: Hibernate Commons Annotations 3.2.0.Final
INFO: Hibernate EntityManager 3.5.0-Final

...removed logging for peristence unit which was mostly just pages of "Binding Named query:..."

INFO: Hibernate Validator not found: ignoring
INFO: Instantiated an instance of org.hibernate.validator.engine.resolver.JPATraversableResolver.
INFO: Instantiated an instance of org.hibernate.validator.engine.resolver.JPATraversableResolver.
INFO: Unable to find org.hibernate.search.event.FullTextIndexEventListener on the classpath. Hibernate Search is not enabled.
INFO: Instantiated an instance of org.hibernate.validator.engine.resolver.JPATraversableResolver.
INFO: Initializing connection provider: org.hibernate.ejb.connection.InjectedDataSourceConnectionProvider
INFO: Using provided datasource
INFO: RDBMS: DB2 UDB for AS/400, version: 06.01.0000 V6R1m0
INFO: JDBC driver: AS/400 Toolbox for Java JDBC Driver, version: 9.4
INFO: Using dialect: org.hibernate.dialect.DB2400Dialect
INFO: Disabling contextual LOB creation as JDBC driver reported JDBC version [3] less than 4
INFO: Transaction strategy: org.hibernate.ejb.transaction.JoinableCMTTransactionFactory
INFO: instantiating TransactionManagerLookup: org.hibernate.transaction.SunONETransactionManagerLookup
INFO: instantiated TransactionManagerLookup
INFO: Automatic flush during beforeCompletion(): disabled
INFO: Automatic session close at end of transaction: disabled
INFO: Scrollable result sets: enabled
INFO: JDBC3 getGeneratedKeys(): enabled
INFO: Connection release mode: auto
INFO: Default batch fetch size: 1
INFO: Generate SQL with comments: disabled
INFO: Order SQL updates by primary key: disabled
INFO: Order SQL inserts for batching: disabled
INFO: Query translator: org.hibernate.hql.ast.ASTQueryTranslatorFactory
INFO: Using ASTQueryTranslatorFactory
INFO: Query language substitutions: {}
INFO: JPA-QL strict compliance: enabled
INFO: Second-level cache: enabled
INFO: Query cache: disabled
INFO: Cache region factory : org.hibernate.cache.impl.NoCachingRegionFactory
INFO: Optimize cache for minimal puts: disabled
INFO: Structured second-level cache entries: disabled
INFO: Statistics: disabled
INFO: Deleted entity synthetic identifier rollback: disabled
INFO: Default entity-mode: pojo
INFO: Named query checking : enabled
INFO: Check Nullability in Core (should be disabled when Bean Validation is on): disabled
INFO: building session factory
INFO: Not binding factory to JNDI, no JNDI name configured
INFO: JNDI InitialContext properties:{}
INFO: PWC1412: WebModule[null] ServletContext.log():Initializing Spring root WebApplicationContext
INFO: Root WebApplicationContext: initialization started
INFO: Refreshing Root WebApplicationContext: startup date [Wed Jul 27 15:04:50 MDT 2011]; root of context hierarchy
INFO: Loading XML bean definitions from class path resource [applicationContext.xml]
INFO: JSR-250 'javax.annotation.ManagedBean' found and supported for component scanning
INFO: JSR-330 'javax.inject.Named' annotation found and supported for component scanning
INFO: JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
INFO: Building JPA container EntityManagerFactory for persistence unit 'co05in'

...removed logging for peristence unit which was mostly just pages of "Binding Named query:..."

INFO: Hibernate Validator not found: ignoring
INFO: Instantiated an instance of org.hibernate.validator.engine.resolver.JPATraversableResolver.
INFO: Instantiated an instance of org.hibernate.validator.engine.resolver.JPATraversableResolver.
INFO: Unable to find org.hibernate.search.event.FullTextIndexEventListener on the classpath. Hibernate Search is not enabled.
INFO: Instantiated an instance of org.hibernate.validator.engine.resolver.JPATraversableResolver.
INFO: Initializing connection provider: org.hibernate.ejb.connection.InjectedDataSourceConnectionProvider
INFO: Using provided datasource
INFO: RDBMS: DB2 UDB for AS/400, version: 06.01.0000 V6R1m0
INFO: JDBC driver: AS/400 Toolbox for Java JDBC Driver, version: 9.4
INFO: Using dialect: org.hibernate.dialect.DB2400Dialect
INFO: Disabling contextual LOB creation as JDBC driver reported JDBC version [3] less than 4
INFO: Transaction strategy: org.hibernate.ejb.transaction.JoinableCMTTransactionFactory
INFO: instantiating TransactionManagerLookup: org.hibernate.transaction.SunONETransactionManagerLookup
INFO: instantiated TransactionManagerLookup
INFO: Automatic flush during beforeCompletion(): disabled
INFO: Automatic session close at end of transaction: disabled
INFO: Scrollable result sets: enabled
INFO: JDBC3 getGeneratedKeys(): enabled
INFO: Connection release mode: auto
INFO: Default batch fetch size: 1
INFO: Generate SQL with comments: disabled
INFO: Order SQL updates by primary key: disabled
INFO: Order SQL inserts for batching: disabled
INFO: Query translator: org.hibernate.hql.ast.ASTQueryTranslatorFactory
INFO: Using ASTQueryTranslatorFactory
INFO: Query language substitutions: {}
INFO: JPA-QL strict compliance: enabled
INFO: Second-level cache: enabled
INFO: Query cache: disabled
INFO: Cache region factory : org.hibernate.cache.impl.NoCachingRegionFactory
INFO: Optimize cache for minimal puts: disabled
INFO: Structured second-level cache entries: disabled
INFO: Statistics: disabled
INFO: Deleted entity synthetic identifier rollback: disabled
INFO: Default entity-mode: pojo
INFO: Named query checking : enabled
INFO: Check Nullability in Core (should be disabled when Bean Validation is on): disabled
INFO: building session factory
INFO: Not binding factory to JNDI, no JNDI name configured
INFO: JNDI InitialContext properties:{}
INFO: Bean 'entityManagerFactory' of type [class org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@5ecada2f: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.annotation.internalPersistenceAnnotationProcessor,dataSource,org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor#0,entityManagerFactory,transactionManager,inventoryService,codeService,orderService,addressService,partService,pickTicketService,employeeService,batchService,rateCodeService,payPeriodService,basicORMParser,org.springframework.aop.config.internalAutoProxyCreator,org.springframework.transaction.annotation.AnnotationTransactionAttributeSource#0,org.springframework.transaction.interceptor.TransactionInterceptor#0,org.springframework.transaction.config.internalTransactionAdvisor]; root of factory hierarchy
INFO: Using JTA UserTransaction: com.sun.enterprise.transaction.UserTransactionImpl@72ae2192
INFO: Using JTA TransactionManager: com.sun.enterprise.transaction.TransactionManagerHelper@61e3310
INFO: Using JTA TransactionSynchronizationRegistry: com.sun.enterprise.transaction.TransactionSynchronizationRegistryImpl@2877770c
INFO: Root WebApplicationContext: initialization completed in 4725 ms
INFO: Parsing configuration file [struts-default.xml]
INFO: Parsing configuration file [struts-plugin.xml]
INFO: Parsing configuration file [struts.xml]
INFO: Initializing Struts-Spring integration...
INFO: Setting autowire strategy to name
INFO: ... initialized Struts-Spring integration successfully
INFO: WEB0671: Loading application [com.aerose_PartGroupMaster_war_2011.04.12] at [/com.aerose_PartGroupMaster_war_2011.04.12]
INFO: com.aerose_PartGroupMaster_war_2011.04.12 was successfully deployed in 25,884 milliseconds.
INFO: log4j: reset attribute= "false".
INFO: log4j: Threshold ="null".
INFO: log4j: Retreiving an instance of org.apache.log4j.Logger.
INFO: log4j: Setting [com.opensymphony] additivity to [true].
INFO: log4j: Level value for com.opensymphony is  [ERROR].
INFO: log4j: com.opensymphony level set to ERROR
INFO: log4j: Class name: [org.apache.log4j.ConsoleAppender]
INFO: log4j: Setting property [target] to [System.out].
INFO: log4j: Parsing layout of class: "org.apache.log4j.PatternLayout"
INFO: log4j: Setting property [conversionPattern] to [%d{ABSOLUTE} %5p %c{1}:%L - %m%n].
INFO: log4j: Adding appender named [STDOUT] to category [com.opensymphony].
INFO: log4j: Retreiving an instance of org.apache.log4j.Logger.
INFO: log4j: Setting [org.apache.struts2] additivity to [true].
INFO: log4j: Level value for org.apache.struts2 is  [ERROR].
INFO: log4j: org.apache.struts2 level set to ERROR
INFO: log4j: Adding appender named [STDOUT] to category [org.apache.struts2].
INFO: log4j: Retreiving an instance of org.apache.log4j.Logger.
INFO: log4j: Setting [org.hibernate] additivity to [true].
INFO: log4j: Level value for org.hibernate is  [TRACE].
INFO: log4j: org.hibernate level set to TRACE
INFO: log4j: Adding appender named [STDOUT] to category [org.hibernate].
INFO: log4j: Retreiving an instance of org.apache.log4j.Logger.
INFO: log4j: Setting [org.hibernate.hql] additivity to [true].
INFO: log4j: Level value for org.hibernate.hql is  [TRACE].
INFO: log4j: org.hibernate.hql level set to TRACE
INFO: log4j: Adding appender named [STDOUT] to category [org.hibernate.hql].
INFO: log4j: Retreiving an instance of org.apache.log4j.Logger.
INFO: log4j: Setting [org.hibernate.SQL] additivity to [true].
INFO: log4j: Level value for org.hibernate.SQL is  [TRACE].
INFO: log4j: org.hibernate.SQL level set to TRACE
INFO: log4j: Adding appender named [STDOUT] to category [org.hibernate.SQL].
INFO: log4j: Retreiving an instance of org.apache.log4j.Logger.
INFO: log4j: Setting [org.hibernate.type] additivity to [true].
INFO: log4j: Level value for org.hibernate.type is  [TRACE].
INFO: log4j: org.hibernate.type level set to TRACE
INFO: log4j: Adding appender named [STDOUT] to category [org.hibernate.type].
INFO: log4j: Retreiving an instance of org.apache.log4j.Logger.
INFO: log4j: Setting [org.springframework] additivity to [true].
INFO: log4j: Level value for org.springframework is  [WARN].
INFO: log4j: org.springframework level set to WARN
INFO: log4j: Adding appender named [STDOUT] to category [org.springframework].
INFO: log4j: Level value for root is  [INFO].
INFO: log4j: root level set to INFO
INFO: log4j: Adding appender named [STDOUT] to category [root].

Ответы [ 2 ]

4 голосов
/ 26 июля 2011

Я вытащил эти зависимости из моего старого проекта. Обновите версии в соответствии с вашим проектом.

Пример зависимостей Maven

<!-- this will transitively include the JPA API and Hibernate Core. -->
<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-entitymanager</artifactId>
    <version>3.4.0.GA</version>
</dependency>

<dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.16</version>
</dependency>

<!-- Hibernate uses slf4j. This will route slf4j log statements to log4j. -->
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-log4j12</artifactId>
    <version>1.4.2</version>
</dependency>

Пример log4j.properties

Я использую файл свойств, а не файл XML, но они должны быть легко переведены в файл XML, если вы предпочитаете это. Кроме того, мы используем системные свойства для нескольких параметров ведения журнала, просто измените их на соответствующие значения в зависимости от ваших потребностей.

#log4j.rootLogger=INFO, C
log4j.rootLogger=${LOG_LEVEL}, R

# ConsoleAppender for developers
log4j.appender.C=org.apache.log4j.ConsoleAppender
log4j.appender.C.layout=org.apache.log4j.PatternLayout
log4j.appender.C.layout.ConversionPattern=%d [%t] %-5p %c - %m%n

# RollingFileAppender for remote deployments
log4j.appender.R=org.apache.log4j.RollingFileAppender
log4j.appender.R.file=${LOG_HOME}/LogFileName.log
log4j.appender.R.MaxFileSize=${LOG_MAXFILESIZE}
log4j.appender.R.MaxBackupIndex=${LOG_MAXBACKUPINDEX}
log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=%d [%t] %-5p %c - %m%n

log4j.logger.org.hibernate=INFO
0 голосов
/ 28 июля 2011

Какие у вас доказательства того, что ваша конфигурация log4j используется? Держу пари, что он использует другой конфигурационный файл. Добавьте -Dlog4j.debug в вашу командную строку, и Log4J покажет, как он настраивается.

...