• Stars
    star
    174
  • Rank 213,271 (Top 5 %)
  • Language
    Java
  • License
    Apache License 2.0
  • Created about 6 years ago
  • Updated 27 days ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

sofa-common-tools is a library that provide some utility functions to other SOFA libraries.

sofa-common-tools

build Coverage Status License maven

sofa-common-tools is a common dependency of SOFAStack middleware, it provides:

  1. Separate log space for application and middleware
  2. SOFA thread

The audience of this library is middleware and SDK developer.

Note: Since version 1.2.0, sofa-common-tools don't support JDK 1.6 anymore.

Background

In daily developing, Java logging usually consists of choosing a log facade (e.g., JCL and SLF4j) and log implementation (e.g., Log4j2 and logback). Say you are developing an application that uses a JAR which utilizes log4j2 for logging. In such scenario, you cannot choose log implementation other than log4j2 (log implementation conflicts if you choose Logback). Some solutions available:

  1. The jar uses log facade instead log implementation but application developers still have to provide log configuration
  2. The jar initialize loggers and appenders programmatically (This works well in Multi-ClassLoader environment where middleware/SDK developers handle many repeated work)
  3. Application resort to same log implementation as the JAR and provide also log configuration

None of the above solutions is perfect, sofa-common-tools provides a Midas touch: middleware/SDK developers print logs using only facade and hand the right to select whichever log implementation to application developer. At the mean time, middleware/SDK developers provide log configurations per log implementation. sofa-common-tools detects automatically the log implementation and initializes appenders and loggers for middleware/SDK. To differentiate SDKs/middlewares, each jar has its own log context and log space identifiable via SpaceID in sofa-common-tools.

Some notes:

  • sofa-common-tools only supports SLF4j facade currently

Quick Start

Say you are developing an OCR SDK for downstream to integrate. First, you choose com.alipay.sdk.ocr as your log space. Second, define a logger factory to retrieve all the loggers you need:

import org.slf4j.Logger;
import com.alipay.sofa.common.log.LoggerSpaceManager;

public class AlipayOcrLoggerFactory {
    private static final String OCR_LOGGER_SPACE = "com.alipay.sdk.ocr";

    public static Logger getLogger(String name) {
        if (name == null || name.isEmpty()) {
            return null;
        }

        return LoggerSpaceManager.getLoggerBySpace(name, OCR_LOGGER_SPACE);
    }

    public static Logger getLogger(Class<?> klass) {
        if (klass == null) {
            return null;
        }

        return getLogger(klass.getCanonicalName());
    }
}

Third, create log configuration for your log space in classpath (space name com.alipay.sdk.ocr maps to com/alipay/sdk/ocr/log/ ), for example

$ cd com/alipay/sdk/ocr/log && tree
.
โ”œโ”€โ”€ log4j
โ”‚ย ย  โ””โ”€โ”€ log-conf.xml
โ”œโ”€โ”€ log4j2
โ”‚ย ย  โ””โ”€โ”€ log-conf.xml
โ””โ”€โ”€ logback
    โ””โ”€โ”€ log-conf.xml

The directory name is quite self-evident. If application choose a log implementation you don't configure, error will be thrown.

A sample configuration for logback logback/log-conf.xml:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <appender name="stdout" class="ch.qos.logback.core.ConsoleAppender">
        <encoder charset="UTF-8">
            <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
        </encoder>
    </appender>

    <logger name="com.alipay.foo" level="INFO" additivity="false">
        <appender-ref ref="stdout"/>
    </logger>

    <root level="INFO">
        <appender-ref ref="stdout"/>
    </root>
</configuration>

Lastly, just logging

public class Main {
    public static void main(String[] args) {
        Logger ocrLogger = AlipayOcrLoggerFactory.getLogger("com.alipay.foo");
        ocrLogger.info("hello world");
    }
}

In console, the following log will be printed:

17:42:41.083 [main] INFO com.alipay.foo - hello world

Configuration

The configuration of corresponding logging implementation can be parameterized, that is to say, placeholders are allowed in XML file. By default, sofa-common-tools provides following parameters with sensible default values:

Parameter Default value
logging.path ${user.home}
file.encoding UTF-8
logging.level.{spaceName} INFO
logging.path.{spaceName} ${logging.path}

Application is able to override the value through JVM options, e.g., -Dlogging.path=/home/admin.

Customized Parameter

Middlewares/SDKs can defined customized parameters for xml placeholders as well. Those parameters must be initialized before using:

import org.slf4j.Logger;
import com.alipay.sofa.common.log.LoggerSpaceManager;import java.util.HashMap;

public class AlipayOcrLoggerFactory {
    private static final String OCR_LOGGER_SPACE = "com.alipay.sdk.ocr";

    static {
        // Note: this step is important, as in Ark environment your SDK may be used in module dependency
        // and will be initialized multiple times.
        if (!MultiAppLoggerSpaceManager.isSpaceInitialized(OCR_LOGGER_SPACE)) {
            Map spaceIdProperties = new HashMap<String, String>();
            // Initialize your parameters here
            MultiAppLoggerSpaceManager.init(OCR_LOGGER_SPACE, spaceIdProperties);
        }
    }

    public static Logger getLogger(String name) {
        if (name == null || name.isEmpty()) {
            return null;
        }

        return LoggerSpaceManager.getLoggerBySpace(name, OCR_LOGGER_SPACE);
    }

    public static Logger getLogger(Class<?> klass) {
        if (klass == null) {
            return null;
        }

        return getLogger(klass.getCanonicalName());
    }
}

