Compare commits
1 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| abfd07331e |
@@ -0,0 +1,22 @@
|
|||||||
|
{
|
||||||
|
"permissions": {
|
||||||
|
"allow": [
|
||||||
|
"Bash(docker --version)",
|
||||||
|
"Bash(docker compose *)",
|
||||||
|
"Bash(curl *)",
|
||||||
|
"Bash(docker cp *)",
|
||||||
|
"Bash(docker stop *)",
|
||||||
|
"Bash(docker rm *)",
|
||||||
|
"Bash(docker network *)",
|
||||||
|
"Bash(docker volume *)",
|
||||||
|
"Bash(python -c \"import sys,json; d=json.load\\(sys.stdin\\); print\\('timestamp:', d['hits'][0]['timestamp']\\)\")",
|
||||||
|
"Bash(python -c ' *)",
|
||||||
|
"Bash(python -c \"import sys,json; d=json.load\\(sys.stdin\\); print\\('bucket:', d['time_buckets'][0]['key'] if d['time_buckets'] else 'none'\\)\")",
|
||||||
|
"Bash(python -c \"import sys,json; d=json.load\\(sys.stdin\\); print\\('found in range:', d['total'], 'logs'\\)\")",
|
||||||
|
"Bash(git init *)",
|
||||||
|
"Bash(git remote *)",
|
||||||
|
"Bash(git add *)",
|
||||||
|
"Bash(git config *)"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
# LogHive Environment Configuration
|
||||||
|
|
||||||
|
# ── API ─────────────────────────────────────────────────────
|
||||||
|
API_HOST=0.0.0.0
|
||||||
|
API_PORT=8000
|
||||||
|
DEBUG=false
|
||||||
|
CORS_ORIGINS=*
|
||||||
|
|
||||||
|
# ── Security ────────────────────────────────────────────────
|
||||||
|
SECRET_KEY=change-me-to-a-random-string
|
||||||
|
TOKEN_EXPIRE_HOURS=720
|
||||||
|
|
||||||
|
# ── PostgreSQL ──────────────────────────────────────────────
|
||||||
|
DATABASE_URL=postgresql+asyncpg://LogHive:LogHive@localhost:5432/LogHive
|
||||||
|
|
||||||
|
# ── Redis ───────────────────────────────────────────────────
|
||||||
|
REDIS_URL=redis://localhost:6379/0
|
||||||
|
CELERY_BROKER_URL=redis://localhost:6379/1
|
||||||
|
CELERY_RESULT_BACKEND=redis://localhost:6379/2
|
||||||
|
|
||||||
|
# ── Log Retention ───────────────────────────────────────────
|
||||||
|
LOG_RETENTION_DAYS=30
|
||||||
|
LOG_COLD_STORAGE_DAYS=7
|
||||||
|
|
||||||
|
# ── Notifications (optional) ────────────────────────────────
|
||||||
|
FEISHU_WEBHOOK_URL=
|
||||||
|
DINGTALK_WEBHOOK_URL=
|
||||||
+18
-167
@@ -1,176 +1,27 @@
|
|||||||
# ---> Python
|
# Python
|
||||||
# Byte-compiled / optimized / DLL files
|
|
||||||
__pycache__/
|
__pycache__/
|
||||||
*.py[cod]
|
*.py[cod]
|
||||||
*$py.class
|
|
||||||
|
|
||||||
# C extensions
|
|
||||||
*.so
|
|
||||||
|
|
||||||
# Distribution / packaging
|
|
||||||
.Python
|
|
||||||
build/
|
|
||||||
develop-eggs/
|
|
||||||
dist/
|
|
||||||
downloads/
|
|
||||||
eggs/
|
|
||||||
.eggs/
|
|
||||||
lib/
|
|
||||||
lib64/
|
|
||||||
parts/
|
|
||||||
sdist/
|
|
||||||
var/
|
|
||||||
wheels/
|
|
||||||
share/python-wheels/
|
|
||||||
*.egg-info/
|
*.egg-info/
|
||||||
.installed.cfg
|
dist/
|
||||||
*.egg
|
build/
|
||||||
MANIFEST
|
.venv/
|
||||||
|
|
||||||
# PyInstaller
|
|
||||||
# Usually these files are written by a python script from a template
|
|
||||||
# before PyInstaller builds the exe, so as to inject date/other infos into it.
|
|
||||||
*.manifest
|
|
||||||
*.spec
|
|
||||||
|
|
||||||
# Installer logs
|
|
||||||
pip-log.txt
|
|
||||||
pip-delete-this-directory.txt
|
|
||||||
|
|
||||||
# Unit test / coverage reports
|
|
||||||
htmlcov/
|
|
||||||
.tox/
|
|
||||||
.nox/
|
|
||||||
.coverage
|
|
||||||
.coverage.*
|
|
||||||
.cache
|
|
||||||
nosetests.xml
|
|
||||||
coverage.xml
|
|
||||||
*.cover
|
|
||||||
*.py,cover
|
|
||||||
.hypothesis/
|
|
||||||
.pytest_cache/
|
|
||||||
cover/
|
|
||||||
|
|
||||||
# Translations
|
|
||||||
*.mo
|
|
||||||
*.pot
|
|
||||||
|
|
||||||
# Django stuff:
|
|
||||||
*.log
|
|
||||||
local_settings.py
|
|
||||||
db.sqlite3
|
|
||||||
db.sqlite3-journal
|
|
||||||
|
|
||||||
# Flask stuff:
|
|
||||||
instance/
|
|
||||||
.webassets-cache
|
|
||||||
|
|
||||||
# Scrapy stuff:
|
|
||||||
.scrapy
|
|
||||||
|
|
||||||
# Sphinx documentation
|
|
||||||
docs/_build/
|
|
||||||
|
|
||||||
# PyBuilder
|
|
||||||
.pybuilder/
|
|
||||||
target/
|
|
||||||
|
|
||||||
# Jupyter Notebook
|
|
||||||
.ipynb_checkpoints
|
|
||||||
|
|
||||||
# IPython
|
|
||||||
profile_default/
|
|
||||||
ipython_config.py
|
|
||||||
|
|
||||||
# pyenv
|
|
||||||
# For a library or package, you might want to ignore these files since the code is
|
|
||||||
# intended to run in multiple environments; otherwise, check them in:
|
|
||||||
# .python-version
|
|
||||||
|
|
||||||
# pipenv
|
|
||||||
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
|
|
||||||
# However, in case of collaboration, if having platform-specific dependencies or dependencies
|
|
||||||
# having no cross-platform support, pipenv may install dependencies that don't work, or not
|
|
||||||
# install all needed dependencies.
|
|
||||||
#Pipfile.lock
|
|
||||||
|
|
||||||
# UV
|
|
||||||
# Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
|
|
||||||
# This is especially recommended for binary packages to ensure reproducibility, and is more
|
|
||||||
# commonly ignored for libraries.
|
|
||||||
#uv.lock
|
|
||||||
|
|
||||||
# poetry
|
|
||||||
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
|
|
||||||
# This is especially recommended for binary packages to ensure reproducibility, and is more
|
|
||||||
# commonly ignored for libraries.
|
|
||||||
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
|
|
||||||
#poetry.lock
|
|
||||||
|
|
||||||
# pdm
|
|
||||||
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
|
|
||||||
#pdm.lock
|
|
||||||
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
|
|
||||||
# in version control.
|
|
||||||
# https://pdm.fming.dev/latest/usage/project/#working-with-version-control
|
|
||||||
.pdm.toml
|
|
||||||
.pdm-python
|
|
||||||
.pdm-build/
|
|
||||||
|
|
||||||
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
|
|
||||||
__pypackages__/
|
|
||||||
|
|
||||||
# Celery stuff
|
|
||||||
celerybeat-schedule
|
|
||||||
celerybeat.pid
|
|
||||||
|
|
||||||
# SageMath parsed files
|
|
||||||
*.sage.py
|
|
||||||
|
|
||||||
# Environments
|
|
||||||
.env
|
|
||||||
.venv
|
|
||||||
env/
|
|
||||||
venv/
|
venv/
|
||||||
ENV/
|
|
||||||
env.bak/
|
|
||||||
venv.bak/
|
|
||||||
|
|
||||||
# Spyder project settings
|
# Environment
|
||||||
.spyderproject
|
.env
|
||||||
.spyproject
|
|
||||||
|
|
||||||
# Rope project settings
|
# Node / Frontend
|
||||||
.ropeproject
|
node_modules/
|
||||||
|
frontend/dist/
|
||||||
|
|
||||||
# mkdocs documentation
|
# IDE
|
||||||
/site
|
.idea/
|
||||||
|
.vscode/
|
||||||
|
*.swp
|
||||||
|
|
||||||
# mypy
|
# Docker
|
||||||
.mypy_cache/
|
docker-compose.override.yml
|
||||||
.dmypy.json
|
|
||||||
dmypy.json
|
|
||||||
|
|
||||||
# Pyre type checker
|
|
||||||
.pyre/
|
|
||||||
|
|
||||||
# pytype static type analyzer
|
|
||||||
.pytype/
|
|
||||||
|
|
||||||
# Cython debug symbols
|
|
||||||
cython_debug/
|
|
||||||
|
|
||||||
# PyCharm
|
|
||||||
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
|
|
||||||
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
|
|
||||||
# and can be added to the global gitignore or merged into this file. For a more nuclear
|
|
||||||
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
|
|
||||||
#.idea/
|
|
||||||
|
|
||||||
# Ruff stuff:
|
|
||||||
.ruff_cache/
|
|
||||||
|
|
||||||
# PyPI configuration file
|
|
||||||
.pypirc
|
|
||||||
|
|
||||||
|
# OS
|
||||||
|
.DS_Store
|
||||||
|
Thumbs.db
|
||||||
|
|||||||
@@ -1,235 +0,0 @@
|
|||||||
GNU AFFERO GENERAL PUBLIC LICENSE
|
|
||||||
Version 3, 19 November 2007
|
|
||||||
|
|
||||||
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
|
|
||||||
|
|
||||||
Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
|
|
||||||
|
|
||||||
Preamble
|
|
||||||
|
|
||||||
The GNU Affero General Public License is a free, copyleft license for software and other kinds of works, specifically designed to ensure cooperation with the community in the case of network server software.
|
|
||||||
|
|
||||||
The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, our General Public Licenses are intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users.
|
|
||||||
|
|
||||||
When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things.
|
|
||||||
|
|
||||||
Developers that use our General Public Licenses protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License which gives you legal permission to copy, distribute and/or modify the software.
|
|
||||||
|
|
||||||
A secondary benefit of defending all users' freedom is that improvements made in alternate versions of the program, if they receive widespread use, become available for other developers to incorporate. Many developers of free software are heartened and encouraged by the resulting cooperation. However, in the case of software used on network servers, this result may fail to come about. The GNU General Public License permits making a modified version and letting the public access it on a server without ever releasing its source code to the public.
|
|
||||||
|
|
||||||
The GNU Affero General Public License is designed specifically to ensure that, in such cases, the modified source code becomes available to the community. It requires the operator of a network server to provide the source code of the modified version running there to the users of that server. Therefore, public use of a modified version, on a publicly accessible server, gives the public access to the source code of the modified version.
|
|
||||||
|
|
||||||
An older license, called the Affero General Public License and published by Affero, was designed to accomplish similar goals. This is a different license, not a version of the Affero GPL, but Affero has released a new version of the Affero GPL which permits relicensing under this license.
|
|
||||||
|
|
||||||
The precise terms and conditions for copying, distribution and modification follow.
|
|
||||||
|
|
||||||
TERMS AND CONDITIONS
|
|
||||||
|
|
||||||
0. Definitions.
|
|
||||||
|
|
||||||
"This License" refers to version 3 of the GNU Affero General Public License.
|
|
||||||
|
|
||||||
"Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks.
|
|
||||||
|
|
||||||
"The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations.
|
|
||||||
|
|
||||||
To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work.
|
|
||||||
|
|
||||||
A "covered work" means either the unmodified Program or a work based on the Program.
|
|
||||||
|
|
||||||
To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well.
|
|
||||||
|
|
||||||
To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying.
|
|
||||||
|
|
||||||
An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion.
|
|
||||||
|
|
||||||
1. Source Code.
|
|
||||||
The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work.
|
|
||||||
|
|
||||||
A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language.
|
|
||||||
|
|
||||||
The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it.
|
|
||||||
|
|
||||||
The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those
|
|
||||||
subprograms and other parts of the work.
|
|
||||||
|
|
||||||
The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source.
|
|
||||||
|
|
||||||
The Corresponding Source for a work in source code form is that same work.
|
|
||||||
|
|
||||||
2. Basic Permissions.
|
|
||||||
All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law.
|
|
||||||
|
|
||||||
You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you.
|
|
||||||
|
|
||||||
Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary.
|
|
||||||
|
|
||||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
|
||||||
No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures.
|
|
||||||
|
|
||||||
When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures.
|
|
||||||
|
|
||||||
4. Conveying Verbatim Copies.
|
|
||||||
You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program.
|
|
||||||
|
|
||||||
You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee.
|
|
||||||
|
|
||||||
5. Conveying Modified Source Versions.
|
|
||||||
You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions:
|
|
||||||
|
|
||||||
a) The work must carry prominent notices stating that you modified it, and giving a relevant date.
|
|
||||||
|
|
||||||
b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices".
|
|
||||||
|
|
||||||
c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it.
|
|
||||||
|
|
||||||
d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so.
|
|
||||||
|
|
||||||
A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate.
|
|
||||||
|
|
||||||
6. Conveying Non-Source Forms.
|
|
||||||
You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways:
|
|
||||||
|
|
||||||
a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange.
|
|
||||||
|
|
||||||
b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge.
|
|
||||||
|
|
||||||
c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b.
|
|
||||||
|
|
||||||
d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements.
|
|
||||||
|
|
||||||
e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d.
|
|
||||||
|
|
||||||
A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work.
|
|
||||||
|
|
||||||
A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product.
|
|
||||||
|
|
||||||
"Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made.
|
|
||||||
|
|
||||||
If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM).
|
|
||||||
|
|
||||||
The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network.
|
|
||||||
|
|
||||||
Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying.
|
|
||||||
|
|
||||||
7. Additional Terms.
|
|
||||||
"Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions.
|
|
||||||
|
|
||||||
When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission.
|
|
||||||
|
|
||||||
Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms:
|
|
||||||
|
|
||||||
a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or
|
|
||||||
|
|
||||||
b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or
|
|
||||||
|
|
||||||
c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or
|
|
||||||
|
|
||||||
d) Limiting the use for publicity purposes of names of licensors or authors of the material; or
|
|
||||||
|
|
||||||
e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or
|
|
||||||
|
|
||||||
f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors.
|
|
||||||
|
|
||||||
All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying.
|
|
||||||
|
|
||||||
If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms.
|
|
||||||
|
|
||||||
Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way.
|
|
||||||
|
|
||||||
8. Termination.
|
|
||||||
|
|
||||||
You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11).
|
|
||||||
|
|
||||||
However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation.
|
|
||||||
|
|
||||||
Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice.
|
|
||||||
|
|
||||||
Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10.
|
|
||||||
|
|
||||||
9. Acceptance Not Required for Having Copies.
|
|
||||||
|
|
||||||
You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so.
|
|
||||||
|
|
||||||
10. Automatic Licensing of Downstream Recipients.
|
|
||||||
|
|
||||||
Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License.
|
|
||||||
|
|
||||||
An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts.
|
|
||||||
|
|
||||||
You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it.
|
|
||||||
|
|
||||||
11. Patents.
|
|
||||||
|
|
||||||
A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version".
|
|
||||||
|
|
||||||
A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License.
|
|
||||||
|
|
||||||
Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version.
|
|
||||||
|
|
||||||
In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party.
|
|
||||||
|
|
||||||
If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent
|
|
||||||
license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid.
|
|
||||||
|
|
||||||
If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it.
|
|
||||||
|
|
||||||
A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007.
|
|
||||||
|
|
||||||
Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law.
|
|
||||||
|
|
||||||
12. No Surrender of Others' Freedom.
|
|
||||||
|
|
||||||
If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may
|
|
||||||
not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program.
|
|
||||||
|
|
||||||
13. Remote Network Interaction; Use with the GNU General Public License.
|
|
||||||
|
|
||||||
Notwithstanding any other provision of this License, if you modify the Program, your modified version must prominently offer all users interacting with it remotely through a computer network (if your version supports such interaction) an opportunity to receive the Corresponding Source of your version by providing access to the Corresponding Source from a network server at no charge, through some standard or customary means of facilitating copying of software. This Corresponding Source shall include the Corresponding Source for any work covered by version 3 of the GNU General Public License that is incorporated pursuant to the following paragraph.
|
|
||||||
|
|
||||||
Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the work with which it is combined will remain governed by version 3 of the GNU General Public License.
|
|
||||||
|
|
||||||
14. Revised Versions of this License.
|
|
||||||
|
|
||||||
The Free Software Foundation may publish revised and/or new versions of the GNU Affero General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
|
|
||||||
|
|
||||||
Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU Affero General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU Affero General Public License, you may choose any version ever published by the Free Software Foundation.
|
|
||||||
|
|
||||||
If the Program specifies that a proxy can decide which future versions of the GNU Affero General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program.
|
|
||||||
|
|
||||||
Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version.
|
|
||||||
|
|
||||||
15. Disclaimer of Warranty.
|
|
||||||
|
|
||||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
|
||||||
|
|
||||||
16. Limitation of Liability.
|
|
||||||
|
|
||||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
|
|
||||||
|
|
||||||
17. Interpretation of Sections 15 and 16.
|
|
||||||
|
|
||||||
If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee.
|
|
||||||
|
|
||||||
END OF TERMS AND CONDITIONS
|
|
||||||
|
|
||||||
How to Apply These Terms to Your New Programs
|
|
||||||
|
|
||||||
If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms.
|
|
||||||
|
|
||||||
To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found.
|
|
||||||
|
|
||||||
LogHive
|
|
||||||
Copyright (C) 2026 v6ole
|
|
||||||
|
|
||||||
This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
|
|
||||||
|
|
||||||
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
|
|
||||||
|
|
||||||
You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
|
|
||||||
|
|
||||||
Also add information on how to contact you by electronic and paper mail.
|
|
||||||
|
|
||||||
If your software can interact with users remotely through a computer network, you should also make sure that it provides a way for users to get its source. For example, if your program is a web application, its interface could display a "Source" link that leads users to an archive of the code. There are many ways you could offer source, and different solutions will be better for different programs; see section 13 for the specific requirements.
|
|
||||||
|
|
||||||
You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU AGPL, see <http://www.gnu.org/licenses/>.
|
|
||||||
@@ -1,2 +1,219 @@
|
|||||||
# LogHive
|
# 🐝 LogHive — 集中式日志管理系统
|
||||||
|
|
||||||
|
LogHive 是一个集中式的日志管理系统,可以从你的多个 Python 项目中收集日志,并提供搜索、分析和告警能力。
|
||||||
|
|
||||||
|
## 架构概览
|
||||||
|
|
||||||
|
```
|
||||||
|
┌──────────────┐ ┌──────────────┐ ┌──────────────┐
|
||||||
|
│ Python 项目 │ │ Python 项目 │ │ Python 项目 │
|
||||||
|
│ (LogHive SDK)│ │ (LogHive SDK)│ │ (LogHive SDK)│
|
||||||
|
└──────┬───────┘ └──────┬───────┘ └──────┬───────┘
|
||||||
|
│ │ │
|
||||||
|
└───────────────────┼───────────────────┘
|
||||||
|
│ HTTPS / REST API
|
||||||
|
▼
|
||||||
|
┌─────────────────┐
|
||||||
|
│ LogHive Backend │
|
||||||
|
│ (FastAPI) │
|
||||||
|
└────────┬─────────┘
|
||||||
|
│
|
||||||
|
┌────────────┼────────────┐
|
||||||
|
▼ ▼ ▼
|
||||||
|
┌──────────┐ ┌──────────┐ ┌──────────┐
|
||||||
|
│ ES │ │PostgreSQL│ │ Redis │
|
||||||
|
│ 日志存储 │ │ 元数据 │ │ 队列/缓存 │
|
||||||
|
└──────────┘ └──────────┘ └──────────┘
|
||||||
|
│
|
||||||
|
┌──────┴──────┐
|
||||||
|
▼ ▼
|
||||||
|
┌─────────┐ ┌──────────┐
|
||||||
|
│ Celery │ │ Vue 3 │
|
||||||
|
│ 异步任务 │ │ 前端 │
|
||||||
|
└─────────┘ └──────────┘
|
||||||
|
```
|
||||||
|
|
||||||
|
## 功能特性
|
||||||
|
|
||||||
|
- **📥 日志收集** — 通过 REST API 接收 JSON 结构化日志,支持同步/异步客户端
|
||||||
|
- **🔍 全文检索** — 基于 Elasticsearch,支持按项目、级别、关键词、Trace ID、时间范围过滤
|
||||||
|
- **📊 统计分析** — 错误率趋势、级别分布、TOP N 错误、时序图表
|
||||||
|
- **🔔 告警规则** — 可配置的阈值告警,支持飞书/钉钉通知
|
||||||
|
- **🔗 链路追踪** — 通过 Trace ID 关联同一请求的跨模块日志
|
||||||
|
- **🐍 Python SDK** — 一行代码集成到现有项目,支持标准 logging handler
|
||||||
|
- **🔄 前后端分离** — FastAPI 后端 + Vue 3 前端
|
||||||
|
|
||||||
|
## 快速启动
|
||||||
|
|
||||||
|
### 前置条件
|
||||||
|
|
||||||
|
- Docker & Docker Compose
|
||||||
|
- Python 3.10+(本地开发)
|
||||||
|
|
||||||
|
### 使用 Docker Compose(推荐)
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 克隆项目
|
||||||
|
cd LogHive
|
||||||
|
|
||||||
|
# 启动所有服务
|
||||||
|
docker compose up -d
|
||||||
|
|
||||||
|
# 检查状态
|
||||||
|
docker compose ps
|
||||||
|
```
|
||||||
|
|
||||||
|
启动后访问:
|
||||||
|
- **前端**:http://localhost:3000
|
||||||
|
- **API**:http://localhost:8000
|
||||||
|
- **API 健康检查**:http://localhost:8000/api/health
|
||||||
|
- **Kibana**:http://localhost:5601
|
||||||
|
|
||||||
|
### 本地开发
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 1. 启动依赖服务
|
||||||
|
docker compose up -d postgres elasticsearch redis
|
||||||
|
|
||||||
|
# 2. 启动后端
|
||||||
|
cd backend
|
||||||
|
pip install -r requirements.txt
|
||||||
|
uvicorn app.main:app --reload --port 8000
|
||||||
|
|
||||||
|
# 3. 启动前端
|
||||||
|
cd frontend
|
||||||
|
npm install
|
||||||
|
npm run dev
|
||||||
|
```
|
||||||
|
|
||||||
|
## 项目结构
|
||||||
|
|
||||||
|
```
|
||||||
|
LogHive/
|
||||||
|
├── backend/ # FastAPI 后端
|
||||||
|
│ ├── app/
|
||||||
|
│ │ ├── api/ # API 路由
|
||||||
|
│ │ │ ├── logs.py # 日志收录 & 查询
|
||||||
|
│ │ │ ├── projects.py # 项目管理
|
||||||
|
│ │ │ ├── alerts.py # 告警管理
|
||||||
|
│ │ │ └── dashboard.py # 仪表盘
|
||||||
|
│ │ ├── models/ # SQLAlchemy 模型
|
||||||
|
│ │ ├── schemas/ # Pydantic 数据模型
|
||||||
|
│ │ ├── services/ # 业务逻辑层
|
||||||
|
│ │ ├── core/ # 认证 & 工具
|
||||||
|
│ │ ├── config.py # 配置
|
||||||
|
│ │ ├── database.py # 数据库连接
|
||||||
|
│ │ └── main.py # 入口
|
||||||
|
│ ├── celery_worker/ # Celery 异步任务
|
||||||
|
│ ├── requirements.txt
|
||||||
|
│ └── Dockerfile
|
||||||
|
├── client/ # Python SDK
|
||||||
|
│ ├── loghive_client/
|
||||||
|
│ │ ├── client.py # 同步客户端
|
||||||
|
│ │ ├── async_client.py # 异步客户端
|
||||||
|
│ │ └── handler.py # logging 集成
|
||||||
|
│ ├── setup.py
|
||||||
|
│ └── README.md
|
||||||
|
├── frontend/ # Vue 3 前端
|
||||||
|
│ ├── src/
|
||||||
|
│ │ ├── api/ # API 调用层
|
||||||
|
│ │ ├── router/ # 路由
|
||||||
|
│ │ └── views/ # 页面
|
||||||
|
│ ├── package.json
|
||||||
|
│ ├── vite.config.js
|
||||||
|
│ └── Dockerfile
|
||||||
|
├── docker-compose.yml
|
||||||
|
├── .env.example
|
||||||
|
└── README.md
|
||||||
|
```
|
||||||
|
|
||||||
|
## 使用指南
|
||||||
|
|
||||||
|
### 1. 创建项目 & 获取 API Key
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 注册项目
|
||||||
|
curl -X POST http://localhost:8000/api/projects \
|
||||||
|
-H "Content-Type: application/json" \
|
||||||
|
-d '{"name": "my-app", "description": "我的 Python 应用"}'
|
||||||
|
|
||||||
|
# 获取 API Key(在响应的 api_key 字段)
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2. 在你的项目中使用 SDK
|
||||||
|
|
||||||
|
```python
|
||||||
|
# 安装 SDK
|
||||||
|
# pip install loghive-client
|
||||||
|
|
||||||
|
from loghive_client import LogHiveLogger
|
||||||
|
|
||||||
|
logger = LogHiveLogger(
|
||||||
|
project="my-app",
|
||||||
|
api_key="your-api-key",
|
||||||
|
endpoint="http://localhost:8000",
|
||||||
|
)
|
||||||
|
|
||||||
|
logger.info("服务启动成功", extra={"port": 8080})
|
||||||
|
logger.error("数据库连接超时", exc_info=True)
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3. 标准 logging 集成(零代码改动)
|
||||||
|
|
||||||
|
```python
|
||||||
|
import logging
|
||||||
|
from loghive_client import LogHiveHandler
|
||||||
|
|
||||||
|
handler = LogHiveHandler("my-app", "api-key", "http://localhost:8000")
|
||||||
|
logging.getLogger().addHandler(handler)
|
||||||
|
|
||||||
|
# 所有现有的日志调用自动转发到 LogHive
|
||||||
|
logging.info("这条日志也会发送到 LogHive")
|
||||||
|
```
|
||||||
|
|
||||||
|
### 4. 直接通过 API 推送日志
|
||||||
|
|
||||||
|
```bash
|
||||||
|
curl -X POST http://localhost:8000/api/logs/ingest \
|
||||||
|
-H "Authorization: Bearer your-api-key" \
|
||||||
|
-H "Content-Type: application/json" \
|
||||||
|
-d '{
|
||||||
|
"project": "my-app",
|
||||||
|
"entries": [
|
||||||
|
{
|
||||||
|
"level": "info",
|
||||||
|
"message": "Hello from my app!",
|
||||||
|
"logger": "myapp.server",
|
||||||
|
"extra": {"user_id": 42}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}'
|
||||||
|
```
|
||||||
|
|
||||||
|
## 技术栈
|
||||||
|
|
||||||
|
| 层级 | 技术 |
|
||||||
|
|------|------|
|
||||||
|
| 后端框架 | FastAPI (Python 3.12) |
|
||||||
|
| 日志存储 | Elasticsearch 8.x |
|
||||||
|
| 元数据存储 | PostgreSQL 16 / TimescaleDB |
|
||||||
|
| 消息队列 | Redis 7 |
|
||||||
|
| 异步任务 | Celery |
|
||||||
|
| 前端 | Vue 3 + Element Plus + ECharts |
|
||||||
|
| 部署 | Docker Compose |
|
||||||
|
|
||||||
|
## 配置
|
||||||
|
|
||||||
|
通过环境变量配置,详见 `.env.example`。主要配置项:
|
||||||
|
|
||||||
|
| 变量 | 默认值 | 说明 |
|
||||||
|
|------|--------|------|
|
||||||
|
| `SECRET_KEY` | — | JWT 密钥(生产必改) |
|
||||||
|
| `ES_HOST` | localhost | Elasticsearch 地址 |
|
||||||
|
| `DATABASE_URL` | — | PostgreSQL 连接串 |
|
||||||
|
| `LOG_RETENTION_DAYS` | 30 | 日志保留天数 |
|
||||||
|
| `FEISHU_WEBHOOK_URL` | — | 飞书机器人 Webhook |
|
||||||
|
|
||||||
|
## License
|
||||||
|
|
||||||
|
MIT
|
||||||
|
|||||||
@@ -0,0 +1,21 @@
|
|||||||
|
FROM python:3.12-slim
|
||||||
|
|
||||||
|
WORKDIR /app
|
||||||
|
|
||||||
|
# Install system dependencies
|
||||||
|
RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||||
|
gcc \
|
||||||
|
&& rm -rf /var/lib/apt/lists/*
|
||||||
|
|
||||||
|
# Install Python dependencies
|
||||||
|
COPY requirements.txt .
|
||||||
|
RUN pip install --no-cache-dir -r requirements.txt
|
||||||
|
|
||||||
|
# Copy application
|
||||||
|
COPY . .
|
||||||
|
|
||||||
|
# Expose port
|
||||||
|
EXPOSE 8000
|
||||||
|
|
||||||
|
# Run with uvicorn
|
||||||
|
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]
|
||||||
@@ -0,0 +1,180 @@
|
|||||||
|
"""Alert management API routes."""
|
||||||
|
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
from typing import List, Optional
|
||||||
|
|
||||||
|
from fastapi import APIRouter, Depends, HTTPException, Query, status
|
||||||
|
from sqlalchemy import select, func
|
||||||
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
||||||
|
from app.database import get_db
|
||||||
|
from app.models.alert import AlertRule, AlertHistory, AlertLevel, AlertOperator
|
||||||
|
from app.schemas.alert import (
|
||||||
|
AlertRuleCreate,
|
||||||
|
AlertRuleUpdate,
|
||||||
|
AlertRuleResponse,
|
||||||
|
AlertHistoryResponse,
|
||||||
|
)
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/api/alerts", tags=["alerts"])
|
||||||
|
|
||||||
|
|
||||||
|
# ── Rule CRUD ──────────────────────────────────────────────────
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/rules", response_model=AlertRuleResponse, status_code=201)
|
||||||
|
async def create_alert_rule(
|
||||||
|
data: AlertRuleCreate,
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
):
|
||||||
|
"""Create a new alert rule."""
|
||||||
|
rule = AlertRule(
|
||||||
|
project_id=data.project_id,
|
||||||
|
name=data.name,
|
||||||
|
level=data.level,
|
||||||
|
field=data.field,
|
||||||
|
operator=data.operator,
|
||||||
|
threshold=data.threshold,
|
||||||
|
window_minutes=data.window_minutes,
|
||||||
|
notify_channels=",".join(data.notify_channels) if data.notify_channels else "",
|
||||||
|
)
|
||||||
|
db.add(rule)
|
||||||
|
await db.flush()
|
||||||
|
await db.refresh(rule)
|
||||||
|
return _rule_to_response(rule)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/rules", response_model=List[AlertRuleResponse])
|
||||||
|
async def list_alert_rules(
|
||||||
|
project_id: Optional[str] = Query(None),
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
):
|
||||||
|
"""List alert rules, optionally filtered by project."""
|
||||||
|
stmt = select(AlertRule)
|
||||||
|
if project_id:
|
||||||
|
stmt = stmt.where(AlertRule.project_id == project_id)
|
||||||
|
stmt = stmt.order_by(AlertRule.created_at.desc())
|
||||||
|
result = await db.execute(stmt)
|
||||||
|
return [_rule_to_response(r) for r in result.scalars().all()]
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/rules/{rule_id}", response_model=AlertRuleResponse)
|
||||||
|
async def get_alert_rule(rule_id: str, db: AsyncSession = Depends(get_db)):
|
||||||
|
"""Get a single alert rule."""
|
||||||
|
result = await db.execute(select(AlertRule).where(AlertRule.id == rule_id))
|
||||||
|
rule = result.scalar_one_or_none()
|
||||||
|
if not rule:
|
||||||
|
raise HTTPException(status_code=404, detail="Alert rule not found")
|
||||||
|
return _rule_to_response(rule)
|
||||||
|
|
||||||
|
|
||||||
|
@router.patch("/rules/{rule_id}", response_model=AlertRuleResponse)
|
||||||
|
async def update_alert_rule(
|
||||||
|
rule_id: str,
|
||||||
|
data: AlertRuleUpdate,
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
):
|
||||||
|
"""Update an alert rule."""
|
||||||
|
result = await db.execute(select(AlertRule).where(AlertRule.id == rule_id))
|
||||||
|
rule = result.scalar_one_or_none()
|
||||||
|
if not rule:
|
||||||
|
raise HTTPException(status_code=404, detail="Alert rule not found")
|
||||||
|
|
||||||
|
if data.name is not None:
|
||||||
|
rule.name = data.name
|
||||||
|
if data.level is not None:
|
||||||
|
rule.level = data.level
|
||||||
|
if data.field is not None:
|
||||||
|
rule.field = data.field
|
||||||
|
if data.operator is not None:
|
||||||
|
rule.operator = data.operator
|
||||||
|
if data.threshold is not None:
|
||||||
|
rule.threshold = data.threshold
|
||||||
|
if data.window_minutes is not None:
|
||||||
|
rule.window_minutes = data.window_minutes
|
||||||
|
if data.is_enabled is not None:
|
||||||
|
rule.is_enabled = data.is_enabled
|
||||||
|
if data.notify_channels is not None:
|
||||||
|
rule.notify_channels = ",".join(data.notify_channels)
|
||||||
|
|
||||||
|
await db.flush()
|
||||||
|
await db.refresh(rule)
|
||||||
|
return _rule_to_response(rule)
|
||||||
|
|
||||||
|
|
||||||
|
@router.delete("/rules/{rule_id}", status_code=204)
|
||||||
|
async def delete_alert_rule(rule_id: str, db: AsyncSession = Depends(get_db)):
|
||||||
|
"""Delete an alert rule."""
|
||||||
|
result = await db.execute(select(AlertRule).where(AlertRule.id == rule_id))
|
||||||
|
rule = result.scalar_one_or_none()
|
||||||
|
if not rule:
|
||||||
|
raise HTTPException(status_code=404, detail="Alert rule not found")
|
||||||
|
await db.delete(rule)
|
||||||
|
|
||||||
|
|
||||||
|
# ── Alert History ──────────────────────────────────────────────
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/history", response_model=List[AlertHistoryResponse])
|
||||||
|
async def list_alert_history(
|
||||||
|
project_id: Optional[str] = Query(None),
|
||||||
|
rule_id: Optional[str] = Query(None),
|
||||||
|
limit: int = Query(100, ge=1, le=1000),
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
):
|
||||||
|
"""List alert trigger history."""
|
||||||
|
stmt = select(AlertHistory).order_by(AlertHistory.triggered_at.desc()).limit(limit)
|
||||||
|
if project_id:
|
||||||
|
stmt = stmt.where(AlertHistory.project_id == project_id)
|
||||||
|
if rule_id:
|
||||||
|
stmt = stmt.where(AlertHistory.rule_id == rule_id)
|
||||||
|
result = await db.execute(stmt)
|
||||||
|
return [_history_to_response(h) for h in result.scalars().all()]
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/history/{history_id}/acknowledge", response_model=AlertHistoryResponse)
|
||||||
|
async def acknowledge_alert(
|
||||||
|
history_id: str,
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
):
|
||||||
|
"""Mark an alert as acknowledged."""
|
||||||
|
result = await db.execute(select(AlertHistory).where(AlertHistory.id == history_id))
|
||||||
|
history = result.scalar_one_or_none()
|
||||||
|
if not history:
|
||||||
|
raise HTTPException(status_code=404, detail="Alert history not found")
|
||||||
|
history.is_acknowledged = True
|
||||||
|
await db.flush()
|
||||||
|
await db.refresh(history)
|
||||||
|
return _history_to_response(history)
|
||||||
|
|
||||||
|
|
||||||
|
# ── Helpers ────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
|
||||||
|
def _rule_to_response(rule: AlertRule) -> AlertRuleResponse:
|
||||||
|
return AlertRuleResponse(
|
||||||
|
id=rule.id,
|
||||||
|
project_id=rule.project_id,
|
||||||
|
name=rule.name,
|
||||||
|
level=rule.level.value if hasattr(rule.level, "value") else rule.level,
|
||||||
|
field=rule.field,
|
||||||
|
operator=rule.operator.value if hasattr(rule.operator, "value") else rule.operator,
|
||||||
|
threshold=rule.threshold,
|
||||||
|
window_minutes=rule.window_minutes,
|
||||||
|
is_enabled=rule.is_enabled,
|
||||||
|
notify_channels=rule.notify_channels.split(",") if rule.notify_channels else [],
|
||||||
|
created_at=rule.created_at,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _history_to_response(history: AlertHistory) -> AlertHistoryResponse:
|
||||||
|
return AlertHistoryResponse(
|
||||||
|
id=history.id,
|
||||||
|
rule_id=history.rule_id,
|
||||||
|
project_id=history.project_id,
|
||||||
|
level=history.level.value if hasattr(history.level, "value") else history.level,
|
||||||
|
message=history.message,
|
||||||
|
triggered_value=history.triggered_value,
|
||||||
|
is_acknowledged=history.is_acknowledged,
|
||||||
|
triggered_at=history.triggered_at,
|
||||||
|
)
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
"""Dashboard API routes."""
|
||||||
|
|
||||||
|
from typing import Optional
|
||||||
|
|
||||||
|
from fastapi import APIRouter, Depends, Query
|
||||||
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
||||||
|
from app.database import get_db
|
||||||
|
from app.services.analytics_service import AnalyticsService
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/api/dashboard", tags=["dashboard"])
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/stats")
|
||||||
|
async def dashboard_stats(
|
||||||
|
project: Optional[str] = Query(None),
|
||||||
|
hours: int = Query(24, ge=1, le=720),
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
):
|
||||||
|
"""Get overview statistics for the dashboard."""
|
||||||
|
service = AnalyticsService(db)
|
||||||
|
return await service.get_dashboard_stats(project=project, hours=hours)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/timeseries")
|
||||||
|
async def dashboard_timeseries(
|
||||||
|
project: Optional[str] = Query(None),
|
||||||
|
hours: int = Query(24, ge=1, le=720),
|
||||||
|
interval: str = Query("5m", max_length=16),
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
):
|
||||||
|
"""Get time-series data for chart rendering."""
|
||||||
|
service = AnalyticsService(db)
|
||||||
|
return await service.get_time_series(project=project, hours=hours, interval=interval)
|
||||||
@@ -0,0 +1,253 @@
|
|||||||
|
"""Log ingestion and query API routes."""
|
||||||
|
|
||||||
|
import logging
|
||||||
|
from datetime import datetime, timezone, timedelta
|
||||||
|
from typing import Optional
|
||||||
|
|
||||||
|
from fastapi import APIRouter, Depends, Header, HTTPException, Query, status
|
||||||
|
from sqlalchemy import func, select, delete, and_
|
||||||
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
||||||
|
from app.config import settings, to_display_time, from_query_time
|
||||||
|
from app.database import get_db
|
||||||
|
from app.schemas.log import (
|
||||||
|
LogBatchRequest,
|
||||||
|
LogEntry as LogEntrySchema,
|
||||||
|
LogQueryParams,
|
||||||
|
LogSearchResult,
|
||||||
|
LogStatsResult,
|
||||||
|
)
|
||||||
|
from app.models.project import Project
|
||||||
|
from app.models.log import LogEntry
|
||||||
|
from app.core.auth import verify_api_key, resolve_project_by_api_key
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
router = APIRouter(prefix="/api/logs", tags=["logs"])
|
||||||
|
|
||||||
|
|
||||||
|
# ── Ingestion ─────────────────────────────────────────────────
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/ingest", status_code=201)
|
||||||
|
async def ingest_logs(
|
||||||
|
batch: LogBatchRequest,
|
||||||
|
authorization: Optional[str] = Header(None),
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
):
|
||||||
|
"""Receive a batch of log entries from a project."""
|
||||||
|
api_key = await verify_api_key(authorization)
|
||||||
|
project = await resolve_project_by_api_key(db, api_key)
|
||||||
|
|
||||||
|
now = datetime.now(timezone.utc)
|
||||||
|
rows = []
|
||||||
|
for entry in batch.entries:
|
||||||
|
row = LogEntry(
|
||||||
|
project_id=project.id,
|
||||||
|
project_name=project.name,
|
||||||
|
timestamp=entry.timestamp or now,
|
||||||
|
level=entry.level,
|
||||||
|
logger=entry.logger,
|
||||||
|
message=entry.message,
|
||||||
|
module=entry.module,
|
||||||
|
function=entry.function,
|
||||||
|
line_no=entry.line_no,
|
||||||
|
trace_id=entry.trace_id,
|
||||||
|
exception=entry.exception,
|
||||||
|
extra=entry.extra,
|
||||||
|
)
|
||||||
|
rows.append(row)
|
||||||
|
|
||||||
|
db.add_all(rows)
|
||||||
|
await db.flush()
|
||||||
|
return {"accepted": len(rows), "project": project.name}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/ingest/single", status_code=201)
|
||||||
|
async def ingest_single_log(
|
||||||
|
entry: LogEntrySchema,
|
||||||
|
project_name: str = Query(..., description="Project name"),
|
||||||
|
authorization: Optional[str] = Header(None),
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
):
|
||||||
|
"""Receive a single log entry (useful for testing / simple clients)."""
|
||||||
|
api_key = await verify_api_key(authorization)
|
||||||
|
project = await resolve_project_by_api_key(db, api_key)
|
||||||
|
|
||||||
|
now = datetime.now(timezone.utc)
|
||||||
|
row = LogEntry(
|
||||||
|
project_id=project.id,
|
||||||
|
project_name=project.name,
|
||||||
|
timestamp=entry.timestamp or now,
|
||||||
|
level=entry.level,
|
||||||
|
logger=entry.logger,
|
||||||
|
message=entry.message,
|
||||||
|
module=entry.module,
|
||||||
|
function=entry.function,
|
||||||
|
line_no=entry.line_no,
|
||||||
|
trace_id=entry.trace_id,
|
||||||
|
exception=entry.exception,
|
||||||
|
extra=entry.extra,
|
||||||
|
)
|
||||||
|
db.add(row)
|
||||||
|
await db.flush()
|
||||||
|
return {"accepted": 1, "project": project.name}
|
||||||
|
|
||||||
|
|
||||||
|
# ── Query ──────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/search", response_model=LogSearchResult)
|
||||||
|
async def search_logs(
|
||||||
|
project: Optional[str] = Query(None, description="Filter by project name"),
|
||||||
|
level: Optional[str] = Query(None, pattern="^(debug|info|warning|error|critical)$"),
|
||||||
|
query: Optional[str] = Query(None, max_length=1024),
|
||||||
|
trace_id: Optional[str] = Query(None, max_length=64),
|
||||||
|
start_time: Optional[datetime] = None,
|
||||||
|
end_time: Optional[datetime] = None,
|
||||||
|
page: int = Query(1, ge=1),
|
||||||
|
page_size: int = Query(50, ge=1, le=1000),
|
||||||
|
sort_by: str = Query("timestamp", max_length=32),
|
||||||
|
sort_order: str = Query("desc", pattern="^(asc|desc)$"),
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
):
|
||||||
|
"""Search logs with full-text query and filters."""
|
||||||
|
conditions = []
|
||||||
|
|
||||||
|
if project:
|
||||||
|
conditions.append(LogEntry.project_name == project)
|
||||||
|
if level:
|
||||||
|
conditions.append(LogEntry.level == level)
|
||||||
|
if trace_id:
|
||||||
|
conditions.append(LogEntry.trace_id == trace_id)
|
||||||
|
if start_time:
|
||||||
|
conditions.append(LogEntry.timestamp >= from_query_time(start_time))
|
||||||
|
if end_time:
|
||||||
|
conditions.append(LogEntry.timestamp <= from_query_time(end_time))
|
||||||
|
if query:
|
||||||
|
conditions.append(
|
||||||
|
func.to_tsvector(
|
||||||
|
"english",
|
||||||
|
func.concat(
|
||||||
|
LogEntry.message, " ",
|
||||||
|
func.coalesce(LogEntry.logger, ""), " ",
|
||||||
|
func.coalesce(LogEntry.module, ""),
|
||||||
|
),
|
||||||
|
).bool_op("@@")(
|
||||||
|
func.plainto_tsquery("english", query)
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
# Sort
|
||||||
|
sort_col = getattr(LogEntry, sort_by, LogEntry.timestamp)
|
||||||
|
order = sort_col.desc() if sort_order == "desc" else sort_col.asc()
|
||||||
|
|
||||||
|
# Count total
|
||||||
|
count_stmt = select(func.count(LogEntry.id))
|
||||||
|
if conditions:
|
||||||
|
count_stmt = count_stmt.where(and_(*conditions))
|
||||||
|
total = (await db.execute(count_stmt)).scalar() or 0
|
||||||
|
|
||||||
|
# Fetch page
|
||||||
|
stmt = select(LogEntry).order_by(order).offset((page - 1) * page_size).limit(page_size)
|
||||||
|
if conditions:
|
||||||
|
stmt = stmt.where(and_(*conditions))
|
||||||
|
rows = (await db.execute(stmt)).scalars().all()
|
||||||
|
|
||||||
|
hits = []
|
||||||
|
for r in rows:
|
||||||
|
hits.append({
|
||||||
|
"project_id": r.project_id,
|
||||||
|
"project_name": r.project_name,
|
||||||
|
"timestamp": to_display_time(r.timestamp),
|
||||||
|
"level": r.level,
|
||||||
|
"logger": r.logger,
|
||||||
|
"message": r.message,
|
||||||
|
"module": r.module,
|
||||||
|
"function": r.function,
|
||||||
|
"line_no": r.line_no,
|
||||||
|
"trace_id": r.trace_id,
|
||||||
|
"exception": r.exception,
|
||||||
|
"extra": r.extra,
|
||||||
|
})
|
||||||
|
|
||||||
|
return LogSearchResult(total=total, page=page, page_size=page_size, hits=hits)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/stats", response_model=LogStatsResult)
|
||||||
|
async def log_stats(
|
||||||
|
project: Optional[str] = Query(None),
|
||||||
|
start_time: Optional[datetime] = None,
|
||||||
|
end_time: Optional[datetime] = None,
|
||||||
|
interval: str = Query("5m", max_length=16),
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
):
|
||||||
|
"""Get aggregated log statistics over a time range."""
|
||||||
|
conditions = []
|
||||||
|
if project:
|
||||||
|
conditions.append(LogEntry.project_name == project)
|
||||||
|
if start_time:
|
||||||
|
conditions.append(LogEntry.timestamp >= from_query_time(start_time))
|
||||||
|
if end_time:
|
||||||
|
conditions.append(LogEntry.timestamp <= from_query_time(end_time))
|
||||||
|
|
||||||
|
def apply(stmt):
|
||||||
|
if conditions:
|
||||||
|
stmt = stmt.where(and_(*conditions))
|
||||||
|
return stmt
|
||||||
|
|
||||||
|
# Time buckets (hourly)
|
||||||
|
stmt = apply(
|
||||||
|
select(
|
||||||
|
func.date_trunc("hour", LogEntry.timestamp).label("bucket"),
|
||||||
|
func.count(LogEntry.id).label("cnt"),
|
||||||
|
).group_by("bucket").order_by("bucket")
|
||||||
|
)
|
||||||
|
time_rows = (await db.execute(stmt)).all()
|
||||||
|
time_buckets = [
|
||||||
|
{"key": to_display_time(r.bucket), "doc_count": r.cnt}
|
||||||
|
for r in time_rows
|
||||||
|
]
|
||||||
|
|
||||||
|
# Level counts
|
||||||
|
stmt = apply(
|
||||||
|
select(LogEntry.level, func.count(LogEntry.id).label("cnt"))
|
||||||
|
.group_by(LogEntry.level)
|
||||||
|
)
|
||||||
|
level_rows = (await db.execute(stmt)).all()
|
||||||
|
level_counts = {r.level: r.cnt for r in level_rows}
|
||||||
|
|
||||||
|
# Top loggers
|
||||||
|
stmt = apply(
|
||||||
|
select(LogEntry.logger, func.count(LogEntry.id).label("cnt"))
|
||||||
|
.group_by(LogEntry.logger)
|
||||||
|
.order_by(func.count(LogEntry.id).desc())
|
||||||
|
.limit(20)
|
||||||
|
)
|
||||||
|
logger_rows = (await db.execute(stmt)).all()
|
||||||
|
top_loggers = [{"logger": r.logger, "count": r.cnt} for r in logger_rows]
|
||||||
|
|
||||||
|
# Total count
|
||||||
|
total = (await db.execute(apply(select(func.count(LogEntry.id))))).scalar() or 0
|
||||||
|
|
||||||
|
return LogStatsResult(
|
||||||
|
project=project,
|
||||||
|
time_buckets=time_buckets,
|
||||||
|
level_counts=level_counts,
|
||||||
|
top_loggers=top_loggers,
|
||||||
|
total=total,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@router.delete("/cleanup")
|
||||||
|
async def cleanup_old_logs(
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
):
|
||||||
|
"""Delete log entries older than the retention period."""
|
||||||
|
cutoff = datetime.now(timezone.utc) - timedelta(days=settings.LOG_RETENTION_DAYS)
|
||||||
|
|
||||||
|
result = await db.execute(
|
||||||
|
delete(LogEntry).where(LogEntry.timestamp < cutoff)
|
||||||
|
)
|
||||||
|
await db.flush()
|
||||||
|
|
||||||
|
return {"deleted_count": result.rowcount}
|
||||||
@@ -0,0 +1,123 @@
|
|||||||
|
"""Project management API routes."""
|
||||||
|
|
||||||
|
import uuid
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
from typing import List
|
||||||
|
|
||||||
|
from fastapi import APIRouter, Depends, HTTPException, status
|
||||||
|
from sqlalchemy import select
|
||||||
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
||||||
|
from app.database import get_db
|
||||||
|
from app.models.project import Project
|
||||||
|
from app.schemas.project import ProjectCreate, ProjectUpdate, ProjectResponse, ProjectWithToken
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/api/projects", tags=["projects"])
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("", response_model=ProjectWithToken, status_code=201)
|
||||||
|
async def create_project(
|
||||||
|
data: ProjectCreate,
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
):
|
||||||
|
"""Register a new project for log collection."""
|
||||||
|
existing = await db.execute(select(Project).where(Project.name == data.name))
|
||||||
|
if existing.scalar_one_or_none():
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_409_CONFLICT,
|
||||||
|
detail=f"Project '{data.name}' already exists",
|
||||||
|
)
|
||||||
|
|
||||||
|
project = Project(
|
||||||
|
name=data.name,
|
||||||
|
description=data.description,
|
||||||
|
api_key=uuid.uuid4().hex,
|
||||||
|
)
|
||||||
|
db.add(project)
|
||||||
|
await db.flush()
|
||||||
|
await db.refresh(project)
|
||||||
|
return project
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("", response_model=List[ProjectResponse])
|
||||||
|
async def list_projects(
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
):
|
||||||
|
"""List all registered projects."""
|
||||||
|
result = await db.execute(select(Project).order_by(Project.created_at.desc()))
|
||||||
|
return result.scalars().all()
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/{project_id}", response_model=ProjectResponse)
|
||||||
|
async def get_project(
|
||||||
|
project_id: str,
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
):
|
||||||
|
"""Get a single project by ID."""
|
||||||
|
result = await db.execute(select(Project).where(Project.id == project_id))
|
||||||
|
project = result.scalar_one_or_none()
|
||||||
|
if not project:
|
||||||
|
raise HTTPException(status_code=404, detail="Project not found")
|
||||||
|
return project
|
||||||
|
|
||||||
|
|
||||||
|
@router.patch("/{project_id}", response_model=ProjectResponse)
|
||||||
|
async def update_project(
|
||||||
|
project_id: str,
|
||||||
|
data: ProjectUpdate,
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
):
|
||||||
|
"""Update a project."""
|
||||||
|
result = await db.execute(select(Project).where(Project.id == project_id))
|
||||||
|
project = result.scalar_one_or_none()
|
||||||
|
if not project:
|
||||||
|
raise HTTPException(status_code=404, detail="Project not found")
|
||||||
|
|
||||||
|
if data.name is not None:
|
||||||
|
# Check uniqueness
|
||||||
|
existing = await db.execute(
|
||||||
|
select(Project).where(Project.name == data.name, Project.id != project_id)
|
||||||
|
)
|
||||||
|
if existing.scalar_one_or_none():
|
||||||
|
raise HTTPException(status_code=409, detail="Name already taken")
|
||||||
|
project.name = data.name
|
||||||
|
if data.description is not None:
|
||||||
|
project.description = data.description
|
||||||
|
if data.is_active is not None:
|
||||||
|
project.is_active = data.is_active
|
||||||
|
|
||||||
|
project.updated_at = datetime.now(timezone.utc)
|
||||||
|
await db.flush()
|
||||||
|
await db.refresh(project)
|
||||||
|
return project
|
||||||
|
|
||||||
|
|
||||||
|
@router.delete("/{project_id}", status_code=204)
|
||||||
|
async def delete_project(
|
||||||
|
project_id: str,
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
):
|
||||||
|
"""Delete a project."""
|
||||||
|
result = await db.execute(select(Project).where(Project.id == project_id))
|
||||||
|
project = result.scalar_one_or_none()
|
||||||
|
if not project:
|
||||||
|
raise HTTPException(status_code=404, detail="Project not found")
|
||||||
|
await db.delete(project)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/{project_id}/rotate-key", response_model=ProjectWithToken)
|
||||||
|
async def rotate_api_key(
|
||||||
|
project_id: str,
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
):
|
||||||
|
"""Rotate a project's API key."""
|
||||||
|
result = await db.execute(select(Project).where(Project.id == project_id))
|
||||||
|
project = result.scalar_one_or_none()
|
||||||
|
if not project:
|
||||||
|
raise HTTPException(status_code=404, detail="Project not found")
|
||||||
|
|
||||||
|
project.api_key = uuid.uuid4().hex
|
||||||
|
project.updated_at = datetime.now(timezone.utc)
|
||||||
|
await db.flush()
|
||||||
|
await db.refresh(project)
|
||||||
|
return project
|
||||||
@@ -0,0 +1,79 @@
|
|||||||
|
"""LogHive configuration."""
|
||||||
|
|
||||||
|
import os
|
||||||
|
from datetime import datetime, timezone, timedelta
|
||||||
|
from typing import Optional
|
||||||
|
|
||||||
|
# Beijing timezone offset
|
||||||
|
_BEIJING_TZ = timezone(timedelta(hours=8))
|
||||||
|
|
||||||
|
|
||||||
|
def to_display_time(dt: datetime) -> str:
|
||||||
|
"""Convert a UTC datetime to Beijing time for display.
|
||||||
|
Returns ISO format without timezone suffix (e.g. '2026-05-08T14:30:00')."""
|
||||||
|
if dt is None:
|
||||||
|
return None
|
||||||
|
if dt.tzinfo is None:
|
||||||
|
dt = dt.replace(tzinfo=timezone.utc)
|
||||||
|
local = dt.astimezone(_BEIJING_TZ)
|
||||||
|
return local.strftime("%Y-%m-%dT%H:%M:%S")
|
||||||
|
|
||||||
|
|
||||||
|
def from_query_time(dt: Optional[datetime]) -> Optional[datetime]:
|
||||||
|
"""Interpret a naive datetime query param as Beijing time, return UTC datetime."""
|
||||||
|
if dt is None:
|
||||||
|
return None
|
||||||
|
if dt.tzinfo is None:
|
||||||
|
dt = dt.replace(tzinfo=_BEIJING_TZ)
|
||||||
|
return dt.astimezone(timezone.utc)
|
||||||
|
|
||||||
|
|
||||||
|
class Settings:
|
||||||
|
"""Application settings loaded from environment variables."""
|
||||||
|
|
||||||
|
# Service name
|
||||||
|
SERVICE_NAME: str = "LogHive"
|
||||||
|
|
||||||
|
# API
|
||||||
|
API_HOST: str = os.getenv("API_HOST", "0.0.0.0")
|
||||||
|
API_PORT: int = int(os.getenv("API_PORT", "8000"))
|
||||||
|
DEBUG: bool = os.getenv("DEBUG", "false").lower() == "true"
|
||||||
|
CORS_ORIGINS: list[str] = os.getenv("CORS_ORIGINS", "*").split(",")
|
||||||
|
|
||||||
|
# Security
|
||||||
|
SECRET_KEY: str = os.getenv("SECRET_KEY", "change-me-in-production")
|
||||||
|
TOKEN_EXPIRE_HOURS: int = int(os.getenv("TOKEN_EXPIRE_HOURS", "720"))
|
||||||
|
|
||||||
|
# PostgreSQL
|
||||||
|
DATABASE_URL: str = os.getenv(
|
||||||
|
"DATABASE_URL",
|
||||||
|
"postgresql+asyncpg://LogHive:LogHive@localhost:5432/LogHive",
|
||||||
|
)
|
||||||
|
|
||||||
|
# Redis
|
||||||
|
REDIS_URL: str = os.getenv("REDIS_URL", "redis://localhost:6379/0")
|
||||||
|
|
||||||
|
# Celery
|
||||||
|
CELERY_BROKER_URL: str = os.getenv("CELERY_BROKER_URL", "redis://localhost:6379/1")
|
||||||
|
CELERY_RESULT_BACKEND: str = os.getenv(
|
||||||
|
"CELERY_RESULT_BACKEND", "redis://localhost:6379/2"
|
||||||
|
)
|
||||||
|
|
||||||
|
# Log retention (days)
|
||||||
|
LOG_RETENTION_DAYS: int = int(os.getenv("LOG_RETENTION_DAYS", "30"))
|
||||||
|
LOG_COLD_STORAGE_DAYS: int = int(os.getenv("LOG_COLD_STORAGE_DAYS", "7"))
|
||||||
|
|
||||||
|
# Rate limit
|
||||||
|
RATE_LIMIT_PER_SECOND: int = int(os.getenv("RATE_LIMIT_PER_SECOND", "1000"))
|
||||||
|
|
||||||
|
# Alert
|
||||||
|
ALERT_CHECK_INTERVAL_SECONDS: int = int(
|
||||||
|
os.getenv("ALERT_CHECK_INTERVAL_SECONDS", "60")
|
||||||
|
)
|
||||||
|
|
||||||
|
# Notification
|
||||||
|
FEISHU_WEBHOOK_URL: Optional[str] = os.getenv("FEISHU_WEBHOOK_URL", None)
|
||||||
|
DINGTALK_WEBHOOK_URL: Optional[str] = os.getenv("DINGTALK_WEBHOOK_URL", None)
|
||||||
|
|
||||||
|
|
||||||
|
settings = Settings()
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
from .auth import verify_api_key, resolve_project_by_api_key
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
"""Auth utilities — API key verification."""
|
||||||
|
|
||||||
|
import hmac
|
||||||
|
from typing import Optional
|
||||||
|
|
||||||
|
from fastapi import Header, HTTPException, status
|
||||||
|
from sqlalchemy import select
|
||||||
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
||||||
|
from app.database import get_db
|
||||||
|
from app.models.project import Project
|
||||||
|
|
||||||
|
|
||||||
|
async def verify_api_key(
|
||||||
|
authorization: Optional[str] = Header(None),
|
||||||
|
) -> str:
|
||||||
|
"""Extract and verify the API key from the Authorization header.
|
||||||
|
|
||||||
|
Returns the project_id on success.
|
||||||
|
"""
|
||||||
|
if not authorization:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||||
|
detail="Missing Authorization header",
|
||||||
|
)
|
||||||
|
|
||||||
|
scheme, _, key = authorization.partition(" ")
|
||||||
|
if scheme.lower() != "bearer" or not key.strip():
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||||
|
detail="Invalid Authorization format. Use: Bearer <api_key>",
|
||||||
|
)
|
||||||
|
|
||||||
|
return key.strip()
|
||||||
|
|
||||||
|
|
||||||
|
async def resolve_project_by_api_key(
|
||||||
|
db: AsyncSession, api_key: str
|
||||||
|
) -> Project:
|
||||||
|
"""Look up a project by its API key."""
|
||||||
|
result = await db.execute(
|
||||||
|
select(Project).where(Project.api_key == api_key, Project.is_active == True)
|
||||||
|
)
|
||||||
|
project = result.scalar_one_or_none()
|
||||||
|
if not project:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||||
|
detail="Invalid or inactive API key",
|
||||||
|
)
|
||||||
|
return project
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
"""Core auth logic."""
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
"""Database connections and session management."""
|
||||||
|
|
||||||
|
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine, async_sessionmaker
|
||||||
|
from sqlalchemy.orm import DeclarativeBase
|
||||||
|
|
||||||
|
from app.config import settings
|
||||||
|
|
||||||
|
# ── PostgreSQL ────────────────────────────────────────────────────
|
||||||
|
engine = create_async_engine(settings.DATABASE_URL, echo=settings.DEBUG)
|
||||||
|
async_session_factory = async_sessionmaker(engine, expire_on_commit=False)
|
||||||
|
|
||||||
|
|
||||||
|
class Base(DeclarativeBase):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
async def get_db() -> AsyncSession:
|
||||||
|
"""Yield a DB session per request."""
|
||||||
|
async with async_session_factory() as session:
|
||||||
|
try:
|
||||||
|
yield session
|
||||||
|
await session.commit()
|
||||||
|
except Exception:
|
||||||
|
await session.rollback()
|
||||||
|
raise
|
||||||
|
finally:
|
||||||
|
await session.close()
|
||||||
|
|
||||||
|
|
||||||
|
async def init_db() -> None:
|
||||||
|
"""Create all tables (use Alembic in production)."""
|
||||||
|
async with engine.begin() as conn:
|
||||||
|
await conn.run_sync(Base.metadata.create_all)
|
||||||
|
|
||||||
|
|
||||||
|
async def close_db() -> None:
|
||||||
|
await engine.dispose()
|
||||||
@@ -0,0 +1,65 @@
|
|||||||
|
"""LogHive — Centralized Log Management System.
|
||||||
|
|
||||||
|
FastAPI application that receives, stores, searches and analyzes logs
|
||||||
|
from multiple Python projects.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import logging
|
||||||
|
from contextlib import asynccontextmanager
|
||||||
|
|
||||||
|
from fastapi import FastAPI
|
||||||
|
from fastapi.middleware.cors import CORSMiddleware
|
||||||
|
|
||||||
|
from app.config import settings
|
||||||
|
from app.database import init_db, close_db
|
||||||
|
from app.api import logs, projects, alerts, dashboard
|
||||||
|
|
||||||
|
# ── Logging ────────────────────────────────────────────────────
|
||||||
|
logging.basicConfig(
|
||||||
|
level=logging.INFO if not settings.DEBUG else logging.DEBUG,
|
||||||
|
format="%(asctime)s [%(levelname)s] %(name)s: %(message)s",
|
||||||
|
)
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
# ── Lifecycle ──────────────────────────────────────────────────
|
||||||
|
|
||||||
|
|
||||||
|
@asynccontextmanager
|
||||||
|
async def lifespan(app: FastAPI):
|
||||||
|
"""Startup and shutdown lifecycle."""
|
||||||
|
logger.info("🚀 LogHive starting up...")
|
||||||
|
await init_db()
|
||||||
|
yield
|
||||||
|
logger.info("🛑 LogHive shutting down...")
|
||||||
|
await close_db()
|
||||||
|
|
||||||
|
|
||||||
|
# ── App ────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
app = FastAPI(
|
||||||
|
title="LogHive API",
|
||||||
|
description="Centralized log management system — ingest, search, monitor, and alert on logs from your Python services.",
|
||||||
|
version="0.1.0",
|
||||||
|
lifespan=lifespan,
|
||||||
|
)
|
||||||
|
|
||||||
|
app.add_middleware(
|
||||||
|
CORSMiddleware,
|
||||||
|
allow_origins=settings.CORS_ORIGINS,
|
||||||
|
allow_credentials=True,
|
||||||
|
allow_methods=["*"],
|
||||||
|
allow_headers=["*"],
|
||||||
|
)
|
||||||
|
|
||||||
|
# ── Routes ─────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
app.include_router(logs.router)
|
||||||
|
app.include_router(projects.router)
|
||||||
|
app.include_router(alerts.router)
|
||||||
|
app.include_router(dashboard.router)
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/api/health")
|
||||||
|
async def health():
|
||||||
|
return {"status": "ok", "service": settings.SERVICE_NAME, "version": "0.1.0"}
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
from app.models.project import Project
|
||||||
|
from app.models.alert import AlertRule, AlertHistory
|
||||||
|
from app.models.log import LogEntry
|
||||||
|
|
||||||
|
__all__ = ["Project", "AlertRule", "AlertHistory", "LogEntry"]
|
||||||
@@ -0,0 +1,71 @@
|
|||||||
|
"""Alert models — rules and history."""
|
||||||
|
|
||||||
|
import uuid
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
|
||||||
|
from sqlalchemy import String, Integer, Float, Boolean, DateTime, Text, Enum as SAEnum
|
||||||
|
from sqlalchemy.orm import Mapped, mapped_column
|
||||||
|
import enum
|
||||||
|
|
||||||
|
from app.database import Base
|
||||||
|
|
||||||
|
|
||||||
|
class AlertLevel(str, enum.Enum):
|
||||||
|
INFO = "info"
|
||||||
|
WARNING = "warning"
|
||||||
|
CRITICAL = "critical"
|
||||||
|
|
||||||
|
|
||||||
|
class AlertOperator(str, enum.Enum):
|
||||||
|
GT = "gt"
|
||||||
|
GTE = "gte"
|
||||||
|
LT = "lt"
|
||||||
|
LTE = "lte"
|
||||||
|
EQ = "eq"
|
||||||
|
|
||||||
|
|
||||||
|
class AlertRule(Base):
|
||||||
|
__tablename__ = "alert_rules"
|
||||||
|
|
||||||
|
id: Mapped[str] = mapped_column(
|
||||||
|
String(36), primary_key=True, default=lambda: str(uuid.uuid4())
|
||||||
|
)
|
||||||
|
project_id: Mapped[str] = mapped_column(String(36), nullable=False, index=True)
|
||||||
|
name: Mapped[str] = mapped_column(String(128), nullable=False)
|
||||||
|
level: Mapped[AlertLevel] = mapped_column(
|
||||||
|
SAEnum(AlertLevel), default=AlertLevel.WARNING
|
||||||
|
)
|
||||||
|
field: Mapped[str] = mapped_column(
|
||||||
|
String(64), nullable=False, default="level"
|
||||||
|
) # log field to evaluate
|
||||||
|
operator: Mapped[AlertOperator] = mapped_column(
|
||||||
|
SAEnum(AlertOperator), default=AlertOperator.GTE
|
||||||
|
)
|
||||||
|
threshold: Mapped[float] = mapped_column(Float, nullable=False)
|
||||||
|
window_minutes: Mapped[int] = mapped_column(Integer, default=5)
|
||||||
|
is_enabled: Mapped[bool] = mapped_column(Boolean, default=True)
|
||||||
|
notify_channels: Mapped[str] = mapped_column(
|
||||||
|
String(256), default=""
|
||||||
|
) # comma-separated
|
||||||
|
created_at: Mapped[datetime] = mapped_column(
|
||||||
|
DateTime(timezone=True), default=lambda: datetime.now(timezone.utc)
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class AlertHistory(Base):
|
||||||
|
__tablename__ = "alert_history"
|
||||||
|
|
||||||
|
id: Mapped[str] = mapped_column(
|
||||||
|
String(36), primary_key=True, default=lambda: str(uuid.uuid4())
|
||||||
|
)
|
||||||
|
rule_id: Mapped[str] = mapped_column(
|
||||||
|
String(36), nullable=False, index=True
|
||||||
|
)
|
||||||
|
project_id: Mapped[str] = mapped_column(String(36), nullable=False, index=True)
|
||||||
|
level: Mapped[AlertLevel] = mapped_column(SAEnum(AlertLevel))
|
||||||
|
message: Mapped[str] = mapped_column(Text, nullable=False)
|
||||||
|
triggered_value: Mapped[float] = mapped_column(Float, nullable=True)
|
||||||
|
is_acknowledged: Mapped[bool] = mapped_column(Boolean, default=False)
|
||||||
|
triggered_at: Mapped[datetime] = mapped_column(
|
||||||
|
DateTime(timezone=True), default=lambda: datetime.now(timezone.utc)
|
||||||
|
)
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
"""Log entry model — stored in PostgreSQL."""
|
||||||
|
|
||||||
|
import uuid
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
|
||||||
|
from sqlalchemy import DateTime, Index, Integer, String, Text
|
||||||
|
from sqlalchemy.dialects.postgresql import JSONB
|
||||||
|
from sqlalchemy.orm import Mapped, mapped_column
|
||||||
|
|
||||||
|
from app.database import Base
|
||||||
|
|
||||||
|
|
||||||
|
class LogEntry(Base):
|
||||||
|
__tablename__ = "log_entries"
|
||||||
|
|
||||||
|
id: Mapped[str] = mapped_column(
|
||||||
|
String(36), primary_key=True, default=lambda: str(uuid.uuid4())
|
||||||
|
)
|
||||||
|
project_id: Mapped[str] = mapped_column(String(36), nullable=False, index=True)
|
||||||
|
project_name: Mapped[str] = mapped_column(String(128), nullable=False, index=True)
|
||||||
|
timestamp: Mapped[datetime] = mapped_column(
|
||||||
|
DateTime(timezone=True), nullable=False, index=True,
|
||||||
|
default=lambda: datetime.now(timezone.utc),
|
||||||
|
)
|
||||||
|
level: Mapped[str] = mapped_column(String(16), nullable=False, index=True)
|
||||||
|
logger: Mapped[str] = mapped_column(String(128), default="root")
|
||||||
|
message: Mapped[str] = mapped_column(Text, nullable=False)
|
||||||
|
module: Mapped[str | None] = mapped_column(String(256), nullable=True)
|
||||||
|
function: Mapped[str | None] = mapped_column(String(128), nullable=True)
|
||||||
|
line_no: Mapped[int | None] = mapped_column(Integer, nullable=True)
|
||||||
|
trace_id: Mapped[str | None] = mapped_column(String(64), nullable=True, index=True)
|
||||||
|
exception: Mapped[str | None] = mapped_column(Text, nullable=True)
|
||||||
|
extra: Mapped[dict] = mapped_column(JSONB, default=dict)
|
||||||
|
|
||||||
|
__table_args__ = (
|
||||||
|
Index("ix_log_entries_project_time", "project_id", timestamp.desc()),
|
||||||
|
)
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
"""Project model — represents an external service that pushes logs."""
|
||||||
|
|
||||||
|
import uuid
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
|
||||||
|
from sqlalchemy import String, Boolean, DateTime, Text
|
||||||
|
from sqlalchemy.orm import Mapped, mapped_column
|
||||||
|
|
||||||
|
from app.database import Base
|
||||||
|
|
||||||
|
|
||||||
|
class Project(Base):
|
||||||
|
__tablename__ = "projects"
|
||||||
|
|
||||||
|
id: Mapped[str] = mapped_column(
|
||||||
|
String(36), primary_key=True, default=lambda: str(uuid.uuid4())
|
||||||
|
)
|
||||||
|
name: Mapped[str] = mapped_column(String(128), unique=True, nullable=False)
|
||||||
|
description: Mapped[str] = mapped_column(Text, default="")
|
||||||
|
api_key: Mapped[str] = mapped_column(
|
||||||
|
String(64), unique=True, nullable=False, default=lambda: uuid.uuid4().hex
|
||||||
|
)
|
||||||
|
is_active: Mapped[bool] = mapped_column(Boolean, default=True)
|
||||||
|
created_at: Mapped[datetime] = mapped_column(
|
||||||
|
DateTime(timezone=True), default=lambda: datetime.now(timezone.utc)
|
||||||
|
)
|
||||||
|
updated_at: Mapped[datetime] = mapped_column(
|
||||||
|
DateTime(timezone=True),
|
||||||
|
default=lambda: datetime.now(timezone.utc),
|
||||||
|
onupdate=lambda: datetime.now(timezone.utc),
|
||||||
|
)
|
||||||
|
|
||||||
|
def __repr__(self) -> str:
|
||||||
|
return f"<Project {self.name}>"
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
from app.schemas.log import (
|
||||||
|
LogEntry,
|
||||||
|
LogBatchRequest,
|
||||||
|
LogQueryParams,
|
||||||
|
LogSearchResult,
|
||||||
|
LogStatsResult,
|
||||||
|
)
|
||||||
|
from app.schemas.project import (
|
||||||
|
ProjectCreate,
|
||||||
|
ProjectUpdate,
|
||||||
|
ProjectResponse,
|
||||||
|
ProjectWithToken,
|
||||||
|
)
|
||||||
|
from app.schemas.alert import (
|
||||||
|
AlertRuleCreate,
|
||||||
|
AlertRuleUpdate,
|
||||||
|
AlertRuleResponse,
|
||||||
|
AlertHistoryResponse,
|
||||||
|
)
|
||||||
|
|
||||||
|
__all__ = [
|
||||||
|
"LogEntry",
|
||||||
|
"LogBatchRequest",
|
||||||
|
"LogQueryParams",
|
||||||
|
"LogSearchResult",
|
||||||
|
"LogStatsResult",
|
||||||
|
"ProjectCreate",
|
||||||
|
"ProjectUpdate",
|
||||||
|
"ProjectResponse",
|
||||||
|
"ProjectWithToken",
|
||||||
|
"AlertRuleCreate",
|
||||||
|
"AlertRuleUpdate",
|
||||||
|
"AlertRuleResponse",
|
||||||
|
"AlertHistoryResponse",
|
||||||
|
]
|
||||||
@@ -0,0 +1,63 @@
|
|||||||
|
"""Alert schemas."""
|
||||||
|
|
||||||
|
from datetime import datetime
|
||||||
|
from typing import List, Optional
|
||||||
|
|
||||||
|
from pydantic import BaseModel, Field
|
||||||
|
|
||||||
|
|
||||||
|
# ── Alert Rule ─────────────────────────────────────────────────
|
||||||
|
|
||||||
|
|
||||||
|
class AlertRuleCreate(BaseModel):
|
||||||
|
project_id: str = Field(..., min_length=1, max_length=36)
|
||||||
|
name: str = Field(..., min_length=1, max_length=128)
|
||||||
|
level: str = Field(default="warning", pattern="^(info|warning|critical)$")
|
||||||
|
field: str = Field(default="level", max_length=64)
|
||||||
|
operator: str = Field(default="gte", pattern="^(gt|gte|lt|lte|eq)$")
|
||||||
|
threshold: float = Field(..., ge=0)
|
||||||
|
window_minutes: int = Field(default=5, ge=1, le=1440)
|
||||||
|
notify_channels: List[str] = Field(default_factory=list)
|
||||||
|
|
||||||
|
|
||||||
|
class AlertRuleUpdate(BaseModel):
|
||||||
|
name: Optional[str] = Field(default=None, max_length=128)
|
||||||
|
level: Optional[str] = Field(default=None, pattern="^(info|warning|critical)$")
|
||||||
|
field: Optional[str] = Field(default=None, max_length=64)
|
||||||
|
operator: Optional[str] = Field(default=None, pattern="^(gt|gte|lt|lte|eq)$")
|
||||||
|
threshold: Optional[float] = Field(default=None, ge=0)
|
||||||
|
window_minutes: Optional[int] = Field(default=None, ge=1, le=1440)
|
||||||
|
is_enabled: Optional[bool] = None
|
||||||
|
notify_channels: Optional[List[str]] = None
|
||||||
|
|
||||||
|
|
||||||
|
class AlertRuleResponse(BaseModel):
|
||||||
|
id: str
|
||||||
|
project_id: str
|
||||||
|
name: str
|
||||||
|
level: str
|
||||||
|
field: str
|
||||||
|
operator: str
|
||||||
|
threshold: float
|
||||||
|
window_minutes: int
|
||||||
|
is_enabled: bool
|
||||||
|
notify_channels: List[str]
|
||||||
|
created_at: datetime
|
||||||
|
|
||||||
|
model_config = {"from_attributes": True}
|
||||||
|
|
||||||
|
|
||||||
|
# ── Alert History ──────────────────────────────────────────────
|
||||||
|
|
||||||
|
|
||||||
|
class AlertHistoryResponse(BaseModel):
|
||||||
|
id: str
|
||||||
|
rule_id: str
|
||||||
|
project_id: str
|
||||||
|
level: str
|
||||||
|
message: str
|
||||||
|
triggered_value: Optional[float] = None
|
||||||
|
is_acknowledged: bool
|
||||||
|
triggered_at: datetime
|
||||||
|
|
||||||
|
model_config = {"from_attributes": True}
|
||||||
@@ -0,0 +1,64 @@
|
|||||||
|
"""Log entry schemas."""
|
||||||
|
|
||||||
|
from datetime import datetime
|
||||||
|
from typing import Any, Dict, List, Optional
|
||||||
|
|
||||||
|
from pydantic import BaseModel, Field
|
||||||
|
|
||||||
|
|
||||||
|
class LogEntry(BaseModel):
|
||||||
|
"""A single log entry pushed by a project."""
|
||||||
|
|
||||||
|
timestamp: Optional[datetime] = None
|
||||||
|
level: str = Field(default="info", pattern="^(debug|info|warning|error|critical)$")
|
||||||
|
logger: str = Field(default="root", max_length=128)
|
||||||
|
message: str = Field(..., min_length=1, max_length=65536)
|
||||||
|
module: Optional[str] = Field(default=None, max_length=256)
|
||||||
|
function: Optional[str] = Field(default=None, max_length=128)
|
||||||
|
line_no: Optional[int] = None
|
||||||
|
trace_id: Optional[str] = Field(default=None, max_length=64)
|
||||||
|
exception: Optional[str] = None
|
||||||
|
extra: Dict[str, Any] = Field(default_factory=dict)
|
||||||
|
|
||||||
|
|
||||||
|
class LogBatchRequest(BaseModel):
|
||||||
|
"""Batch of log entries pushed in a single request."""
|
||||||
|
|
||||||
|
project: str = Field(..., min_length=1, max_length=128)
|
||||||
|
entries: List[LogEntry] = Field(..., min_length=1, max_length=5000)
|
||||||
|
|
||||||
|
|
||||||
|
class LogQueryParams(BaseModel):
|
||||||
|
"""Parameters for log search / query."""
|
||||||
|
|
||||||
|
project: Optional[str] = None
|
||||||
|
level: Optional[str] = Field(
|
||||||
|
default=None, pattern="^(debug|info|warning|error|critical)$"
|
||||||
|
)
|
||||||
|
query: Optional[str] = Field(default=None, max_length=1024)
|
||||||
|
trace_id: Optional[str] = Field(default=None, max_length=64)
|
||||||
|
start_time: Optional[datetime] = None
|
||||||
|
end_time: Optional[datetime] = None
|
||||||
|
page: int = Field(default=1, ge=1)
|
||||||
|
page_size: int = Field(default=50, ge=1, le=1000)
|
||||||
|
sort_by: str = Field(default="timestamp", max_length=32)
|
||||||
|
sort_order: str = Field(default="desc", pattern="^(asc|desc)$")
|
||||||
|
|
||||||
|
|
||||||
|
class LogSearchResult(BaseModel):
|
||||||
|
"""Search result wrapper."""
|
||||||
|
|
||||||
|
total: int
|
||||||
|
page: int
|
||||||
|
page_size: int
|
||||||
|
hits: List[Dict[str, Any]]
|
||||||
|
|
||||||
|
|
||||||
|
class LogStatsResult(BaseModel):
|
||||||
|
"""Aggregated log statistics."""
|
||||||
|
|
||||||
|
project: Optional[str] = None
|
||||||
|
time_buckets: List[Dict[str, Any]]
|
||||||
|
level_counts: Dict[str, int]
|
||||||
|
top_loggers: List[Dict[str, Any]]
|
||||||
|
total: int
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
"""Project schemas."""
|
||||||
|
|
||||||
|
from datetime import datetime
|
||||||
|
from typing import Optional
|
||||||
|
|
||||||
|
from pydantic import BaseModel, Field
|
||||||
|
|
||||||
|
|
||||||
|
class ProjectCreate(BaseModel):
|
||||||
|
name: str = Field(..., min_length=1, max_length=128, description="Project name")
|
||||||
|
description: str = Field(default="", max_length=1024)
|
||||||
|
|
||||||
|
|
||||||
|
class ProjectUpdate(BaseModel):
|
||||||
|
name: Optional[str] = Field(default=None, max_length=128)
|
||||||
|
description: Optional[str] = Field(default=None, max_length=1024)
|
||||||
|
is_active: Optional[bool] = None
|
||||||
|
|
||||||
|
|
||||||
|
class ProjectResponse(BaseModel):
|
||||||
|
id: str
|
||||||
|
name: str
|
||||||
|
description: str
|
||||||
|
is_active: bool
|
||||||
|
created_at: datetime
|
||||||
|
updated_at: datetime
|
||||||
|
|
||||||
|
model_config = {"from_attributes": True}
|
||||||
|
|
||||||
|
|
||||||
|
class ProjectWithToken(ProjectResponse):
|
||||||
|
api_key: str
|
||||||
|
|
||||||
|
model_config = {"from_attributes": True}
|
||||||
@@ -0,0 +1,142 @@
|
|||||||
|
"""Alert evaluation and notification service."""
|
||||||
|
|
||||||
|
import logging
|
||||||
|
from datetime import datetime, timezone, timedelta
|
||||||
|
from typing import Optional
|
||||||
|
|
||||||
|
from sqlalchemy import func, select
|
||||||
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
||||||
|
from app.config import settings
|
||||||
|
from app.models.alert import AlertRule, AlertHistory, AlertLevel, AlertOperator
|
||||||
|
from app.models.log import LogEntry
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
class AlertService:
|
||||||
|
"""Evaluates alert rules against recent log data and triggers notifications."""
|
||||||
|
|
||||||
|
def __init__(self, db: AsyncSession):
|
||||||
|
self.db = db
|
||||||
|
|
||||||
|
async def evaluate_rules(self) -> list[AlertHistory]:
|
||||||
|
"""Check all enabled alert rules and trigger any that match."""
|
||||||
|
result = await self.db.execute(
|
||||||
|
select(AlertRule).where(AlertRule.is_enabled == True)
|
||||||
|
)
|
||||||
|
rules: list[AlertRule] = result.scalars().all()
|
||||||
|
triggered: list[AlertHistory] = []
|
||||||
|
|
||||||
|
for rule in rules:
|
||||||
|
try:
|
||||||
|
hit = await self._evaluate_single(rule)
|
||||||
|
if hit:
|
||||||
|
triggered.append(hit)
|
||||||
|
except Exception as e:
|
||||||
|
logger.error("Error evaluating rule %s: %s", rule.id, e)
|
||||||
|
|
||||||
|
return triggered
|
||||||
|
|
||||||
|
async def _evaluate_single(self, rule: AlertRule) -> Optional[AlertHistory]:
|
||||||
|
"""Evaluate a single rule. Returns AlertHistory if triggered."""
|
||||||
|
now = datetime.now(timezone.utc)
|
||||||
|
since = now - timedelta(minutes=rule.window_minutes)
|
||||||
|
|
||||||
|
stmt = (
|
||||||
|
select(func.count(LogEntry.id))
|
||||||
|
.where(LogEntry.project_id == rule.project_id)
|
||||||
|
.where(LogEntry.timestamp >= since)
|
||||||
|
.where(LogEntry.level == rule.level.value)
|
||||||
|
)
|
||||||
|
count = (await self.db.execute(stmt)).scalar() or 0
|
||||||
|
|
||||||
|
operator_map = {
|
||||||
|
AlertOperator.GT: lambda v, t: v > t,
|
||||||
|
AlertOperator.GTE: lambda v, t: v >= t,
|
||||||
|
AlertOperator.LT: lambda v, t: v < t,
|
||||||
|
AlertOperator.LTE: lambda v, t: v <= t,
|
||||||
|
AlertOperator.EQ: lambda v, t: v == t,
|
||||||
|
}
|
||||||
|
|
||||||
|
op_fn = operator_map.get(rule.operator)
|
||||||
|
if op_fn and op_fn(float(count), rule.threshold):
|
||||||
|
history = AlertHistory(
|
||||||
|
rule_id=rule.id,
|
||||||
|
project_id=rule.project_id,
|
||||||
|
level=rule.level,
|
||||||
|
message=(
|
||||||
|
f"Alert '{rule.name}': {rule.level.value} logs count ({count}) "
|
||||||
|
f"{rule.operator.value} threshold ({rule.threshold}) "
|
||||||
|
f"in last {rule.window_minutes} min"
|
||||||
|
),
|
||||||
|
triggered_value=float(count),
|
||||||
|
)
|
||||||
|
self.db.add(history)
|
||||||
|
await self.db.flush()
|
||||||
|
logger.info("Alert triggered: %s", history.message)
|
||||||
|
|
||||||
|
if rule.notify_channels:
|
||||||
|
await self._notify(rule, history)
|
||||||
|
|
||||||
|
return history
|
||||||
|
|
||||||
|
return None
|
||||||
|
|
||||||
|
async def _notify(self, rule: AlertRule, history: AlertHistory) -> None:
|
||||||
|
"""Send notification via configured channels."""
|
||||||
|
channels = [c.strip() for c in rule.notify_channels.split(",") if c.strip()]
|
||||||
|
for channel in channels:
|
||||||
|
if channel == "feishu" and settings.FEISHU_WEBHOOK_URL:
|
||||||
|
await self._send_feishu(rule, history)
|
||||||
|
elif channel == "dingtalk" and settings.DINGTALK_WEBHOOK_URL:
|
||||||
|
await self._send_dingtalk(rule, history)
|
||||||
|
|
||||||
|
async def _send_feishu(self, rule: AlertRule, history: AlertHistory) -> None:
|
||||||
|
"""Send a notification to Feishu webhook."""
|
||||||
|
import httpx
|
||||||
|
|
||||||
|
payload = {
|
||||||
|
"msg_type": "post",
|
||||||
|
"content": {
|
||||||
|
"post": {
|
||||||
|
"zh_cn": {
|
||||||
|
"title": f"[LogHive] Alert: {rule.name}",
|
||||||
|
"content": [
|
||||||
|
[{"tag": "text", "text": history.message}],
|
||||||
|
[
|
||||||
|
{
|
||||||
|
"tag": "text",
|
||||||
|
"text": f"Project: {rule.project_id} | Level: {rule.level.value}",
|
||||||
|
}
|
||||||
|
],
|
||||||
|
],
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
}
|
||||||
|
try:
|
||||||
|
async with httpx.AsyncClient() as client:
|
||||||
|
await client.post(settings.FEISHU_WEBHOOK_URL, json=payload, timeout=10)
|
||||||
|
except Exception as e:
|
||||||
|
logger.error("Feishu notification failed: %s", e)
|
||||||
|
|
||||||
|
async def _send_dingtalk(self, rule: AlertRule, history: AlertHistory) -> None:
|
||||||
|
"""Send a notification to DingTalk webhook."""
|
||||||
|
import httpx
|
||||||
|
|
||||||
|
payload = {
|
||||||
|
"msgtype": "text",
|
||||||
|
"text": {
|
||||||
|
"content": (
|
||||||
|
f"[LogHive] Alert: {rule.name}\n"
|
||||||
|
f"{history.message}\n"
|
||||||
|
f"Project: {rule.project_id} | Level: {rule.level.value}"
|
||||||
|
)
|
||||||
|
},
|
||||||
|
}
|
||||||
|
try:
|
||||||
|
async with httpx.AsyncClient() as client:
|
||||||
|
await client.post(settings.DINGTALK_WEBHOOK_URL, json=payload, timeout=10)
|
||||||
|
except Exception as e:
|
||||||
|
logger.error("DingTalk notification failed: %s", e)
|
||||||
@@ -0,0 +1,125 @@
|
|||||||
|
"""Log analytics service — provides aggregated statistics and insights."""
|
||||||
|
|
||||||
|
import logging
|
||||||
|
from datetime import datetime, timezone, timedelta
|
||||||
|
from typing import Optional
|
||||||
|
|
||||||
|
from sqlalchemy import func, select, text
|
||||||
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
||||||
|
from app.config import to_display_time
|
||||||
|
from app.models.log import LogEntry
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
class AnalyticsService:
|
||||||
|
"""Time-series analytics over log data."""
|
||||||
|
|
||||||
|
def __init__(self, db: AsyncSession):
|
||||||
|
self.db = db
|
||||||
|
|
||||||
|
def _build_filters(self, project: Optional[str], since: datetime):
|
||||||
|
"""Build SQLAlchemy filter list."""
|
||||||
|
filters = [LogEntry.timestamp >= since]
|
||||||
|
if project:
|
||||||
|
filters.append(LogEntry.project_name == project)
|
||||||
|
return filters
|
||||||
|
|
||||||
|
async def get_dashboard_stats(
|
||||||
|
self, project: Optional[str] = None, hours: int = 24
|
||||||
|
) -> dict:
|
||||||
|
"""Get overview statistics for the dashboard."""
|
||||||
|
now = datetime.now(timezone.utc)
|
||||||
|
since = now - timedelta(hours=hours)
|
||||||
|
filters = self._build_filters(project, since)
|
||||||
|
|
||||||
|
# Total log count
|
||||||
|
total = (await self.db.execute(
|
||||||
|
select(func.count(LogEntry.id)).where(*filters)
|
||||||
|
)).scalar() or 0
|
||||||
|
|
||||||
|
# Error count
|
||||||
|
error_count = (await self.db.execute(
|
||||||
|
select(func.count(LogEntry.id)).where(
|
||||||
|
*filters, LogEntry.level.in_(["error", "critical"])
|
||||||
|
)
|
||||||
|
)).scalar() or 0
|
||||||
|
|
||||||
|
# Level breakdown
|
||||||
|
level_rows = (await self.db.execute(
|
||||||
|
select(LogEntry.level, func.count(LogEntry.id))
|
||||||
|
.where(*filters)
|
||||||
|
.group_by(LogEntry.level)
|
||||||
|
)).all()
|
||||||
|
level_breakdown = {row[0]: row[1] for row in level_rows}
|
||||||
|
|
||||||
|
# Error rate
|
||||||
|
error_rate = round((error_count / total * 100), 2) if total > 0 else 0
|
||||||
|
|
||||||
|
# Top error messages
|
||||||
|
top_rows = (await self.db.execute(
|
||||||
|
select(LogEntry.message, func.count(LogEntry.id).label("cnt"))
|
||||||
|
.where(*filters, LogEntry.level.in_(["error", "critical"]))
|
||||||
|
.group_by(LogEntry.message)
|
||||||
|
.order_by(func.count(LogEntry.id).desc())
|
||||||
|
.limit(10)
|
||||||
|
)).all()
|
||||||
|
top_errors = [{"message": row[0], "count": row[1]} for row in top_rows]
|
||||||
|
|
||||||
|
return {
|
||||||
|
"total_logs": total,
|
||||||
|
"error_count": error_count,
|
||||||
|
"error_rate": error_rate,
|
||||||
|
"level_breakdown": level_breakdown,
|
||||||
|
"time_range_hours": hours,
|
||||||
|
"top_errors": top_errors,
|
||||||
|
}
|
||||||
|
|
||||||
|
async def get_time_series(
|
||||||
|
self,
|
||||||
|
project: Optional[str] = None,
|
||||||
|
hours: int = 24,
|
||||||
|
interval: str = "5m",
|
||||||
|
) -> list[dict]:
|
||||||
|
"""Get time-series data for log volume charts."""
|
||||||
|
now = datetime.now(timezone.utc)
|
||||||
|
since = now - timedelta(hours=hours)
|
||||||
|
|
||||||
|
n = int("".join(c for c in interval if c.isdigit()) or "5")
|
||||||
|
unit = "".join(c for c in interval if c.isalpha()) or "m"
|
||||||
|
if unit == "h":
|
||||||
|
n = n * 60
|
||||||
|
n = max(n, 1)
|
||||||
|
|
||||||
|
# Build WHERE clauses
|
||||||
|
where_clauses = [f"timestamp >= '{since.isoformat()}'"]
|
||||||
|
params: dict = {}
|
||||||
|
if project:
|
||||||
|
where_clauses.append("project_name = :project")
|
||||||
|
params["project"] = project
|
||||||
|
where_sql = " AND ".join(where_clauses)
|
||||||
|
|
||||||
|
sql = text(
|
||||||
|
f"SELECT "
|
||||||
|
f" date_trunc('hour', timestamp) + "
|
||||||
|
f" ((floor(extract(minute from timestamp) / {n})::int * {n}) || ' min')::interval AS bucket, "
|
||||||
|
f" level, "
|
||||||
|
f" count(*) AS cnt "
|
||||||
|
f"FROM log_entries "
|
||||||
|
f"WHERE {where_sql} "
|
||||||
|
f"GROUP BY bucket, level "
|
||||||
|
f"ORDER BY bucket"
|
||||||
|
)
|
||||||
|
|
||||||
|
rows = (await self.db.execute(sql, params)).all()
|
||||||
|
|
||||||
|
buckets: dict[str, dict] = {}
|
||||||
|
for row in rows:
|
||||||
|
ts = to_display_time(row.bucket) if isinstance(row.bucket, datetime) else str(row.bucket)
|
||||||
|
if ts not in buckets:
|
||||||
|
buckets[ts] = {"timestamp": ts, "total": 0, "levels": {}}
|
||||||
|
buckets[ts]["total"] += row.cnt
|
||||||
|
buckets[ts]["levels"][row.level] = row.cnt
|
||||||
|
|
||||||
|
return list(buckets.values())
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
"""Celery application for async background tasks."""
|
||||||
|
|
||||||
|
from celery import Celery
|
||||||
|
|
||||||
|
from app.config import settings
|
||||||
|
|
||||||
|
celery_app = Celery(
|
||||||
|
"loghive",
|
||||||
|
broker=settings.CELERY_BROKER_URL,
|
||||||
|
backend=settings.CELERY_RESULT_BACKEND,
|
||||||
|
include=["celery_worker.tasks"],
|
||||||
|
)
|
||||||
|
|
||||||
|
celery_app.conf.update(
|
||||||
|
task_serializer="json",
|
||||||
|
accept_content=["json"],
|
||||||
|
result_serializer="json",
|
||||||
|
timezone="UTC",
|
||||||
|
enable_utc=True,
|
||||||
|
task_track_started=True,
|
||||||
|
task_acks_late=True,
|
||||||
|
worker_prefetch_multiplier=1,
|
||||||
|
beat_schedule={
|
||||||
|
"evaluate-alert-rules": {
|
||||||
|
"task": "celery_worker.tasks.evaluate_alerts",
|
||||||
|
"schedule": settings.ALERT_CHECK_INTERVAL_SECONDS,
|
||||||
|
},
|
||||||
|
"cleanup-old-log-indices": {
|
||||||
|
"task": "celery_worker.tasks.cleanup_old_indices",
|
||||||
|
"schedule": 3600, # once per hour
|
||||||
|
},
|
||||||
|
},
|
||||||
|
)
|
||||||
@@ -0,0 +1,82 @@
|
|||||||
|
"""Celery tasks for periodic and async processing."""
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
import logging
|
||||||
|
from datetime import datetime, timezone, timedelta
|
||||||
|
|
||||||
|
from sqlalchemy import delete
|
||||||
|
from sqlalchemy.ext.asyncio import create_async_engine, async_sessionmaker
|
||||||
|
|
||||||
|
from app.config import settings
|
||||||
|
from app.models.log import LogEntry
|
||||||
|
from app.services.alert_service import AlertService
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
from celery_worker.celery_app import celery_app
|
||||||
|
|
||||||
|
|
||||||
|
@celery_app.task(bind=True, max_retries=3)
|
||||||
|
def evaluate_alerts(self):
|
||||||
|
"""Evaluate all alert rules and trigger notifications.
|
||||||
|
|
||||||
|
Runs periodically (default: every 60 seconds via beat schedule).
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
loop = asyncio.get_event_loop()
|
||||||
|
if loop.is_closed():
|
||||||
|
loop = asyncio.new_event_loop()
|
||||||
|
asyncio.set_event_loop(loop)
|
||||||
|
|
||||||
|
result = loop.run_until_complete(_async_evaluate_alerts())
|
||||||
|
logger.info("Alert evaluation complete: %d triggers", len(result))
|
||||||
|
return {"triggered": len(result)}
|
||||||
|
except Exception as e:
|
||||||
|
logger.error("Alert evaluation failed: %s", e)
|
||||||
|
raise self.retry(exc=e, countdown=30)
|
||||||
|
|
||||||
|
|
||||||
|
async def _async_evaluate_alerts():
|
||||||
|
"""Async body of alert evaluation."""
|
||||||
|
engine = create_async_engine(settings.DATABASE_URL)
|
||||||
|
factory = async_sessionmaker(engine, expire_on_commit=False)
|
||||||
|
|
||||||
|
try:
|
||||||
|
async with factory() as db:
|
||||||
|
service = AlertService(db)
|
||||||
|
triggered = await service.evaluate_rules()
|
||||||
|
await db.commit()
|
||||||
|
return triggered
|
||||||
|
finally:
|
||||||
|
await engine.dispose()
|
||||||
|
|
||||||
|
|
||||||
|
@celery_app.task
|
||||||
|
def cleanup_old_indices():
|
||||||
|
"""Delete log entries older than the retention period."""
|
||||||
|
try:
|
||||||
|
loop = asyncio.get_event_loop()
|
||||||
|
if loop.is_closed():
|
||||||
|
loop = asyncio.new_event_loop()
|
||||||
|
asyncio.set_event_loop(loop)
|
||||||
|
result = loop.run_until_complete(_async_cleanup())
|
||||||
|
logger.info("Cleanup complete: %d entries deleted", result)
|
||||||
|
return {"deleted": result}
|
||||||
|
except Exception as e:
|
||||||
|
logger.error("Cleanup failed: %s", e)
|
||||||
|
return {"error": str(e)}
|
||||||
|
|
||||||
|
|
||||||
|
async def _async_cleanup() -> int:
|
||||||
|
"""Delete old log entries."""
|
||||||
|
engine = create_async_engine(settings.DATABASE_URL)
|
||||||
|
factory = async_sessionmaker(engine, expire_on_commit=False)
|
||||||
|
|
||||||
|
try:
|
||||||
|
cutoff = datetime.now(timezone.utc) - timedelta(days=settings.LOG_RETENTION_DAYS)
|
||||||
|
async with factory() as db:
|
||||||
|
result = await db.execute(delete(LogEntry).where(LogEntry.timestamp < cutoff))
|
||||||
|
await db.commit()
|
||||||
|
return result.rowcount
|
||||||
|
finally:
|
||||||
|
await engine.dispose()
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
# LogHive Backend Dependencies
|
||||||
|
|
||||||
|
# Framework
|
||||||
|
fastapi>=0.111.0
|
||||||
|
uvicorn[standard]>=0.30.0
|
||||||
|
pydantic>=2.7.0
|
||||||
|
pydantic-settings>=2.3.0
|
||||||
|
|
||||||
|
# Database
|
||||||
|
sqlalchemy[asyncio]>=2.0.30
|
||||||
|
asyncpg>=0.29.0
|
||||||
|
|
||||||
|
# Task Queue
|
||||||
|
celery>=5.4.0
|
||||||
|
redis>=5.0.0
|
||||||
|
|
||||||
|
# HTTP Client (for webhook notifications)
|
||||||
|
httpx>=0.27.0
|
||||||
|
|
||||||
|
# CORS / Middleware
|
||||||
|
python-multipart>=0.0.9
|
||||||
|
|
||||||
|
# Utilities
|
||||||
|
python-dateutil>=2.9.0
|
||||||
|
orjson>=3.10.0
|
||||||
@@ -0,0 +1,84 @@
|
|||||||
|
# LogHive Client SDK
|
||||||
|
|
||||||
|
Python client SDK for sending logs to [LogHive](https://github.com/your-org/loghive).
|
||||||
|
|
||||||
|
## Installation
|
||||||
|
|
||||||
|
```bash
|
||||||
|
pip install loghive-client
|
||||||
|
```
|
||||||
|
|
||||||
|
Or install from source:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd client
|
||||||
|
pip install .
|
||||||
|
```
|
||||||
|
|
||||||
|
## Quick Start
|
||||||
|
|
||||||
|
### Sync mode (recommended for scripts, Django, Flask)
|
||||||
|
|
||||||
|
```python
|
||||||
|
from loghive_client import LogHiveLogger
|
||||||
|
|
||||||
|
logger = LogHiveLogger(
|
||||||
|
project="my-awesome-app",
|
||||||
|
api_key="your-api-key",
|
||||||
|
endpoint="http://localhost:8000",
|
||||||
|
)
|
||||||
|
|
||||||
|
logger.info("Server started", extra={"port": 8080})
|
||||||
|
logger.error("Database timeout", exc_info=True)
|
||||||
|
```
|
||||||
|
|
||||||
|
### Async mode (for FastAPI, aiohttp, asyncio)
|
||||||
|
|
||||||
|
```python
|
||||||
|
from loghive_client import AsyncLogHiveLogger
|
||||||
|
import asyncio
|
||||||
|
|
||||||
|
async def main():
|
||||||
|
async with AsyncLogHiveLogger(
|
||||||
|
project="my-api",
|
||||||
|
api_key="your-api-key",
|
||||||
|
endpoint="http://localhost:8000",
|
||||||
|
) as logger:
|
||||||
|
await logger.info("API started")
|
||||||
|
# ...
|
||||||
|
|
||||||
|
asyncio.run(main())
|
||||||
|
```
|
||||||
|
|
||||||
|
### Standard logging integration (zero code change)
|
||||||
|
|
||||||
|
Add the handler to your existing logger:
|
||||||
|
|
||||||
|
```python
|
||||||
|
import logging
|
||||||
|
from loghive_client import LogHiveHandler
|
||||||
|
|
||||||
|
handler = LogHiveHandler("my-project", "api-key", "http://localhost:8000")
|
||||||
|
logging.getLogger().addHandler(handler)
|
||||||
|
|
||||||
|
# All existing logger calls now forward to LogHive
|
||||||
|
logging.info("This goes to LogHive too!")
|
||||||
|
```
|
||||||
|
|
||||||
|
## Configuration
|
||||||
|
|
||||||
|
| Param | Default | Description |
|
||||||
|
|-------|---------|-------------|
|
||||||
|
| `project` | (required) | Your project name in LogHive |
|
||||||
|
| `api_key` | (required) | Your project's API key |
|
||||||
|
| `endpoint` | `http://localhost:8000` | LogHive server URL |
|
||||||
|
| `batch_size` | 50 | Max entries per HTTP request |
|
||||||
|
| `flush_interval` | 2.0 | Seconds between flushes |
|
||||||
|
| `max_retries` | 3 | Retries on failure |
|
||||||
|
| `timeout` | 5.0 | HTTP request timeout |
|
||||||
|
|
||||||
|
## Trace ID (request correlation)
|
||||||
|
|
||||||
|
```python
|
||||||
|
logger.set_trace_id("req-abc-123")
|
||||||
|
```
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
"""LogHive Client — Send logs from your Python projects to LogHive.
|
||||||
|
|
||||||
|
Usage:
|
||||||
|
from loghive_client import LogHiveLogger
|
||||||
|
|
||||||
|
logger = LogHiveLogger(
|
||||||
|
project="my-project",
|
||||||
|
api_key="your-api-key",
|
||||||
|
endpoint="http://localhost:8000",
|
||||||
|
)
|
||||||
|
|
||||||
|
logger.info("User logged in", extra={"user_id": 42})
|
||||||
|
logger.error("Database connection failed", exc_info=True)
|
||||||
|
"""
|
||||||
|
|
||||||
|
from loghive_client.client import LogHiveLogger
|
||||||
|
from loghive_client.async_client import AsyncLogHiveLogger
|
||||||
|
from loghive_client.handler import LogHiveHandler
|
||||||
|
|
||||||
|
__all__ = ["LogHiveLogger", "AsyncLogHiveLogger", "LogHiveHandler"]
|
||||||
@@ -0,0 +1,178 @@
|
|||||||
|
"""Async LogHive client — for use in asyncio-based projects (e.g., FastAPI, aiohttp)."""
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
import logging
|
||||||
|
import traceback
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
from typing import Any, Dict, List, Optional
|
||||||
|
from urllib.parse import urljoin
|
||||||
|
|
||||||
|
import httpx
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
class AsyncLogHiveLogger:
|
||||||
|
"""Async logger for asyncio applications.
|
||||||
|
|
||||||
|
Uses an async background task to batch and send log entries.
|
||||||
|
Ideal for FastAPI / Starlette / aiohttp projects.
|
||||||
|
|
||||||
|
Usage:
|
||||||
|
logger = AsyncLogHiveLogger("my-project", "api-key", "http://localhost:8000")
|
||||||
|
await logger.start()
|
||||||
|
|
||||||
|
await logger.info("Request processed", extra={"path": "/api/users"})
|
||||||
|
|
||||||
|
await logger.stop()
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
project: str,
|
||||||
|
api_key: str,
|
||||||
|
endpoint: str = "http://localhost:8000",
|
||||||
|
batch_size: int = 50,
|
||||||
|
flush_interval: float = 2.0,
|
||||||
|
max_retries: int = 3,
|
||||||
|
timeout: float = 5.0,
|
||||||
|
):
|
||||||
|
self.project = project
|
||||||
|
self.api_key = api_key
|
||||||
|
self.endpoint = endpoint.rstrip("/")
|
||||||
|
self.batch_size = batch_size
|
||||||
|
self.flush_interval = flush_interval
|
||||||
|
self.max_retries = max_retries
|
||||||
|
self.timeout = timeout
|
||||||
|
|
||||||
|
self._queue: asyncio.Queue = asyncio.Queue()
|
||||||
|
self._task: Optional[asyncio.Task] = None
|
||||||
|
self._client: Optional[httpx.AsyncClient] = None
|
||||||
|
self._stop_event = asyncio.Event()
|
||||||
|
|
||||||
|
async def start(self):
|
||||||
|
"""Start the background flush task."""
|
||||||
|
if self._task and not self._task.done():
|
||||||
|
return
|
||||||
|
self._client = httpx.AsyncClient(timeout=self.timeout)
|
||||||
|
self._stop_event.clear()
|
||||||
|
self._task = asyncio.create_task(self._flush_loop())
|
||||||
|
logger.debug("AsyncLogHiveLogger started for project '%s'", self.project)
|
||||||
|
|
||||||
|
async def stop(self, flush: bool = True):
|
||||||
|
"""Stop the background task."""
|
||||||
|
self._stop_event.set()
|
||||||
|
if flush:
|
||||||
|
await self._flush_now()
|
||||||
|
if self._task:
|
||||||
|
self._task.cancel()
|
||||||
|
try:
|
||||||
|
await self._task
|
||||||
|
except asyncio.CancelledError:
|
||||||
|
pass
|
||||||
|
if self._client:
|
||||||
|
await self._client.aclose()
|
||||||
|
logger.debug("AsyncLogHiveLogger stopped for project '%s'", self.project)
|
||||||
|
|
||||||
|
async def __aenter__(self):
|
||||||
|
await self.start()
|
||||||
|
return self
|
||||||
|
|
||||||
|
async def __aexit__(self, *args):
|
||||||
|
await self.stop()
|
||||||
|
|
||||||
|
async def _flush_loop(self):
|
||||||
|
"""Background loop that periodically flushes the queue."""
|
||||||
|
while not self._stop_event.is_set():
|
||||||
|
await self._flush_now()
|
||||||
|
await asyncio.sleep(self.flush_interval)
|
||||||
|
|
||||||
|
async def _flush_now(self):
|
||||||
|
"""Flush all currently queued entries."""
|
||||||
|
entries = []
|
||||||
|
while len(entries) < self.batch_size:
|
||||||
|
try:
|
||||||
|
entry = self._queue.get_nowait()
|
||||||
|
entries.append(entry)
|
||||||
|
except asyncio.QueueEmpty:
|
||||||
|
break
|
||||||
|
|
||||||
|
if not entries:
|
||||||
|
return
|
||||||
|
|
||||||
|
await self._send_batch(entries)
|
||||||
|
|
||||||
|
async def _send_batch(self, entries: List[Dict[str, Any]]):
|
||||||
|
"""Send a batch with retries."""
|
||||||
|
url = urljoin(self.endpoint, "/api/logs/ingest")
|
||||||
|
payload = {"project": self.project, "entries": entries}
|
||||||
|
|
||||||
|
for attempt in range(self.max_retries):
|
||||||
|
try:
|
||||||
|
resp = await self._client.post(
|
||||||
|
url,
|
||||||
|
json=payload,
|
||||||
|
headers={"Authorization": f"Bearer {self.api_key}"},
|
||||||
|
)
|
||||||
|
if resp.status_code == 201:
|
||||||
|
return
|
||||||
|
elif resp.status_code == 401:
|
||||||
|
logger.error("LogHive: Invalid API key — dropping batch")
|
||||||
|
return
|
||||||
|
else:
|
||||||
|
logger.warning(
|
||||||
|
"LogHive: HTTP %d (attempt %d/%d)",
|
||||||
|
resp.status_code,
|
||||||
|
attempt + 1,
|
||||||
|
self.max_retries,
|
||||||
|
)
|
||||||
|
except httpx.RequestError as e:
|
||||||
|
logger.warning(
|
||||||
|
"LogHive: Connection error (attempt %d/%d): %s",
|
||||||
|
attempt + 1,
|
||||||
|
self.max_retries,
|
||||||
|
e,
|
||||||
|
)
|
||||||
|
|
||||||
|
if attempt < self.max_retries - 1:
|
||||||
|
await asyncio.sleep(2 ** attempt)
|
||||||
|
|
||||||
|
logger.error("LogHive: Failed to send %d entries after %d retries", len(entries), self.max_retries)
|
||||||
|
|
||||||
|
def _enqueue(self, level: str, message: str, **kwargs):
|
||||||
|
"""Enqueue a log entry."""
|
||||||
|
entry = {
|
||||||
|
"timestamp": datetime.now(timezone.utc).isoformat(),
|
||||||
|
"level": level,
|
||||||
|
"message": message,
|
||||||
|
"logger": kwargs.pop("logger", None) or __name__,
|
||||||
|
"extra": kwargs,
|
||||||
|
}
|
||||||
|
|
||||||
|
exc_info = kwargs.pop("exc_info", None)
|
||||||
|
if exc_info:
|
||||||
|
if isinstance(exc_info, BaseException):
|
||||||
|
entry["exception"] = "".join(
|
||||||
|
traceback.format_exception(type(exc_info), exc_info, exc_info.__traceback__)
|
||||||
|
)
|
||||||
|
elif exc_info is True:
|
||||||
|
entry["exception"] = traceback.format_exc()
|
||||||
|
|
||||||
|
self._queue.put_nowait(entry)
|
||||||
|
|
||||||
|
# ── Public API ─────────────────────────────────────────────
|
||||||
|
|
||||||
|
async def debug(self, message: str, **kwargs):
|
||||||
|
self._enqueue("debug", message, **kwargs)
|
||||||
|
|
||||||
|
async def info(self, message: str, **kwargs):
|
||||||
|
self._enqueue("info", message, **kwargs)
|
||||||
|
|
||||||
|
async def warning(self, message: str, **kwargs):
|
||||||
|
self._enqueue("warning", message, **kwargs)
|
||||||
|
|
||||||
|
async def error(self, message: str, **kwargs):
|
||||||
|
self._enqueue("error", message, **kwargs)
|
||||||
|
|
||||||
|
async def critical(self, message: str, **kwargs):
|
||||||
|
self._enqueue("critical", message, **kwargs)
|
||||||
@@ -0,0 +1,183 @@
|
|||||||
|
"""Synchronous LogHive client — uses threading for non-blocking sends."""
|
||||||
|
|
||||||
|
import json
|
||||||
|
import logging
|
||||||
|
import threading
|
||||||
|
import time
|
||||||
|
import traceback
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
from queue import Queue, Empty
|
||||||
|
from typing import Any, Dict, List, Optional
|
||||||
|
from urllib.parse import urljoin
|
||||||
|
|
||||||
|
import httpx
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
class LogHiveLogger:
|
||||||
|
"""Synchronous logger that sends logs to LogHive in the background.
|
||||||
|
|
||||||
|
Uses a background thread with a queue to avoid blocking the main
|
||||||
|
application on network I/O.
|
||||||
|
|
||||||
|
Usage:
|
||||||
|
logger = LogHiveLogger("my-project", "api-key-here", "http://localhost:8000")
|
||||||
|
logger.info("Hello, world!")
|
||||||
|
logger.error("Something broke", exc_info=True)
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
project: str,
|
||||||
|
api_key: str,
|
||||||
|
endpoint: str = "http://localhost:8000",
|
||||||
|
batch_size: int = 50,
|
||||||
|
flush_interval: float = 2.0,
|
||||||
|
max_retries: int = 3,
|
||||||
|
timeout: float = 5.0,
|
||||||
|
auto_start: bool = True,
|
||||||
|
):
|
||||||
|
self.project = project
|
||||||
|
self.api_key = api_key
|
||||||
|
self.endpoint = endpoint.rstrip("/")
|
||||||
|
self.batch_size = batch_size
|
||||||
|
self.flush_interval = flush_interval
|
||||||
|
self.max_retries = max_retries
|
||||||
|
self.timeout = timeout
|
||||||
|
|
||||||
|
self._queue: Queue = Queue()
|
||||||
|
self._stop_event = threading.Event()
|
||||||
|
self._thread: Optional[threading.Thread] = None
|
||||||
|
|
||||||
|
if auto_start:
|
||||||
|
self.start()
|
||||||
|
|
||||||
|
def start(self):
|
||||||
|
"""Start the background flush thread."""
|
||||||
|
if self._thread and self._thread.is_alive():
|
||||||
|
return
|
||||||
|
self._stop_event.clear()
|
||||||
|
self._thread = threading.Thread(target=self._flush_loop, daemon=True)
|
||||||
|
self._thread.start()
|
||||||
|
|
||||||
|
def stop(self, flush: bool = True):
|
||||||
|
"""Stop the background thread, optionally flushing remaining logs."""
|
||||||
|
self._stop_event.set()
|
||||||
|
if flush and self._thread:
|
||||||
|
self._flush_now()
|
||||||
|
if self._thread:
|
||||||
|
self._thread.join(timeout=5)
|
||||||
|
|
||||||
|
def _flush_loop(self):
|
||||||
|
"""Background loop that periodically flushes the queue."""
|
||||||
|
while not self._stop_event.is_set():
|
||||||
|
self._flush_now()
|
||||||
|
self._stop_event.wait(self.flush_interval)
|
||||||
|
|
||||||
|
def _flush_now(self):
|
||||||
|
"""Flush all currently queued log entries."""
|
||||||
|
entries = []
|
||||||
|
while len(entries) < self.batch_size:
|
||||||
|
try:
|
||||||
|
entry = self._queue.get_nowait()
|
||||||
|
entries.append(entry)
|
||||||
|
except Empty:
|
||||||
|
break
|
||||||
|
|
||||||
|
if not entries:
|
||||||
|
return
|
||||||
|
|
||||||
|
self._send_batch(entries)
|
||||||
|
|
||||||
|
def _send_batch(self, entries: List[Dict[str, Any]]):
|
||||||
|
"""Send a batch of entries to the LogHive API, with retries."""
|
||||||
|
url = urljoin(self.endpoint, "/api/logs/ingest")
|
||||||
|
payload = {"project": self.project, "entries": entries}
|
||||||
|
|
||||||
|
for attempt in range(self.max_retries):
|
||||||
|
try:
|
||||||
|
resp = httpx.post(
|
||||||
|
url,
|
||||||
|
json=payload,
|
||||||
|
headers={"Authorization": f"Bearer {self.api_key}"},
|
||||||
|
timeout=self.timeout,
|
||||||
|
)
|
||||||
|
if resp.status_code == 201:
|
||||||
|
return
|
||||||
|
elif resp.status_code == 401:
|
||||||
|
logger.error("LogHive: Invalid API key — dropping batch")
|
||||||
|
return
|
||||||
|
else:
|
||||||
|
logger.warning(
|
||||||
|
"LogHive: HTTP %d (attempt %d/%d)",
|
||||||
|
resp.status_code,
|
||||||
|
attempt + 1,
|
||||||
|
self.max_retries,
|
||||||
|
)
|
||||||
|
except httpx.RequestError as e:
|
||||||
|
logger.warning(
|
||||||
|
"LogHive: Connection error (attempt %d/%d): %s",
|
||||||
|
attempt + 1,
|
||||||
|
self.max_retries,
|
||||||
|
e,
|
||||||
|
)
|
||||||
|
|
||||||
|
if attempt < self.max_retries - 1:
|
||||||
|
time.sleep(2 ** attempt)
|
||||||
|
|
||||||
|
logger.error("LogHive: Failed to send %d entries after %d retries", len(entries), self.max_retries)
|
||||||
|
|
||||||
|
def _enqueue(self, level: str, message: str, **kwargs):
|
||||||
|
"""Enqueue a log entry for async sending."""
|
||||||
|
entry = {
|
||||||
|
"timestamp": datetime.now(timezone.utc).isoformat(),
|
||||||
|
"level": level,
|
||||||
|
"message": message,
|
||||||
|
"logger": kwargs.pop("logger", None) or __name__,
|
||||||
|
"module": kwargs.pop("module", None),
|
||||||
|
"function": kwargs.pop("function", None),
|
||||||
|
"line_no": kwargs.pop("line_no", None),
|
||||||
|
"trace_id": kwargs.pop("trace_id", None),
|
||||||
|
"extra": kwargs,
|
||||||
|
}
|
||||||
|
|
||||||
|
# Handle exception info
|
||||||
|
exc_info = kwargs.pop("exc_info", None)
|
||||||
|
if exc_info:
|
||||||
|
if isinstance(exc_info, BaseException):
|
||||||
|
entry["exception"] = "".join(
|
||||||
|
traceback.format_exception(type(exc_info), exc_info, exc_info.__traceback__)
|
||||||
|
)
|
||||||
|
elif exc_info is True:
|
||||||
|
entry["exception"] = traceback.format_exc()
|
||||||
|
|
||||||
|
self._queue.put_nowait(entry)
|
||||||
|
|
||||||
|
# ── Public API (matching standard logging levels) ──────────
|
||||||
|
|
||||||
|
def debug(self, message: str, **kwargs):
|
||||||
|
self._enqueue("debug", message, **kwargs)
|
||||||
|
|
||||||
|
def info(self, message: str, **kwargs):
|
||||||
|
self._enqueue("info", message, **kwargs)
|
||||||
|
|
||||||
|
def warning(self, message: str, **kwargs):
|
||||||
|
self._enqueue("warning", message, **kwargs)
|
||||||
|
|
||||||
|
def error(self, message: str, **kwargs):
|
||||||
|
self._enqueue("error", message, **kwargs)
|
||||||
|
|
||||||
|
def critical(self, message: str, **kwargs):
|
||||||
|
self._enqueue("critical", message, **kwargs)
|
||||||
|
|
||||||
|
def log(self, level: str, message: str, **kwargs):
|
||||||
|
"""Log a message with an explicit level string."""
|
||||||
|
self._enqueue(level, message, **kwargs)
|
||||||
|
|
||||||
|
def set_trace_id(self, trace_id: str):
|
||||||
|
"""Set a trace_id for request correlation (used in web frameworks)."""
|
||||||
|
self._current_trace_id = trace_id
|
||||||
|
|
||||||
|
def __del__(self):
|
||||||
|
self.stop(flush=True)
|
||||||
@@ -0,0 +1,72 @@
|
|||||||
|
"""Python logging.Handler integration — use LogHive with the stdlib logging module.
|
||||||
|
|
||||||
|
This allows you to replace or augment your existing logging setup with
|
||||||
|
zero code changes (just add a handler to your logger).
|
||||||
|
"""
|
||||||
|
|
||||||
|
import logging
|
||||||
|
from typing import Optional
|
||||||
|
|
||||||
|
from loghive_client.client import LogHiveLogger
|
||||||
|
|
||||||
|
|
||||||
|
class LogHiveHandler(logging.Handler):
|
||||||
|
"""A logging.Handler that sends records to LogHive.
|
||||||
|
|
||||||
|
Use it with Python's standard logging module:
|
||||||
|
import logging
|
||||||
|
from loghive_client import LogHiveHandler
|
||||||
|
|
||||||
|
handler = LogHiveHandler("my-project", "api-key", "http://localhost:8000")
|
||||||
|
logging.getLogger().addHandler(handler)
|
||||||
|
|
||||||
|
All existing logger calls (logger.info, logger.error, etc.) will
|
||||||
|
automatically forward to LogHive.
|
||||||
|
"""
|
||||||
|
|
||||||
|
LEVEL_MAP = {
|
||||||
|
logging.DEBUG: "debug",
|
||||||
|
logging.INFO: "info",
|
||||||
|
logging.WARNING: "warning",
|
||||||
|
logging.ERROR: "error",
|
||||||
|
logging.CRITICAL: "critical",
|
||||||
|
}
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
project: str,
|
||||||
|
api_key: str,
|
||||||
|
endpoint: str = "http://localhost:8000",
|
||||||
|
level: int = logging.INFO,
|
||||||
|
):
|
||||||
|
super().__init__(level=level)
|
||||||
|
self._client = LogHiveLogger(
|
||||||
|
project=project,
|
||||||
|
api_key=api_key,
|
||||||
|
endpoint=endpoint,
|
||||||
|
)
|
||||||
|
|
||||||
|
def emit(self, record: logging.LogRecord):
|
||||||
|
"""Send a log record to LogHive."""
|
||||||
|
try:
|
||||||
|
level = self.LEVEL_MAP.get(record.levelno, "info")
|
||||||
|
extra = {
|
||||||
|
"logger": record.name,
|
||||||
|
"module": record.module,
|
||||||
|
"function": record.funcName,
|
||||||
|
"line_no": record.lineno,
|
||||||
|
}
|
||||||
|
if record.exc_info and record.exc_info[0]:
|
||||||
|
import traceback
|
||||||
|
extra["exception"] = "".join(
|
||||||
|
traceback.format_exception(*record.exc_info)
|
||||||
|
)
|
||||||
|
|
||||||
|
self._client._enqueue(level, record.getMessage(), **extra)
|
||||||
|
except Exception:
|
||||||
|
self.handleError(record)
|
||||||
|
|
||||||
|
def close(self):
|
||||||
|
"""Flush and close."""
|
||||||
|
self._client.stop(flush=True)
|
||||||
|
super().close()
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
"""Setup script for loghive-client."""
|
||||||
|
|
||||||
|
from setuptools import setup, find_packages
|
||||||
|
|
||||||
|
setup(
|
||||||
|
name="loghive-client",
|
||||||
|
version="0.1.0",
|
||||||
|
description="LogHive client SDK — push logs from your Python projects to LogHive",
|
||||||
|
author="LogHive",
|
||||||
|
packages=find_packages(),
|
||||||
|
install_requires=[
|
||||||
|
"httpx>=0.27.0",
|
||||||
|
],
|
||||||
|
python_requires=">=3.10",
|
||||||
|
classifiers=[
|
||||||
|
"Development Status :: 3 - Alpha",
|
||||||
|
"Intended Audience :: Developers",
|
||||||
|
"Programming Language :: Python :: 3",
|
||||||
|
"Programming Language :: Python :: 3.10",
|
||||||
|
"Programming Language :: Python :: 3.11",
|
||||||
|
"Programming Language :: Python :: 3.12",
|
||||||
|
],
|
||||||
|
)
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
services:
|
||||||
|
# ── LogHive Backend API ───────────────────────────────────
|
||||||
|
backend:
|
||||||
|
build:
|
||||||
|
context: ./backend
|
||||||
|
dockerfile: Dockerfile
|
||||||
|
ports:
|
||||||
|
- "8000:8000"
|
||||||
|
env_file:
|
||||||
|
- .env
|
||||||
|
|
||||||
|
# ── Celery Worker ─────────────────────────────────────────
|
||||||
|
celery_worker:
|
||||||
|
build:
|
||||||
|
context: ./backend
|
||||||
|
dockerfile: Dockerfile
|
||||||
|
command: celery -A celery_worker.celery_app worker --loglevel=info
|
||||||
|
env_file:
|
||||||
|
- .env
|
||||||
|
depends_on:
|
||||||
|
- backend
|
||||||
|
|
||||||
|
# ── Celery Beat (periodic tasks) ──────────────────────────
|
||||||
|
celery_beat:
|
||||||
|
build:
|
||||||
|
context: ./backend
|
||||||
|
dockerfile: Dockerfile
|
||||||
|
command: celery -A celery_worker.celery_app beat --loglevel=info
|
||||||
|
env_file:
|
||||||
|
- .env
|
||||||
|
depends_on:
|
||||||
|
- backend
|
||||||
|
|
||||||
|
# ── LogHive Frontend (Vue 3) ──────────────────────────────
|
||||||
|
frontend:
|
||||||
|
build:
|
||||||
|
context: ./frontend
|
||||||
|
dockerfile: Dockerfile
|
||||||
|
ports:
|
||||||
|
- "3000:80"
|
||||||
|
depends_on:
|
||||||
|
- backend
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
# ── Build Stage ──
|
||||||
|
FROM node:20-alpine AS builder
|
||||||
|
|
||||||
|
WORKDIR /app
|
||||||
|
|
||||||
|
COPY package.json ./
|
||||||
|
RUN npm install
|
||||||
|
|
||||||
|
COPY . .
|
||||||
|
RUN npm run build
|
||||||
|
|
||||||
|
# ── Production Stage (nginx) ──
|
||||||
|
FROM nginx:stable-alpine
|
||||||
|
|
||||||
|
COPY --from=builder /app/dist /usr/share/nginx/html
|
||||||
|
COPY nginx.conf /etc/nginx/conf.d/default.conf
|
||||||
|
|
||||||
|
EXPOSE 80
|
||||||
|
|
||||||
|
CMD ["nginx", "-g", "daemon off;"]
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="zh-CN">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8" />
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||||
|
<title>LogHive — 日志管理系统</title>
|
||||||
|
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div id="app"></div>
|
||||||
|
<script type="module" src="/src/main.js"></script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
server {
|
||||||
|
listen 80;
|
||||||
|
server_name localhost;
|
||||||
|
|
||||||
|
root /usr/share/nginx/html;
|
||||||
|
index index.html;
|
||||||
|
|
||||||
|
# Vue SPA — serve index.html for all routes
|
||||||
|
location / {
|
||||||
|
try_files $uri $uri/ /index.html;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Proxy API requests to the backend
|
||||||
|
location /api/ {
|
||||||
|
proxy_pass http://backend:8000;
|
||||||
|
proxy_set_header Host $host;
|
||||||
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
|
proxy_set_header X-Forwarded-Proto $scheme;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
{
|
||||||
|
"name": "loghive-frontend",
|
||||||
|
"version": "0.1.0",
|
||||||
|
"private": true,
|
||||||
|
"type": "module",
|
||||||
|
"scripts": {
|
||||||
|
"dev": "vite",
|
||||||
|
"build": "vite build",
|
||||||
|
"preview": "vite preview"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"vue": "^3.4.0",
|
||||||
|
"vue-router": "^4.3.0",
|
||||||
|
"pinia": "^2.1.0",
|
||||||
|
"axios": "^1.7.0",
|
||||||
|
"echarts": "^5.5.0",
|
||||||
|
"vue-echarts": "^6.7.0",
|
||||||
|
"element-plus": "^2.7.0",
|
||||||
|
"@element-plus/icons-vue": "^2.3.0"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@vitejs/plugin-vue": "^5.0.0",
|
||||||
|
"vite": "^5.2.0"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64">
|
||||||
|
<circle cx="32" cy="32" r="30" fill="#f0c040"/>
|
||||||
|
<text x="32" y="42" text-anchor="middle" font-size="36" font-family="Arial" fill="#333">H</text>
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 217 B |
@@ -0,0 +1,69 @@
|
|||||||
|
<template>
|
||||||
|
<el-container style="height: 100vh">
|
||||||
|
<el-aside width="220px" style="background: #1d1e1f; color: #fff">
|
||||||
|
<div class="sidebar-header">
|
||||||
|
<h2 style="margin: 0; padding: 20px; font-size: 20px">🐝 LogHive</h2>
|
||||||
|
</div>
|
||||||
|
<el-menu
|
||||||
|
:default-active="route.path"
|
||||||
|
router
|
||||||
|
background-color="#1d1e1f"
|
||||||
|
text-color="#bfcbd9"
|
||||||
|
active-text-color="#409eff"
|
||||||
|
>
|
||||||
|
<el-menu-item index="/">
|
||||||
|
<el-icon><DataAnalysis /></el-icon>
|
||||||
|
<span>仪表盘</span>
|
||||||
|
</el-menu-item>
|
||||||
|
<el-menu-item index="/logs">
|
||||||
|
<el-icon><Search /></el-icon>
|
||||||
|
<span>日志检索</span>
|
||||||
|
</el-menu-item>
|
||||||
|
<el-menu-item index="/projects">
|
||||||
|
<el-icon><Setting /></el-icon>
|
||||||
|
<span>项目管理</span>
|
||||||
|
</el-menu-item>
|
||||||
|
<el-menu-item index="/alerts">
|
||||||
|
<el-icon><WarningFilled /></el-icon>
|
||||||
|
<span>告警中心</span>
|
||||||
|
</el-menu-item>
|
||||||
|
</el-menu>
|
||||||
|
</el-aside>
|
||||||
|
|
||||||
|
<el-container>
|
||||||
|
<el-header style="background: #fff; border-bottom: 1px solid #e4e7ed; display: flex; align-items: center; justify-content: space-between; padding: 0 20px">
|
||||||
|
<el-breadcrumb>
|
||||||
|
<el-breadcrumb-item :to="{ path: '/' }">LogHive</el-breadcrumb-item>
|
||||||
|
<el-breadcrumb-item v-if="route.path === '/logs'">日志检索</el-breadcrumb-item>
|
||||||
|
<el-breadcrumb-item v-if="route.path === '/projects'">项目管理</el-breadcrumb-item>
|
||||||
|
<el-breadcrumb-item v-if="route.path === '/alerts'">告警中心</el-breadcrumb-item>
|
||||||
|
</el-breadcrumb>
|
||||||
|
<div style="font-size: 14px; color: #909399">
|
||||||
|
LogHive v0.1.0
|
||||||
|
</div>
|
||||||
|
</el-header>
|
||||||
|
|
||||||
|
<el-main style="background: #f5f7fa">
|
||||||
|
<router-view />
|
||||||
|
</el-main>
|
||||||
|
</el-container>
|
||||||
|
</el-container>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup>
|
||||||
|
import { useRoute } from 'vue-router'
|
||||||
|
const route = useRoute()
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<style>
|
||||||
|
body {
|
||||||
|
margin: 0;
|
||||||
|
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
|
||||||
|
}
|
||||||
|
.el-menu {
|
||||||
|
border-right: none !important;
|
||||||
|
}
|
||||||
|
.sidebar-header {
|
||||||
|
border-bottom: 1px solid #333;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,92 @@
|
|||||||
|
import axios from 'axios'
|
||||||
|
|
||||||
|
const api = axios.create({
|
||||||
|
baseURL: '/api',
|
||||||
|
timeout: 10000,
|
||||||
|
})
|
||||||
|
|
||||||
|
// Response interceptor for error handling
|
||||||
|
api.interceptors.response.use(
|
||||||
|
(response) => response,
|
||||||
|
(error) => {
|
||||||
|
const msg = error.response?.data?.detail || error.message
|
||||||
|
console.error('API Error:', msg)
|
||||||
|
return Promise.reject(error)
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
// ── Dashboard ─────────────────────────────────────────────────
|
||||||
|
|
||||||
|
export function fetchDashboardStats(params) {
|
||||||
|
return api.get('/dashboard/stats', { params })
|
||||||
|
}
|
||||||
|
|
||||||
|
export function fetchTimeSeries(params) {
|
||||||
|
return api.get('/dashboard/timeseries', { params })
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Logs ──────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
export function searchLogs(params) {
|
||||||
|
return api.get('/logs/search', { params })
|
||||||
|
}
|
||||||
|
|
||||||
|
export function fetchLogStats(params) {
|
||||||
|
return api.get('/logs/stats', { params })
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Projects ──────────────────────────────────────────────────
|
||||||
|
|
||||||
|
export function listProjects() {
|
||||||
|
return api.get('/projects')
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getProject(id) {
|
||||||
|
return api.get(`/projects/${id}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function createProject(data) {
|
||||||
|
return api.post('/projects', data)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function updateProject(id, data) {
|
||||||
|
return api.patch(`/projects/${id}`, data)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function deleteProject(id) {
|
||||||
|
return api.delete(`/projects/${id}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function rotateApiKey(id) {
|
||||||
|
return api.post(`/projects/${id}/rotate-key`)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Alerts ────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
export function listAlertRules(params) {
|
||||||
|
return api.get('/alerts/rules', { params })
|
||||||
|
}
|
||||||
|
|
||||||
|
export function createAlertRule(data) {
|
||||||
|
return api.post('/alerts/rules', data)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function updateAlertRule(id, data) {
|
||||||
|
return api.patch(`/alerts/rules/${id}`, data)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function deleteAlertRule(id) {
|
||||||
|
return api.delete(`/alerts/rules/${id}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function listAlertHistory(params) {
|
||||||
|
return api.get('/alerts/history', { params })
|
||||||
|
}
|
||||||
|
|
||||||
|
export function acknowledgeAlert(id) {
|
||||||
|
return api.post(`/alerts/history/${id}/acknowledge`)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function healthCheck() {
|
||||||
|
return api.get('/health')
|
||||||
|
}
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
import { createApp } from 'vue'
|
||||||
|
import { createPinia } from 'pinia'
|
||||||
|
import ElementPlus from 'element-plus'
|
||||||
|
import 'element-plus/dist/index.css'
|
||||||
|
import * as ElementPlusIconsVue from '@element-plus/icons-vue'
|
||||||
|
|
||||||
|
import App from './App.vue'
|
||||||
|
import router from './router'
|
||||||
|
|
||||||
|
const app = createApp(App)
|
||||||
|
|
||||||
|
// Register all Element Plus icons
|
||||||
|
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
|
||||||
|
app.component(key, component)
|
||||||
|
}
|
||||||
|
|
||||||
|
app.use(createPinia())
|
||||||
|
app.use(router)
|
||||||
|
app.use(ElementPlus)
|
||||||
|
app.mount('#app')
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
import { createRouter, createWebHistory } from 'vue-router'
|
||||||
|
import DashboardView from '../views/DashboardView.vue'
|
||||||
|
import LogSearchView from '../views/LogSearchView.vue'
|
||||||
|
import ProjectManageView from '../views/ProjectManageView.vue'
|
||||||
|
import AlertManageView from '../views/AlertManageView.vue'
|
||||||
|
|
||||||
|
const routes = [
|
||||||
|
{ path: '/', name: 'dashboard', component: DashboardView },
|
||||||
|
{ path: '/logs', name: 'logs', component: LogSearchView },
|
||||||
|
{ path: '/projects', name: 'projects', component: ProjectManageView },
|
||||||
|
{ path: '/alerts', name: 'alerts', component: AlertManageView },
|
||||||
|
]
|
||||||
|
|
||||||
|
const router = createRouter({
|
||||||
|
history: createWebHistory(),
|
||||||
|
routes,
|
||||||
|
})
|
||||||
|
|
||||||
|
export default router
|
||||||
@@ -0,0 +1,272 @@
|
|||||||
|
<template>
|
||||||
|
<div class="alert-manage">
|
||||||
|
<h2 style="margin-bottom: 20px">🔔 告警中心</h2>
|
||||||
|
|
||||||
|
<!-- Tabs: Rules / History -->
|
||||||
|
<el-tabs v-model="activeTab">
|
||||||
|
<!-- ── Rules ── -->
|
||||||
|
<el-tab-pane label="告警规则" name="rules">
|
||||||
|
<div style="display: flex; justify-content: flex-end; margin-bottom: 16px">
|
||||||
|
<el-button type="primary" @click="showCreateRuleDialog" :icon="Plus">新建规则</el-button>
|
||||||
|
</div>
|
||||||
|
<el-card shadow="hover">
|
||||||
|
<el-table :data="rules" stripe style="width: 100%" v-loading="rulesLoading">
|
||||||
|
<el-table-column prop="name" label="规则名称" min-width="150" />
|
||||||
|
<el-table-column label="级别" width="100">
|
||||||
|
<template #default="{ row }">
|
||||||
|
<el-tag :type="row.level === 'critical' ? 'danger' : row.level === 'warning' ? 'warning' : 'info'" size="small">
|
||||||
|
{{ row.level?.toUpperCase() }}
|
||||||
|
</el-tag>
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
<el-table-column prop="field" label="字段" width="100" />
|
||||||
|
<el-table-column label="条件" width="150">
|
||||||
|
<template #default="{ row }">
|
||||||
|
{{ row.field }} {{ operatorLabel(row.operator) }} {{ row.threshold }}
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
<el-table-column label="时间窗口" width="120">
|
||||||
|
<template #default="{ row }">{{ row.window_minutes }} 分钟</template>
|
||||||
|
</el-table-column>
|
||||||
|
<el-table-column label="状态" width="90">
|
||||||
|
<template #default="{ row }">
|
||||||
|
<el-switch :model-value="row.is_enabled" @change="(v) => toggleRule(row, v)" />
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
<el-table-column prop="project_id" label="项目 ID" min-width="180" show-overflow-tooltip />
|
||||||
|
<el-table-column label="操作" width="160" fixed="right">
|
||||||
|
<template #default="{ row }">
|
||||||
|
<el-button size="small" @click="showEditRuleDialog(row)">编辑</el-button>
|
||||||
|
<el-button size="small" type="danger" @click="handleDeleteRule(row)">删除</el-button>
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
</el-table>
|
||||||
|
</el-card>
|
||||||
|
</el-tab-pane>
|
||||||
|
|
||||||
|
<!-- ── History ── -->
|
||||||
|
<el-tab-pane label="告警历史" name="history">
|
||||||
|
<el-card shadow="hover">
|
||||||
|
<el-table :data="history" stripe style="width: 100%" v-loading="historyLoading">
|
||||||
|
<el-table-column label="时间" width="170">
|
||||||
|
<template #default="{ row }">
|
||||||
|
{{ row.triggered_at?.substring(0, 19)?.replace('T', ' ') }}
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
<el-table-column label="级别" width="100">
|
||||||
|
<template #default="{ row }">
|
||||||
|
<el-tag :type="row.level === 'critical' ? 'danger' : 'warning'" size="small">
|
||||||
|
{{ row.level?.toUpperCase() }}
|
||||||
|
</el-tag>
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
<el-table-column label="消息" min-width="400" prop="message" show-overflow-tooltip />
|
||||||
|
<el-table-column label="触发值" width="100" prop="triggered_value" />
|
||||||
|
<el-table-column label="状态" width="100">
|
||||||
|
<template #default="{ row }">
|
||||||
|
<el-tag :type="row.is_acknowledged ? 'success' : 'danger'" size="small">
|
||||||
|
{{ row.is_acknowledged ? '已确认' : '未确认' }}
|
||||||
|
</el-tag>
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
<el-table-column label="操作" width="120">
|
||||||
|
<template #default="{ row }">
|
||||||
|
<el-button v-if="!row.is_acknowledged" size="small" type="primary" @click="handleAcknowledge(row)">确认</el-button>
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
</el-table>
|
||||||
|
</el-card>
|
||||||
|
</el-tab-pane>
|
||||||
|
</el-tabs>
|
||||||
|
|
||||||
|
<!-- Rule Dialog -->
|
||||||
|
<el-dialog v-model="ruleDialogVisible" :title="isEditingRule ? '编辑规则' : '新建规则'" width="550px">
|
||||||
|
<el-form :model="ruleForm" :rules="ruleRules" ref="ruleFormRef" label-width="120px">
|
||||||
|
<el-form-item label="规则名称" prop="name">
|
||||||
|
<el-input v-model="ruleForm.name" />
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="项目 ID" prop="project_id">
|
||||||
|
<el-input v-model="ruleForm.project_id" placeholder="输入项目 ID" />
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="告警级别" prop="level">
|
||||||
|
<el-select v-model="ruleForm.level" style="width: 100%">
|
||||||
|
<el-option label="INFO" value="info" />
|
||||||
|
<el-option label="WARNING" value="warning" />
|
||||||
|
<el-option label="CRITICAL" value="critical" />
|
||||||
|
</el-select>
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="字段" prop="field">
|
||||||
|
<el-input v-model="ruleForm.field" placeholder="如: level" />
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="条件" prop="operator">
|
||||||
|
<el-select v-model="ruleForm.operator" style="width: 120px">
|
||||||
|
<el-option label=">" value="gt" />
|
||||||
|
<el-option label=">=" value="gte" />
|
||||||
|
<el-option label="<" value="lt" />
|
||||||
|
<el-option label="<=" value="lte" />
|
||||||
|
<el-option label="=" value="eq" />
|
||||||
|
</el-select>
|
||||||
|
<el-input-number v-model="ruleForm.threshold" :min="0" style="margin-left: 10px" />
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="时间窗口(分)">
|
||||||
|
<el-input-number v-model="ruleForm.window_minutes" :min="1" :max="1440" />
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="通知渠道">
|
||||||
|
<el-checkbox-group v-model="ruleForm.notify_channels">
|
||||||
|
<el-checkbox label="feishu">飞书</el-checkbox>
|
||||||
|
<el-checkbox label="dingtalk">钉钉</el-checkbox>
|
||||||
|
</el-checkbox-group>
|
||||||
|
</el-form-item>
|
||||||
|
</el-form>
|
||||||
|
<template #footer>
|
||||||
|
<el-button @click="ruleDialogVisible = false">取消</el-button>
|
||||||
|
<el-button type="primary" @click="handleSubmitRule" :loading="ruleSubmitting">确定</el-button>
|
||||||
|
</template>
|
||||||
|
</el-dialog>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup>
|
||||||
|
import { ref, onMounted } from 'vue'
|
||||||
|
import { listAlertRules, createAlertRule, updateAlertRule, deleteAlertRule, listAlertHistory, acknowledgeAlert } from '../api'
|
||||||
|
import { Plus } from '@element-plus/icons-vue'
|
||||||
|
import { ElMessage, ElMessageBox } from 'element-plus'
|
||||||
|
|
||||||
|
const activeTab = ref('rules')
|
||||||
|
|
||||||
|
// Rules
|
||||||
|
const rules = ref([])
|
||||||
|
const rulesLoading = ref(false)
|
||||||
|
const ruleDialogVisible = ref(false)
|
||||||
|
const isEditingRule = ref(false)
|
||||||
|
const editRuleId = ref(null)
|
||||||
|
const ruleSubmitting = ref(false)
|
||||||
|
const ruleFormRef = ref(null)
|
||||||
|
const ruleForm = ref({
|
||||||
|
name: '',
|
||||||
|
project_id: '',
|
||||||
|
level: 'warning',
|
||||||
|
field: 'level',
|
||||||
|
operator: 'gte',
|
||||||
|
threshold: 10,
|
||||||
|
window_minutes: 5,
|
||||||
|
notify_channels: [],
|
||||||
|
})
|
||||||
|
const ruleRules = {
|
||||||
|
name: [{ required: true, message: '请输入规则名称', trigger: 'blur' }],
|
||||||
|
project_id: [{ required: true, message: '请输入项目 ID', trigger: 'blur' }],
|
||||||
|
}
|
||||||
|
|
||||||
|
// History
|
||||||
|
const history = ref([])
|
||||||
|
const historyLoading = ref(false)
|
||||||
|
|
||||||
|
function operatorLabel(op) {
|
||||||
|
const map = { gt: '>', gte: '>=', lt: '<', lte: '<=', eq: '=' }
|
||||||
|
return map[op] || op
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadRules() {
|
||||||
|
rulesLoading.value = true
|
||||||
|
try {
|
||||||
|
const res = await listAlertRules()
|
||||||
|
rules.value = res.data
|
||||||
|
} catch (e) {
|
||||||
|
console.error(e)
|
||||||
|
} finally {
|
||||||
|
rulesLoading.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadHistory() {
|
||||||
|
historyLoading.value = true
|
||||||
|
try {
|
||||||
|
const res = await listAlertHistory()
|
||||||
|
history.value = res.data
|
||||||
|
} catch (e) {
|
||||||
|
console.error(e)
|
||||||
|
} finally {
|
||||||
|
historyLoading.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function showCreateRuleDialog() {
|
||||||
|
isEditingRule.value = false
|
||||||
|
editRuleId.value = null
|
||||||
|
ruleForm.value = { name: '', project_id: '', level: 'warning', field: 'level', operator: 'gte', threshold: 10, window_minutes: 5, notify_channels: [] }
|
||||||
|
ruleDialogVisible.value = true
|
||||||
|
}
|
||||||
|
|
||||||
|
function showEditRuleDialog(row) {
|
||||||
|
isEditingRule.value = true
|
||||||
|
editRuleId.value = row.id
|
||||||
|
ruleForm.value = {
|
||||||
|
name: row.name,
|
||||||
|
project_id: row.project_id,
|
||||||
|
level: row.level,
|
||||||
|
field: row.field,
|
||||||
|
operator: row.operator,
|
||||||
|
threshold: row.threshold,
|
||||||
|
window_minutes: row.window_minutes,
|
||||||
|
notify_channels: row.notify_channels || [],
|
||||||
|
}
|
||||||
|
ruleDialogVisible.value = true
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleSubmitRule() {
|
||||||
|
const valid = await ruleFormRef.value.validate().catch(() => false)
|
||||||
|
if (!valid) return
|
||||||
|
|
||||||
|
ruleSubmitting.value = true
|
||||||
|
try {
|
||||||
|
if (isEditingRule.value) {
|
||||||
|
await updateAlertRule(editRuleId.value, ruleForm.value)
|
||||||
|
ElMessage.success('规则已更新')
|
||||||
|
} else {
|
||||||
|
await createAlertRule(ruleForm.value)
|
||||||
|
ElMessage.success('规则已创建')
|
||||||
|
}
|
||||||
|
ruleDialogVisible.value = false
|
||||||
|
await loadRules()
|
||||||
|
} catch (e) {
|
||||||
|
ElMessage.error(e.response?.data?.detail || '操作失败')
|
||||||
|
} finally {
|
||||||
|
ruleSubmitting.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleDeleteRule(row) {
|
||||||
|
try {
|
||||||
|
await ElMessageBox.confirm(`确定删除规则"${row.name}"?`, '确认删除', { type: 'warning' })
|
||||||
|
await deleteAlertRule(row.id)
|
||||||
|
ElMessage.success('规则已删除')
|
||||||
|
await loadRules()
|
||||||
|
} catch (e) {
|
||||||
|
if (e !== 'cancel') ElMessage.error('删除失败')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function toggleRule(row, enabled) {
|
||||||
|
try {
|
||||||
|
await updateAlertRule(row.id, { is_enabled: enabled })
|
||||||
|
ElMessage.success(enabled ? '规则已启用' : '规则已停用')
|
||||||
|
} catch (e) {
|
||||||
|
ElMessage.error('操作失败')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleAcknowledge(row) {
|
||||||
|
try {
|
||||||
|
await acknowledgeAlert(row.id)
|
||||||
|
ElMessage.success('已确认')
|
||||||
|
await loadHistory()
|
||||||
|
} catch (e) {
|
||||||
|
ElMessage.error('确认失败')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
onMounted(() => {
|
||||||
|
loadRules()
|
||||||
|
loadHistory()
|
||||||
|
})
|
||||||
|
</script>
|
||||||
@@ -0,0 +1,204 @@
|
|||||||
|
<template>
|
||||||
|
<div class="dashboard">
|
||||||
|
<h2 style="margin-bottom: 20px">📊 仪表盘</h2>
|
||||||
|
|
||||||
|
<!-- Stats Cards -->
|
||||||
|
<el-row :gutter="20" style="margin-bottom: 20px">
|
||||||
|
<el-col :span="6">
|
||||||
|
<el-card shadow="hover">
|
||||||
|
<div class="stat-card">
|
||||||
|
<div class="stat-label">总日志量</div>
|
||||||
|
<div class="stat-value">{{ stats.total_logs.toLocaleString() }}</div>
|
||||||
|
</div>
|
||||||
|
</el-card>
|
||||||
|
</el-col>
|
||||||
|
<el-col :span="6">
|
||||||
|
<el-card shadow="hover">
|
||||||
|
<div class="stat-card">
|
||||||
|
<div class="stat-label">错误数</div>
|
||||||
|
<div class="stat-value" style="color: #f56c6c">{{ stats.error_count.toLocaleString() }}</div>
|
||||||
|
</div>
|
||||||
|
</el-card>
|
||||||
|
</el-col>
|
||||||
|
<el-col :span="6">
|
||||||
|
<el-card shadow="hover">
|
||||||
|
<div class="stat-card">
|
||||||
|
<div class="stat-label">错误率</div>
|
||||||
|
<div class="stat-value" :style="{ color: stats.error_rate > 5 ? '#f56c6c' : '#67c23a' }">
|
||||||
|
{{ stats.error_rate }}%
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</el-card>
|
||||||
|
</el-col>
|
||||||
|
<el-col :span="6">
|
||||||
|
<el-card shadow="hover">
|
||||||
|
<div class="stat-card">
|
||||||
|
<div class="stat-label">项目数</div>
|
||||||
|
<div class="stat-value" style="color: #409eff">{{ projects.length }}</div>
|
||||||
|
</div>
|
||||||
|
</el-card>
|
||||||
|
</el-col>
|
||||||
|
</el-row>
|
||||||
|
|
||||||
|
<!-- Charts Row -->
|
||||||
|
<el-row :gutter="20" style="margin-bottom: 20px">
|
||||||
|
<el-col :span="16">
|
||||||
|
<el-card shadow="hover">
|
||||||
|
<template #header>
|
||||||
|
<span>📈 日志趋势(近24h)</span>
|
||||||
|
</template>
|
||||||
|
<div ref="trendChart" style="height: 300px"></div>
|
||||||
|
</el-card>
|
||||||
|
</el-col>
|
||||||
|
<el-col :span="8">
|
||||||
|
<el-card shadow="hover">
|
||||||
|
<template #header>
|
||||||
|
<span>🥧 日志级别分布</span>
|
||||||
|
</template>
|
||||||
|
<div ref="pieChart" style="height: 300px"></div>
|
||||||
|
</el-card>
|
||||||
|
</el-col>
|
||||||
|
</el-row>
|
||||||
|
|
||||||
|
<!-- Top Errors -->
|
||||||
|
<el-card shadow="hover">
|
||||||
|
<template #header>
|
||||||
|
<span>⚠️ 高频错误 TOP 10</span>
|
||||||
|
</template>
|
||||||
|
<el-table :data="stats.top_errors" stripe style="width: 100%" v-if="stats.top_errors.length">
|
||||||
|
<el-table-column prop="message" label="错误消息" min-width="500">
|
||||||
|
<template #default="{ row }">
|
||||||
|
<el-tooltip :content="row.message" placement="top">
|
||||||
|
<span class="error-msg">{{ row.message }}</span>
|
||||||
|
</el-tooltip>
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
<el-table-column prop="count" label="出现次数" width="120" align="right" sortable />
|
||||||
|
</el-table>
|
||||||
|
<el-empty v-else description="暂无错误数据" />
|
||||||
|
</el-card>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup>
|
||||||
|
import { ref, onMounted, nextTick, watch } from 'vue'
|
||||||
|
import { fetchDashboardStats, fetchTimeSeries, listProjects } from '../api'
|
||||||
|
import * as echarts from 'echarts'
|
||||||
|
|
||||||
|
const stats = ref({
|
||||||
|
total_logs: 0,
|
||||||
|
error_count: 0,
|
||||||
|
error_rate: 0,
|
||||||
|
level_breakdown: {},
|
||||||
|
top_errors: [],
|
||||||
|
})
|
||||||
|
const projects = ref([])
|
||||||
|
const trendChart = ref(null)
|
||||||
|
const pieChart = ref(null)
|
||||||
|
|
||||||
|
async function loadData() {
|
||||||
|
try {
|
||||||
|
const [statsRes, tsRes, projRes] = await Promise.all([
|
||||||
|
fetchDashboardStats(),
|
||||||
|
fetchTimeSeries(),
|
||||||
|
listProjects(),
|
||||||
|
])
|
||||||
|
stats.value = statsRes.data
|
||||||
|
projects.value = projRes.data
|
||||||
|
renderCharts(tsRes.data)
|
||||||
|
} catch (e) {
|
||||||
|
console.error('Failed to load dashboard data', e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderCharts(timeSeries) {
|
||||||
|
nextTick(() => {
|
||||||
|
// Trend chart
|
||||||
|
if (trendChart.value) {
|
||||||
|
const chart = echarts.init(trendChart.value)
|
||||||
|
chart.setOption({
|
||||||
|
tooltip: { trigger: 'axis' },
|
||||||
|
legend: { data: ['总计', 'error', 'warning'] },
|
||||||
|
grid: { left: 40, right: 20, bottom: 30 },
|
||||||
|
xAxis: {
|
||||||
|
type: 'category',
|
||||||
|
data: timeSeries.map((t) => t.timestamp?.substring(11, 16) || ''),
|
||||||
|
axisLabel: { rotate: 45 },
|
||||||
|
},
|
||||||
|
yAxis: { type: 'value' },
|
||||||
|
series: [
|
||||||
|
{
|
||||||
|
name: '总计',
|
||||||
|
type: 'line',
|
||||||
|
data: timeSeries.map((t) => t.total || 0),
|
||||||
|
smooth: true,
|
||||||
|
lineStyle: { color: '#409eff' },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'error',
|
||||||
|
type: 'line',
|
||||||
|
data: timeSeries.map((t) => t.levels?.error || 0),
|
||||||
|
smooth: true,
|
||||||
|
lineStyle: { color: '#f56c6c' },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'warning',
|
||||||
|
type: 'line',
|
||||||
|
data: timeSeries.map((t) => t.levels?.warning || 0),
|
||||||
|
smooth: true,
|
||||||
|
lineStyle: { color: '#e6a23c' },
|
||||||
|
},
|
||||||
|
],
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// Pie chart
|
||||||
|
if (pieChart.value) {
|
||||||
|
const chart = echarts.init(pieChart.value)
|
||||||
|
const levels = stats.value.level_breakdown || {}
|
||||||
|
const colors = { debug: '#909399', info: '#409eff', warning: '#e6a23c', error: '#f56c6c', critical: '#f56c6c' }
|
||||||
|
chart.setOption({
|
||||||
|
tooltip: { trigger: 'item', formatter: '{b}: {c} ({d}%)' },
|
||||||
|
series: [
|
||||||
|
{
|
||||||
|
type: 'pie',
|
||||||
|
radius: ['40%', '70%'],
|
||||||
|
center: ['50%', '50%'],
|
||||||
|
data: Object.entries(levels).map(([name, value]) => ({
|
||||||
|
name,
|
||||||
|
value,
|
||||||
|
itemStyle: { color: colors[name] || '#909399' },
|
||||||
|
})),
|
||||||
|
label: { formatter: '{b}\n{d}%' },
|
||||||
|
},
|
||||||
|
],
|
||||||
|
})
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
onMounted(loadData)
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.stat-card {
|
||||||
|
text-align: center;
|
||||||
|
padding: 10px 0;
|
||||||
|
}
|
||||||
|
.stat-label {
|
||||||
|
font-size: 14px;
|
||||||
|
color: #909399;
|
||||||
|
margin-bottom: 8px;
|
||||||
|
}
|
||||||
|
.stat-value {
|
||||||
|
font-size: 28px;
|
||||||
|
font-weight: bold;
|
||||||
|
}
|
||||||
|
.error-msg {
|
||||||
|
display: inline-block;
|
||||||
|
max-width: 480px;
|
||||||
|
overflow: hidden;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,222 @@
|
|||||||
|
<template>
|
||||||
|
<div class="log-search">
|
||||||
|
<h2 style="margin-bottom: 20px">🔍 日志检索</h2>
|
||||||
|
|
||||||
|
<!-- Search Filters -->
|
||||||
|
<el-card shadow="hover" style="margin-bottom: 20px">
|
||||||
|
<el-form :model="filters" inline>
|
||||||
|
<el-form-item label="项目">
|
||||||
|
<el-select v-model="filters.project" placeholder="全部项目" clearable style="width: 160px">
|
||||||
|
<el-option v-for="p in projects" :key="p.name" :label="p.name" :value="p.name" />
|
||||||
|
</el-select>
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="级别">
|
||||||
|
<el-select v-model="filters.level" placeholder="全部级别" clearable style="width: 120px">
|
||||||
|
<el-option label="DEBUG" value="debug" />
|
||||||
|
<el-option label="INFO" value="info" />
|
||||||
|
<el-option label="WARNING" value="warning" />
|
||||||
|
<el-option label="ERROR" value="error" />
|
||||||
|
<el-option label="CRITICAL" value="critical" />
|
||||||
|
</el-select>
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="关键词">
|
||||||
|
<el-input v-model="filters.query" placeholder="搜索消息内容..." clearable style="width: 250px" />
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="Trace ID">
|
||||||
|
<el-input v-model="filters.trace_id" placeholder="按 trace ID 过滤" clearable style="width: 200px" />
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="时间">
|
||||||
|
<el-date-picker
|
||||||
|
v-model="timeRange"
|
||||||
|
type="datetimerange"
|
||||||
|
range-separator="至"
|
||||||
|
start-placeholder="开始时间"
|
||||||
|
end-placeholder="结束时间"
|
||||||
|
format="YYYY-MM-DD HH:mm:ss"
|
||||||
|
value-format="YYYY-MM-DDTHH:mm:ss"
|
||||||
|
style="width: 360px"
|
||||||
|
/>
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item>
|
||||||
|
<el-button type="primary" @click="doSearch" :icon="Search">搜索</el-button>
|
||||||
|
<el-button @click="resetFilters">重置</el-button>
|
||||||
|
</el-form-item>
|
||||||
|
</el-form>
|
||||||
|
</el-card>
|
||||||
|
|
||||||
|
<!-- Stats Summary -->
|
||||||
|
<el-card shadow="hover" style="margin-bottom: 20px">
|
||||||
|
<el-row :gutter="20">
|
||||||
|
<el-col :span="8">
|
||||||
|
<div class="stat-item">
|
||||||
|
<span class="stat-label">匹配总数</span>
|
||||||
|
<span class="stat-value">{{ result.total }}</span>
|
||||||
|
</div>
|
||||||
|
</el-col>
|
||||||
|
<el-col :span="8">
|
||||||
|
<div class="stat-item">
|
||||||
|
<span class="stat-label">当前页</span>
|
||||||
|
<span class="stat-value">{{ result.page }} / {{ totalPages }}</span>
|
||||||
|
</div>
|
||||||
|
</el-col>
|
||||||
|
<el-col :span="8">
|
||||||
|
<div class="stat-item">
|
||||||
|
<span class="stat-label">每页</span>
|
||||||
|
<el-select v-model="filters.page_size" style="width: 80px" @change="doSearch">
|
||||||
|
<el-option label="20" :value="20" />
|
||||||
|
<el-option label="50" :value="50" />
|
||||||
|
<el-option label="100" :value="100" />
|
||||||
|
</el-select>
|
||||||
|
</div>
|
||||||
|
</el-col>
|
||||||
|
</el-row>
|
||||||
|
</el-card>
|
||||||
|
|
||||||
|
<!-- Log Results -->
|
||||||
|
<el-card shadow="hover">
|
||||||
|
<el-table :data="result.hits" stripe style="width: 100%" v-loading="loading" @row-click="showDetail">
|
||||||
|
<el-table-column label="时间" width="180">
|
||||||
|
<template #default="{ row }">
|
||||||
|
{{ row['timestamp']?.substring(0, 19)?.replace('T', ' ') || '-' }}
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
<el-table-column label="级别" width="90">
|
||||||
|
<template #default="{ row }">
|
||||||
|
<el-tag :type="levelTag(row.level)" size="small" effect="dark">
|
||||||
|
{{ row.level?.toUpperCase() }}
|
||||||
|
</el-tag>
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
<el-table-column label="项目" width="130" prop="project_name" />
|
||||||
|
<el-table-column label="Logger" width="150" prop="logger" />
|
||||||
|
<el-table-column label="消息" min-width="300">
|
||||||
|
<template #default="{ row }">
|
||||||
|
<span class="log-message">{{ row.message }}</span>
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
<el-table-column label="Trace ID" width="160" prop="trace_id" />
|
||||||
|
</el-table>
|
||||||
|
|
||||||
|
<!-- Pagination -->
|
||||||
|
<div style="margin-top: 16px; display: flex; justify-content: center">
|
||||||
|
<el-pagination
|
||||||
|
v-model:current-page="filters.page"
|
||||||
|
:page-size="filters.page_size"
|
||||||
|
:total="result.total"
|
||||||
|
layout="prev, pager, next"
|
||||||
|
@current-change="doSearch"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</el-card>
|
||||||
|
|
||||||
|
<!-- Log Detail Dialog -->
|
||||||
|
<el-dialog v-model="detailVisible" title="日志详情" width="700px" top="5vh">
|
||||||
|
<pre class="log-detail">{{ JSON.stringify(selectedLog, null, 2) }}</pre>
|
||||||
|
</el-dialog>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup>
|
||||||
|
import { ref, computed, onMounted } from 'vue'
|
||||||
|
import { searchLogs, listProjects } from '../api'
|
||||||
|
import { Search } from '@element-plus/icons-vue'
|
||||||
|
|
||||||
|
const filters = ref({
|
||||||
|
project: null,
|
||||||
|
level: null,
|
||||||
|
query: '',
|
||||||
|
trace_id: '',
|
||||||
|
page: 1,
|
||||||
|
page_size: 50,
|
||||||
|
sort_by: 'timestamp',
|
||||||
|
sort_order: 'desc',
|
||||||
|
})
|
||||||
|
const timeRange = ref(null)
|
||||||
|
const result = ref({ total: 0, page: 1, page_size: 50, hits: [] })
|
||||||
|
const projects = ref([])
|
||||||
|
const loading = ref(false)
|
||||||
|
const detailVisible = ref(false)
|
||||||
|
const selectedLog = ref(null)
|
||||||
|
|
||||||
|
const totalPages = computed(() => Math.max(1, Math.ceil(result.value.total / filters.value.page_size)))
|
||||||
|
|
||||||
|
function levelTag(level) {
|
||||||
|
const map = { debug: 'info', info: 'primary', warning: 'warning', error: 'danger', critical: 'danger' }
|
||||||
|
return map[level] || 'info'
|
||||||
|
}
|
||||||
|
|
||||||
|
async function doSearch() {
|
||||||
|
loading.value = true
|
||||||
|
try {
|
||||||
|
const params = { ...filters.value }
|
||||||
|
if (timeRange.value) {
|
||||||
|
params.start_time = timeRange.value[0]
|
||||||
|
params.end_time = timeRange.value[1]
|
||||||
|
}
|
||||||
|
// Remove null/empty values
|
||||||
|
Object.keys(params).forEach((k) => {
|
||||||
|
if (params[k] === null || params[k] === '' || params[k] === undefined) delete params[k]
|
||||||
|
})
|
||||||
|
const res = await searchLogs(params)
|
||||||
|
result.value = res.data
|
||||||
|
} catch (e) {
|
||||||
|
console.error('Search failed', e)
|
||||||
|
} finally {
|
||||||
|
loading.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function resetFilters() {
|
||||||
|
filters.value = { project: null, level: null, query: '', trace_id: '', page: 1, page_size: 50, sort_by: 'timestamp', sort_order: 'desc' }
|
||||||
|
timeRange.value = null
|
||||||
|
doSearch()
|
||||||
|
}
|
||||||
|
|
||||||
|
function showDetail(row) {
|
||||||
|
selectedLog.value = row
|
||||||
|
detailVisible.value = true
|
||||||
|
}
|
||||||
|
|
||||||
|
onMounted(async () => {
|
||||||
|
try {
|
||||||
|
const res = await listProjects()
|
||||||
|
projects.value = res.data
|
||||||
|
} catch (e) {
|
||||||
|
// ignore
|
||||||
|
}
|
||||||
|
doSearch()
|
||||||
|
})
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.stat-item {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 8px;
|
||||||
|
}
|
||||||
|
.stat-label {
|
||||||
|
font-size: 14px;
|
||||||
|
color: #909399;
|
||||||
|
}
|
||||||
|
.stat-value {
|
||||||
|
font-size: 16px;
|
||||||
|
font-weight: bold;
|
||||||
|
}
|
||||||
|
.log-message {
|
||||||
|
display: inline-block;
|
||||||
|
max-width: 500px;
|
||||||
|
overflow: hidden;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
.log-detail {
|
||||||
|
background: #f5f7fa;
|
||||||
|
padding: 16px;
|
||||||
|
border-radius: 4px;
|
||||||
|
font-size: 13px;
|
||||||
|
overflow: auto;
|
||||||
|
max-height: 60vh;
|
||||||
|
white-space: pre-wrap;
|
||||||
|
word-break: break-all;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,179 @@
|
|||||||
|
<template>
|
||||||
|
<div class="project-manage">
|
||||||
|
<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px">
|
||||||
|
<h2 style="margin: 0">⚙️ 项目管理</h2>
|
||||||
|
<el-button type="primary" @click="showCreateDialog" :icon="Plus">新建项目</el-button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<el-card shadow="hover">
|
||||||
|
<el-table :data="projects" stripe style="width: 100%" v-loading="loading">
|
||||||
|
<el-table-column prop="name" label="项目名称" min-width="150" />
|
||||||
|
<el-table-column prop="description" label="描述" min-width="250" show-overflow-tooltip />
|
||||||
|
<el-table-column label="状态" width="100">
|
||||||
|
<template #default="{ row }">
|
||||||
|
<el-tag :type="row.is_active ? 'success' : 'danger'" size="small">
|
||||||
|
{{ row.is_active ? '启用' : '停用' }}
|
||||||
|
</el-tag>
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
<el-table-column label="创建时间" width="170">
|
||||||
|
<template #default="{ row }">
|
||||||
|
{{ row.created_at?.substring(0, 19)?.replace('T', ' ') }}
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
<el-table-column label="API Key" width="200">
|
||||||
|
<template #default="{ row }">
|
||||||
|
<el-input :model-value="row.api_key || '••••••••'" readonly size="small" style="width: 140px">
|
||||||
|
<template #suffix>
|
||||||
|
<el-icon style="cursor: pointer" @click="copyKey(row)"><CopyDocument /></el-icon>
|
||||||
|
</template>
|
||||||
|
</el-input>
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
<el-table-column label="操作" width="240" fixed="right">
|
||||||
|
<template #default="{ row }">
|
||||||
|
<el-button size="small" @click="showEditDialog(row)">编辑</el-button>
|
||||||
|
<el-button size="small" type="warning" @click="handleRotateKey(row)">重置密钥</el-button>
|
||||||
|
<el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
</el-table>
|
||||||
|
</el-card>
|
||||||
|
|
||||||
|
<!-- Create/Edit Dialog -->
|
||||||
|
<el-dialog v-model="dialogVisible" :title="isEditing ? '编辑项目' : '新建项目'" width="500px">
|
||||||
|
<el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
|
||||||
|
<el-form-item label="项目名称" prop="name">
|
||||||
|
<el-input v-model="form.name" placeholder="输入项目名称" />
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="描述" prop="description">
|
||||||
|
<el-input v-model="form.description" type="textarea" :rows="3" placeholder="项目描述(可选)" />
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="启用" v-if="isEditing">
|
||||||
|
<el-switch v-model="form.is_active" />
|
||||||
|
</el-form-item>
|
||||||
|
</el-form>
|
||||||
|
<template #footer>
|
||||||
|
<el-button @click="dialogVisible = false">取消</el-button>
|
||||||
|
<el-button type="primary" @click="handleSubmit" :loading="submitting">确定</el-button>
|
||||||
|
</template>
|
||||||
|
</el-dialog>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup>
|
||||||
|
import { ref, onMounted } from 'vue'
|
||||||
|
import { listProjects, createProject, updateProject, deleteProject, rotateApiKey } from '../api'
|
||||||
|
import { Plus, CopyDocument } from '@element-plus/icons-vue'
|
||||||
|
import { ElMessage, ElMessageBox } from 'element-plus'
|
||||||
|
|
||||||
|
const projects = ref([])
|
||||||
|
const loading = ref(false)
|
||||||
|
const dialogVisible = ref(false)
|
||||||
|
const isEditing = ref(false)
|
||||||
|
const submitting = ref(false)
|
||||||
|
const editId = ref(null)
|
||||||
|
const formRef = ref(null)
|
||||||
|
const form = ref({ name: '', description: '', is_active: true })
|
||||||
|
const rules = {
|
||||||
|
name: [{ required: true, message: '请输入项目名称', trigger: 'blur' }],
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadProjects() {
|
||||||
|
loading.value = true
|
||||||
|
try {
|
||||||
|
const res = await listProjects()
|
||||||
|
projects.value = res.data
|
||||||
|
} catch (e) {
|
||||||
|
console.error(e)
|
||||||
|
} finally {
|
||||||
|
loading.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function showCreateDialog() {
|
||||||
|
isEditing.value = false
|
||||||
|
editId.value = null
|
||||||
|
form.value = { name: '', description: '', is_active: true }
|
||||||
|
dialogVisible.value = true
|
||||||
|
}
|
||||||
|
|
||||||
|
function showEditDialog(row) {
|
||||||
|
isEditing.value = true
|
||||||
|
editId.value = row.id
|
||||||
|
form.value = { name: row.name, description: row.description || '', is_active: row.is_active }
|
||||||
|
dialogVisible.value = true
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleSubmit() {
|
||||||
|
const valid = await formRef.value.validate().catch(() => false)
|
||||||
|
if (!valid) return
|
||||||
|
|
||||||
|
submitting.value = true
|
||||||
|
try {
|
||||||
|
if (isEditing.value) {
|
||||||
|
await updateProject(editId.value, form.value)
|
||||||
|
ElMessage.success('项目已更新')
|
||||||
|
} else {
|
||||||
|
const res = await createProject(form.value)
|
||||||
|
ElMessage.success(`项目已创建!API Key: ${res.data.api_key}`)
|
||||||
|
}
|
||||||
|
dialogVisible.value = false
|
||||||
|
await loadProjects()
|
||||||
|
} catch (e) {
|
||||||
|
ElMessage.error(e.response?.data?.detail || '操作失败')
|
||||||
|
} finally {
|
||||||
|
submitting.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleRotateKey(row) {
|
||||||
|
try {
|
||||||
|
await ElMessageBox.confirm('确定要重置该项目的 API Key 吗?旧密钥将立即失效。', '确认重置', { type: 'warning' })
|
||||||
|
const res = await rotateApiKey(row.id)
|
||||||
|
ElMessage.success(`新 API Key: ${res.data.api_key}`)
|
||||||
|
await loadProjects()
|
||||||
|
} catch (e) {
|
||||||
|
if (e !== 'cancel') ElMessage.error('重置失败')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleDelete(row) {
|
||||||
|
try {
|
||||||
|
await ElMessageBox.confirm(`确定要删除项目"${row.name}"吗?相关日志不会被删除。`, '确认删除', { type: 'warning' })
|
||||||
|
await deleteProject(row.id)
|
||||||
|
ElMessage.success('项目已删除')
|
||||||
|
await loadProjects()
|
||||||
|
} catch (e) {
|
||||||
|
if (e !== 'cancel') ElMessage.error('删除失败')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function copyKey(row) {
|
||||||
|
if (!row.api_key) return
|
||||||
|
if (navigator.clipboard && window.isSecureContext) {
|
||||||
|
navigator.clipboard.writeText(row.api_key).then(() => {
|
||||||
|
ElMessage.success('API Key 已复制')
|
||||||
|
}).catch(() => {
|
||||||
|
ElMessage.error('复制失败')
|
||||||
|
})
|
||||||
|
} else {
|
||||||
|
const ta = document.createElement('textarea')
|
||||||
|
ta.value = row.api_key
|
||||||
|
ta.style.position = 'fixed'
|
||||||
|
ta.style.left = '-9999px'
|
||||||
|
document.body.appendChild(ta)
|
||||||
|
ta.select()
|
||||||
|
try {
|
||||||
|
document.execCommand('copy')
|
||||||
|
ElMessage.success('API Key 已复制')
|
||||||
|
} catch (e) {
|
||||||
|
ElMessage.error('复制失败,请手动复制')
|
||||||
|
} finally {
|
||||||
|
document.body.removeChild(ta)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
onMounted(loadProjects)
|
||||||
|
</script>
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
import { defineConfig } from 'vite'
|
||||||
|
import vue from '@vitejs/plugin-vue'
|
||||||
|
|
||||||
|
export default defineConfig({
|
||||||
|
plugins: [vue()],
|
||||||
|
server: {
|
||||||
|
port: 3000,
|
||||||
|
proxy: {
|
||||||
|
'/api': {
|
||||||
|
target: 'http://localhost:8000',
|
||||||
|
changeOrigin: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
@@ -0,0 +1,150 @@
|
|||||||
|
# 接入 LogHive 日志系统指南
|
||||||
|
|
||||||
|
## 前置准备
|
||||||
|
|
||||||
|
向管理员提供你的**项目名称**(如 `user-service`),管理员会返回一个 **API Key**。
|
||||||
|
|
||||||
|
拿到 API Key 后,在你的项目 `.env` 文件中添加:
|
||||||
|
|
||||||
|
```env
|
||||||
|
# LogHive 日志系统
|
||||||
|
LOGHIVE_ENDPOINT=http://10.10.10.14:8000
|
||||||
|
LOGHIVE_PROJECT=你的项目名称
|
||||||
|
LOGHIVE_API_KEY=管理员给你的API-Key
|
||||||
|
```
|
||||||
|
|
||||||
|
> **不要**把 API 地址和 Key 硬编码在代码里,全部从环境变量读取。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 方式一:零代码改动(推荐)
|
||||||
|
|
||||||
|
适用于已使用 Python 标准 `logging` 模块的项目。只需在入口文件添加 3 行:
|
||||||
|
|
||||||
|
```python
|
||||||
|
import logging
|
||||||
|
import os
|
||||||
|
from loghive_client import LogHiveHandler
|
||||||
|
|
||||||
|
handler = LogHiveHandler(
|
||||||
|
project=os.environ["LOGHIVE_PROJECT"],
|
||||||
|
api_key=os.environ["LOGHIVE_API_KEY"],
|
||||||
|
endpoint=os.environ["LOGHIVE_ENDPOINT"],
|
||||||
|
level=logging.INFO, # 只发送 INFO 及以上级别
|
||||||
|
)
|
||||||
|
logging.getLogger().addHandler(handler)
|
||||||
|
|
||||||
|
# 现有代码无需任何修改,所有日志自动发送到 LogHive
|
||||||
|
logging.info("服务启动成功")
|
||||||
|
logging.error("数据库连接超时", exc_info=True)
|
||||||
|
```
|
||||||
|
|
||||||
|
### 仅发送特定 logger 的日志
|
||||||
|
|
||||||
|
```python
|
||||||
|
logger = logging.getLogger("myapp.api")
|
||||||
|
logger.addHandler(handler)
|
||||||
|
logger.setLevel(logging.WARNING)
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 方式二:使用 LogHive SDK
|
||||||
|
|
||||||
|
适合需要更精细控制的场景,或者不想影响全局 logging 配置。
|
||||||
|
|
||||||
|
### 安装
|
||||||
|
|
||||||
|
```bash
|
||||||
|
pip install /path/to/loghive-client
|
||||||
|
```
|
||||||
|
|
||||||
|
### 同步项目使用
|
||||||
|
|
||||||
|
```python
|
||||||
|
import os
|
||||||
|
from loghive_client import LogHiveLogger
|
||||||
|
|
||||||
|
logger = LogHiveLogger(
|
||||||
|
project=os.environ["LOGHIVE_PROJECT"],
|
||||||
|
api_key=os.environ["LOGHIVE_API_KEY"],
|
||||||
|
endpoint=os.environ["LOGHIVE_ENDPOINT"],
|
||||||
|
)
|
||||||
|
|
||||||
|
logger.info("用户登录成功", user_id=42, ip="1.2.3.4")
|
||||||
|
logger.warning("API 限流触发", rate="90%")
|
||||||
|
logger.error("支付回调验签失败", trace_id="req-abc-123", exc_info=True)
|
||||||
|
logger.debug("缓存命中 key=user:42")
|
||||||
|
logger.critical("磁盘空间不足,服务即将崩溃")
|
||||||
|
```
|
||||||
|
|
||||||
|
SDK 在后台线程异步批量发送,**不会阻塞主线程**。程序退出时会自动 flush 剩余日志。
|
||||||
|
|
||||||
|
### 异步项目使用(FastAPI / aiohttp)
|
||||||
|
|
||||||
|
```python
|
||||||
|
import os
|
||||||
|
from loghive_client import AsyncLogHiveLogger
|
||||||
|
|
||||||
|
async def main():
|
||||||
|
async with AsyncLogHiveLogger(
|
||||||
|
project=os.environ["LOGHIVE_PROJECT"],
|
||||||
|
api_key=os.environ["LOGHIVE_API_KEY"],
|
||||||
|
endpoint=os.environ["LOGHIVE_ENDPOINT"],
|
||||||
|
) as logger:
|
||||||
|
await logger.info("请求处理完成", path="/api/users", status=200)
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 方式三:直接调用 REST API(非 Python 项目)
|
||||||
|
|
||||||
|
```bash
|
||||||
|
curl -X POST $LOGHIVE_ENDPOINT/api/logs/ingest \
|
||||||
|
-H "Authorization: Bearer $LOGHIVE_API_KEY" \
|
||||||
|
-H "Content-Type: application/json" \
|
||||||
|
-d '{
|
||||||
|
"project": "'$LOGHIVE_PROJECT'",
|
||||||
|
"entries": [
|
||||||
|
{
|
||||||
|
"level": "error",
|
||||||
|
"message": "服务异常",
|
||||||
|
"logger": "myapp.module",
|
||||||
|
"trace_id": "abc-123",
|
||||||
|
"extra": {"key": "value"}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}'
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 日志字段说明
|
||||||
|
|
||||||
|
| 字段 | 类型 | 必填 | 说明 |
|
||||||
|
|------|------|------|------|
|
||||||
|
| `level` | string | 是 | `debug` / `info` / `warning` / `error` / `critical` |
|
||||||
|
| `message` | string | 是 | 日志内容,最长 65536 字符 |
|
||||||
|
| `logger` | string | 否 | Logger 名称,默认 `root` |
|
||||||
|
| `trace_id` | string | 否 | 链路追踪 ID,用于关联跨模块日志 |
|
||||||
|
| `exception` | string | 否 | 异常堆栈,SDK 通过 `exc_info=True` 自动捕获 |
|
||||||
|
| `extra` | object | 否 | 任意键值对,支持嵌套结构 |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 在 LogHive 前端查看
|
||||||
|
|
||||||
|
访问 `http://10.10.10.14:3000`,按项目、级别、关键词、时间范围搜索和统计。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 常见问题
|
||||||
|
|
||||||
|
**Q: 发送失败会影响我的主业务吗?**
|
||||||
|
A: 不会。SDK 在后台线程异步发送,网络失败会自动重试 3 次,最终丢弃并记录本地 warning。
|
||||||
|
|
||||||
|
**Q: 日志量很大怎么办?**
|
||||||
|
A: SDK 默认每 2 秒或积攒 50 条批量发送。可通过 `batch_size` 和 `flush_interval` 参数调节。
|
||||||
|
|
||||||
|
**Q: 多个进程/worker 同时发送有问题吗?**
|
||||||
|
A: 没问题。每个进程创建自己的 LogHiveLogger 实例即可。
|
||||||
Reference in New Issue
Block a user