A malware classifier template with built-in logging.
Project description
MalwareClassifier
MalwareClassifier is a Python package that provides a template for building a malware classification system with a built-in logging system and configurable settings.
It is designed to be modular, extensible, and easy to install using pip.
Table of Contents
Installation
Option A: Install using pip
pip install MalwareClassifier
Option B: Standard installation
# Clone the repository
git clone git@github.com:cchunhuang/MalwareClassifier.git
cd MalwareClassifier
# Install
pip install .
# Install additional dependencies (optional)
pip install -r requirements.txt
Dependencies
The package requires the following core dependencies:
python_box>=7.3.2- For configuration management with dot notation accesspython-json-logger>=2.0.7- For JSON format logging (optional)
Quick Start
from MalwareClassifier import MalwareClassifier, setup_logging, get_logger
class SubMalwareClassifier(MalwareClassifier):
def __init__(self, config_path="./config.json"):
super().__init__(config_path)
logging_config = setup_logging(log_dir=self.config.folder.log)
self.start_time = logging_config["start_time"]
self.logger = get_logger(__name__)
def get_feature(self):
self.logger.info("Extracting features.")
def get_vector(self):
self.logger.info("Vectorizing.")
def get_model(self, action: str = "train"):
self.logger.info(f"Using model for action: {action}.")
def get_prediction(self):
self.logger.info("Predicting.")
if __name__ == "__main__":
classifier = SubMalwareClassifier()
classifier.get_feature()
classifier.get_vector()
classifier.get_model()
classifier.get_prediction()
Key Features
- The
MalwareClassifierclass inmalware_classifier.pydefines the workflow skeleton. Subclass it to override the following methods:get_feature()- Extracts features from the malware datasetget_vector()- Vectorizes the extracted featuresget_model(action="train")- Trains the model or performs inference (action: "train" or "predict")get_prediction()- Predicts the given files
- Configuration Management: Use
config.jsonwith dot notation access viapython_box(e.g.,self.config.folder.log) - Automatic Directory Creation: All folders specified in config are created automatically via
self.mkdir() - Built-in Logging: Integrated logging system with file and console output
- You can specify your own
config_pathwhen initializing the classifier
Configuration
The package includes a default config.json:
{
"file": {
"label": "./dataset/label.csv"
},
"folder": {
"log": "./output/log/",
"dataset": "./dataset/",
"feature": "./output/feature/",
"vector": "./output/vector/",
"model": "./output/model/",
"predict": "./output/predict/"
},
"params": {
"mode": "detection",
"feature": {
"save": true,
"load": false
},
"vector": {
"save": true,
"load": false
},
"model": {
"save": true,
"load": false
},
"predict": {
"save": true,
"load": false
}
}
}
Configuration Access
After calling super().__init__(), you can access configuration values using dot notation:
- File paths:
self.config.file.label - Directory paths:
self.config.folder.log,self.config.folder.dataset, etc. - Parameters:
self.config.params.mode - Feature settings:
self.config.params.feature.save,self.config.params.vector.load, etc.
Customization
- The
config.jsonstructure is fully customizable - Add new sections or parameters as needed
- Access nested values with dot notation, e.g.
self.config.section.subsection.value - All directories listed in the
foldersection are created automatically viaself.mkdir()
Logging Usage
The logging system is defined in src/MalwareClassifier/logging.py.
Available functions
setup_logging(config=None, config_path=None, reset_handlers=True, log_dir=None)Initialize logging with optional config overrides.- It is recommended to use
setup_logging(log_dir=self.config.folder.log) - Return: logging config (dict)
# Global variables: Process start time captured once per interpreter run START_TIME = datetime.now().strftime("%Y%m%d-%H%M%S") _DEFAULT_CONFIG: Dict[str, Any] = { "version": 1, "disable_existing_loggers": False, "formatters": { "basic": { "format": "[%(levelname)s] %(name)s %(filename)s: %(message)s", "datefmt": "%Y-%m-%d %H:%M:%S", }, "verbose": { "format": "%(asctime)s [%(levelname)s] %(name)s %(filename)s:%(lineno)d - %(message)s", "datefmt": "%Y-%m-%d %H:%M:%S", }, "json": { "class": "pythonjsonlogger.jsonlogger.JsonFormatter", "format": "%(asctime)s %(levelname)s %(name)s %(message)s", }, }, "handlers": { "console": { "class": "logging.StreamHandler", "level": "INFO", "formatter": "basic", "stream": "ext://sys.stdout", }, "file": { "class": "logging.FileHandler", "level": "DEBUG", "formatter": "verbose", "filename": f"malware_classifier-{START_TIME}.log", "encoding": "utf-8", }, }, "root": { "level": "INFO", "handlers": ["console", "file"], }, "start_time": START_TIME }
- It is recommended to use
get_logger(name)Retrieve a logger for any module.
Default behavior
- Logs are written both to console and file.
- Log files are automatically named as:
malware_classifier-YYYYMMDD-HHMMSS.log
Environment variables
| Variable | Description | Example |
|---|---|---|
MALCLASS_LOG_LEVEL |
Set log level | DEBUG, INFO |
MALCLASS_LOG_FILE |
Full path for the log file | /tmp/log.txt |
MALCLASS_LOG_DIR |
Directory for log files | ./output/log |
MALCLASS_LOG_FORMATTER |
Choose formatter: basic, verbose, json |
verbose |
Note: JSON logging is supported through python-json-logger, which is included as a dependency.
Example usage in modules
from MalwareClassifier import setup_logging, get_logger
setup_logging()
logger = get_logger(__name__)
logger.info("This is an info message")
logger.debug("This is a debug message")
Publishing
Check version
pip install -e .
python -c "import MalwareClassifier; print(MalwareClassifier.__version__)"
Publish to PyPI
git tag v0.1.0 # Replace the version
git push origin v0.1.0
# git action will publish it automatically.
Publish to PyPI (Manual)
pip install build twine
python -m build
twine upload dist/*
License
This project is licensed under the terms of the MIT License.
Contact
Project details
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file malwareclassifier-0.1.6.tar.gz.
File metadata
- Download URL: malwareclassifier-0.1.6.tar.gz
- Upload date:
- Size: 14.1 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.11.14
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
757f328571b0b636d93b9eaa3088539b502924c17b444bc1dacd9c82a878e4c5
|
|
| MD5 |
85719f7da4a91ba3b40e7ca1e3ffc21d
|
|
| BLAKE2b-256 |
e6a63a074fe407a5e50313d87525ed97bf4eb54c3a023d586747d9a6a4d0dfbb
|
File details
Details for the file malwareclassifier-0.1.6-py3-none-any.whl.
File metadata
- Download URL: malwareclassifier-0.1.6-py3-none-any.whl
- Upload date:
- Size: 10.2 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.11.14
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
64058916afab1eb3810eb468121888d66e66bb85bf0834e106017336d8399575
|
|
| MD5 |
65db702fd3baf57d272754f4bd032200
|
|
| BLAKE2b-256 |
74f837b80a87a932e4a5f081fd3475a1198c4efc8b9926f2a936dd9c6d01a660
|