Debugging

  1. The logging ability can be disabled totally through sofa.middleware.log.disable JVM option (Of course for middleware/SDK jar using sofa-common-tools).
  2. Debugging with specific log implementation, lock-down of other log implementation, e.g., -Dlogback.middleware.log.disable=true disables logback. All supported switch:
    • log4j.middleware.log.disable
    • log4j2.middleware.log.disable
    • logback.middleware.log.disable

Miscellaneous

  • sofa.middleware.log.disable, defaults to false
  • logback.middleware.log.disable, defaults to false
  • log4j2.middleware.log.disable, defaults to false
  • log4j.middleware.log.disable, defaults to false

LogLog

sofa-common-tools uses internally System.out for logging, logging level can be set via JVM option sofa.middleware.log.internal.level.

Console logging

  • Global configuration
    • Switch sofa.middleware.log.console toggles console logging for all middleware/SDK, defaults to false
    • sofa.middleware.log.console.level configures log level globally
  • Independent middleware/SDK configuration
    • Switch sofa.middleware.log.${spaceid}.console toggles console logging for corresponding middleware/SDK, defaults to false
    • sofa.middleware.log.{space id}.console.level configures log level correspondingly, which overrides global log level
Logging pattern
  • logback: sofa.middleware.log.console.logback.pattern defaults to %d{yyyy-MM-dd HH:mm:ss.SSS} %5p ${PID:- } --- [%15.15t] %-40.40logger{39} : %m%n
  • log4j2: sofa.middleware.log.console.log4j2.pattern defaults to %d{yyyy-MM-dd HH:mm:ss.SSS} %5p %X{PID} --- [%15.15t] %-40.40logger{39} : %m%n

Console logging options can be passed through JVM option or Spring Boot properties.

Compiling

Maven 3.2.5+, JDK Version 1.6+

LICENSE

Apache 2.0

Contribution

Contribution Guide

More Repositories

1

sofa-boot

SOFABoot is a framework that enhances Spring Boot and fully compatible with it, provides readiness check, class isolation, etc.
Java
4,870
star
2

sofa-rpc

SOFARPC is a high-performance, high-extensibility, production-level Java RPC framework.
Java
3,799
star
3

sofa-jraft

A production-grade java implementation of RAFT consensus algorithm.
Java
3,450
star
4

sofa-jarslink

Jarslink is a sofa ark plugin used to manage multi-application deployment
Java
3,041
star
5

sofa-bolt

SOFABolt is a lightweight, easy to use and high performance remoting framework based on Netty.
Java
2,391
star
6

sofa-ark

SOFAArk is a light-weight๏ผŒjava based classloader isolation framework.
Java
1,529
star
7

sofa-tracer

SOFATracer is a component for the distributed system call trace. And through a unified traceId logging the logs of various network calls in the invoking link. These logs can be used for quick discovery of faults, service governance, etc.
Java
1,089
star
8

sofa-registry

SOFARegistry is a production-level, low-latency, high-availability service registry powered by Ant Financial.
Java
639
star
9

sofa-rpc-node

SOFARPC Node is a high-performance, high-extensibility, production-level Nodejs RPC framework.
JavaScript
609
star
10

sofa-lookout

SOFALookout is a light-weight monitoring and analysis tool
Java
372
star
11

sofa-acts

ACTS is a white box testing framework based on data model drivers.
Java
301
star
12

sofa-rpc-boot-projects

SOFABoot projects for SOFARPC, include starter and samples.
Java
289
star
13

sofa-bolt-node

The Node.js implementation of the SOFABolt protocol
JavaScript
156
star
14

sofa-hessian

An internal improved version of Hessian3/4 powered by Ant Group CO., Ltd.
Java
129
star
15

sofastack-doc

ๅฎ˜็ฝ‘ๅทฒ่ฟ็งป่‡ณ 2.0 ็‰ˆๆœฌ https://github.com/sofastack/sofastack.tech -->
128
star
16

sofa-serverless

a framework to enabe app architecture evolve from monolithic to microservices smoothly by involving modular and macroservices architecture.
Java
113
star
17

sofastack.tech

Source for the SOFAStack website https://www.sofastack.tech
SCSS
105
star
18

spring-cloud-sofastack-samples

Spring Cloud โค๏ธ SOFAStack
Java
93
star
19

sofa-dashboard

Dashboard of SOFAStack.
Java
91
star
20

sofa-bolt-python

The Python implementation of the SOFABolt protocol.
Python
47
star
21

sofa-jraft-jepsen

Clojure
30
star
22

sofa-kubernetes-demo

A demo project that run SOFA in kubernetes.
Java
26
star
23

sofa-node

JavaScript
25
star
24

sofa-bolt-cpp

The C++ implementation of the SOFABolt protocol.
C++
24
star
25

sofa-hessian-node

A performance improved version of Hessian powered by Ant Group.
JavaScript
21
star
26

sofa-dashboard-client

Java
16
star
27

community

SOFAStack community material
14
star
28

sofastack.github.io

Website content of sofastack.io.
HTML
9
star
29

sofa-lookout-node

SOFALookout Nodejs Client
JavaScript
7
star
30

sofa-build

sofa-build is a common utility project for SOFABoot to use for plugin and dependency management.
6
star
31

sofa-common-go

sofa golang ้€š็”จ็ฑปๅบ“
Go
3
star
32

sofa-registry-node

Node.js SDK for SOFARegistry
JavaScript
3
star
33

sofa-bolt-go

The Golang implementation of the SOFABolt protocol.
Go
2
star
34

sofa-hessian-go

Go
1
star