# java.util.logging

***

**1. Basic Logging:**

```java
import java.util.logging.Logger;

public class BasicLogging {
    private static final Logger logger = Logger.getLogger(BasicLogging.class.getName());

    public static void main(String[] args) {
        logger.info("This is an informational message.");
        logger.warning("This is a warning message.");
        logger.severe("This is an error message.");
    }
}
```

**2. Logging to Different Handlers:**

```java
import java.util.logging.ConsoleHandler;
import java.util.logging.FileHandler;
import java.util.logging.Logger;

public class DifferentHandlers {
    private static final Logger logger = Logger.getLogger(DifferentHandlers.class.getName());

    public static void main(String[] args) {
        try {
            // Create console handler and set level to INFO
            ConsoleHandler consoleHandler = new ConsoleHandler();
            consoleHandler.setLevel(Level.INFO);
            logger.addHandler(consoleHandler);

            // Create file handler and set level to WARNING
            FileHandler fileHandler = new FileHandler("mylog.log");
            fileHandler.setLevel(Level.WARNING);
            logger.addHandler(fileHandler);

            // Log messages
            logger.info("This is an informational message.");
            logger.warning("This is a warning message.");
            logger.severe("This is an error message.");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
```

**3. Custom Formatter:**

```java
import java.util.logging.Formatter;
import java.util.logging.Handler;
import java.util.logging.LogRecord;
import java.util.logging.Logger;

public class CustomFormatter {
    private static final Logger logger = Logger.getLogger(CustomFormatter.class.getName());

    public static void main(String[] args) {
        // Create a custom formatter
        Formatter formatter = new Formatter() {
            @Override
            public String format(LogRecord record) {
                return String.format("%s: %s\n", record.getLevel(), record.getMessage());
            }
        };

        // Create a console handler and set the custom formatter
        ConsoleHandler consoleHandler = new ConsoleHandler();
        consoleHandler.setFormatter(formatter);

        // Add the console handler to the logger
        logger.addHandler(consoleHandler);

        // Log messages
        logger.info("This is an informational message.");
        logger.warning("This is a warning message.");
        logger.severe("This is an error message.");
    }
}
```

**4. Filters:**

```java
import java.util.logging.Filter;
import java.util.logging.LogRecord;
import java.util.logging.Logger;

public class Filters {
    private static final Logger logger = Logger.getLogger(Filters.class.getName());

    public static void main(String[] args) {
        // Create a filter that only logs messages with a level of WARNING or higher
        Filter filter = new Filter() {
            @Override
            public boolean isLoggable(LogRecord record) {
                return record.getLevel().intValue() >= Level.WARNING.intValue();
            }
        };

        // Add the filter to the logger
        logger.setFilter(filter);

        // Log messages
        logger.info("This is an informational message.");
        logger.warning("This is a warning message.");
        logger.severe("This is an error message.");
    }
}
```

**5. Logging from Exceptions:**

```java
import java.util.logging.Level;
import java.util.logging.Logger;

public class Exceptions {
    private static final Logger logger = Logger.getLogger(Exceptions.class.getName());

    public static void main(String[] args) {
        try {
            // Perform an operation that might throw an exception
            int result = 1 / 0;
        } catch (Exception e) {
            // Log the exception using the severe level
            logger.log(Level.SEVERE, "An exception occurred: " + e.getMessage(), e);
        }
    }
}
```

**6. Logging to a Database:**

```java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.util.logging.Handler;
import java.util.logging.LogRecord;

public class DatabaseHandler implements Handler {
    private Connection connection;

    public DatabaseHandler() {
        try {
            connection = DriverManager.getConnection("jdbc:postgresql://localhost:5432/mydatabase", "user", "password");
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void close() {
        try {
            connection.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void flush() {
        try {
            connection.commit();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void publish(LogRecord record) {
        try {
            String sql = "INSERT INTO log (level, message) VALUES (?, ?)";
            PreparedStatement statement = connection.prepareStatement(sql);
            statement.setString(1, record.getLevel().getName());
            statement.setString(2, record.getMessage());
            statement.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
```

**7. Logging to a Web Service:**

```java
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.logging.Handler;
import java.util.logging.LogRecord;

public class WebServiceHandler implements Handler {
    private String url;

    public WebServiceHandler(String url) {
        this.url = url;
    }

    @Override
    public void close() {
        // Do nothing
    }

    @Override
    public void flush() {
        // Do nothing
    }

    @Override
    public void publish(LogRecord record) {
        try {
            // Create a URL object
            URL urlObject = new URL(this.url);

            // Create an HttpURLConnection
            HttpURLConnection connection = (HttpURLConnection) urlObject.openConnection();
            connection.setRequestMethod("POST");
            connection.setDoOutput(true);

            // Write the log record to the connection
            connection.getOutputStream().write(record.getMessage().getBytes());
            connection.getOutputStream().close();

            // Read the response from the web service
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String response = reader.readLine();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
```

**8. Level Inheritance:**

```java
import java.util.logging.Level;
import java.util.logging.Logger;

public class LevelInheritance {
    private static final Logger parentLogger = Logger.getLogger("parent");
    private static final Logger childLogger = Logger.getLogger("parent.child");

    public static void main(String[] args) {
        // Set the level for the parent logger
        parentLogger.setLevel(Level.WARNING);

        // Log messages to the parent and child loggers
        parentLogger.info("This is an informational message.");
        childLogger.info("This is an informational message.");
        parentLogger.warning("This is a warning message.");
        childLogger.warning("This is a warning message.");
        parentLogger.severe("This is an error message.");
        childLogger.severe("This is an error message.");
    }
}
```

**9. Loggers by Class Name:**

```java
import java.util.logging.Level;
import java.util.logging.Logger;

public class LoggersByClassName {
    public static void main(String[] args) {
        // Get the logger for the current class
        Logger logger = Logger.getLogger(LoggersByClassName.class.getName());

        // Set the level for the logger
        logger.setLevel(Level.WARNING);

        // Log messages
        logger.info("This is an informational message.");
        logger.warning("This is a warning message.");
        logger.severe("This is an error message.");
    }
}
```

**10. Loggers by Name:**

```java
import java.util.logging.Level;
import java.util.logging.LogManager;
import java.util.logging.Logger;

public class LoggersByName {
    public static void main(String[] args) {
        // Create a custom logger with a specific name
        Logger logger = Logger.getLogger("my.custom.logger");

        // Set the level for the logger
        logger.setLevel(Level.WARNING);

        // Log messages
        logger.info("This is an informational message.");
        logger.warning("This is a warning message.");
        logger.severe("This is an error message.");
    }
}
```

**11. File Logging with Rotation:**

```java
import java.io.File;
import java.io.IOException;
import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.Logger;

public class FileLoggingWithRotation {
    public static void main(String[] args) {
        // Create a log file with a maximum size of 1MB and a maximum number of 5 files
        FileHandler fileHandler = new FileHandler("mylog.log", 1024 * 1024, 5);

        // Add the file handler to the logger
        Logger logger = Logger.getLogger("my.custom.logger");
        logger.addHandler(fileHandler);

        // Set the level for the logger
        logger.setLevel(Level.WARNING);



```
