Skip to content

Commit 3234b21

Browse files
authored
Redo logger and fix examples (#113)
* Redo logger and fix examples * Experimental change * Incorrectly setup logger * Changelog * Tweak tutorial and went back to skip true
1 parent 7a7ba23 commit 3234b21

File tree

12 files changed

+64
-52
lines changed

12 files changed

+64
-52
lines changed

.github/workflows/ci.yml

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,13 @@ on:
1313
- '!*post*'
1414
pull_request:
1515
workflow_dispatch:
16+
schedule:
17+
# ┌───────── minute (0 - 59)
18+
# │ ┌───────── hour (0 - 23)
19+
# │ │ ┌───────── day of the month (1 - 31)
20+
# │ │ │ ┌───────── month (1 - 12 or JAN-DEC)
21+
# │ │ │ │ ┌───────── day of the week (0 - 6 or SUN-SAT)
22+
- cron: '0 7 * * *' # Every day at 07:00 UTC
1623

1724
concurrency:
1825
group: ${{ github.workflow }}-${{ github.ref }}

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -213,6 +213,7 @@ examples/**/*.asdf
213213
examples/**/*.csv
214214
examples/jsoc.stanford.edu/
215215
jsoc.stanford.edu/
216+
docs/sg_execution_times.rst
216217

217218
### Pycharm(?)
218219
.idea

.pre-commit-config.yaml

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -11,17 +11,17 @@ repos:
1111
args: ['--in-place', '--remove-all-unused-imports', '--remove-unused-variable']
1212
exclude: ".*(.fits|.fts|.fit|.txt|tca.*|extern.*|.rst|.md|docs/conf.py)$"
1313
- repo: https://github.com/charliermarsh/ruff-pre-commit
14-
rev: 'v0.1.6'
14+
rev: 'v0.1.9'
1515
hooks:
1616
- id: ruff
1717
args: ['--fix', '--unsafe-fixes']
1818
- repo: https://github.com/psf/black
19-
rev: 23.11.0
19+
rev: 23.12.1
2020
hooks:
2121
- id: black
2222
exclude: ".*(.fits|.fts|.fit|.txt|.csv)$"
2323
- repo: https://github.com/PyCQA/isort
24-
rev: 5.12.0
24+
rev: 5.13.2
2525
hooks:
2626
- id: isort
2727
exclude: ".*(.fits|.fts|.fit|.txt|.csv)$"

CHANGELOG.rst

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,12 @@
1+
0.7.1 (2023-12-28)
2+
==================
3+
4+
Bug Fixes
5+
---------
6+
7+
- Incorrect setup of the logger is now fixed. (`#113 <https://github.com/sunpy/drms/pull/113>`__)
8+
- Fixed missing environment variable in the docs. (`#113 <https://github.com/sunpy/drms/pull/113>`__)
9+
110
0.7.0 (2023-11-17)
211
==================
312

docs/conf.py

Lines changed: 3 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,6 @@
1414
project = "drms"
1515
author = "The SunPy Project"
1616
copyright = f"{datetime.datetime.now().year}, {author}" # NOQA: A001
17-
1817
# The full version, including alpha/beta/rc tags
1918
release = __version__
2019
is_development = ".dev" in __version__
@@ -37,25 +36,14 @@
3736
"sphinx.ext.todo",
3837
"sphinx.ext.viewcode",
3938
]
40-
41-
# Set automodapi to generate files inside the generated directory
4239
automodapi_toctreedirnm = "generated/api"
43-
# List of patterns, relative to source directory, that match files and
44-
# directories to ignore when looking for source files.
45-
# This pattern also affects html_static_path and html_extra_path.
4640
exclude_patterns = ["_build", "Thumbs.db", ".DS_Store"]
47-
# The suffix(es) of source filenames.
48-
# You can specify multiple suffix as a list of string:
4941
source_suffix = ".rst"
50-
# The master toctree document.
5142
master_doc = "index"
52-
# The reST default role (used for this markup: `text`) to use for all
53-
# documents. Set to the "smart" one.
5443
default_role = "obj"
5544

5645
# -- Options for hoverxref -----------------------------------------------------
5746
if os.environ.get("READTHEDOCS"):
58-
# Building on Read the Docs
5947
hoverxref_api_host = "https://readthedocs.org"
6048
if os.environ.get("PROXIED_API_ENDPOINT"):
6149
# Use the proxied API endpoint
@@ -65,7 +53,6 @@
6553
hoverxref_tooltip_maxwidth = 600 # RTD main window is 696px
6654
hoverxref_auto_ref = True
6755
hoverxref_mathjax = True
68-
# hoverxref has to be applied to these
6956
hoverxref_domains = ["py"]
7057
hoverxref_role_types = {
7158
# roles with py domain
@@ -111,7 +98,9 @@
11198
}
11299

113100
# -- Options for HTML output -------------------------------------------------
114-
# Render inheritance diagrams in SVG
101+
# JSOC email os env
102+
# see https://github.com/sunpy/sunpy/wiki/Home:-JSOC
103+
os.environ["JSOC_EMAIL"] = "jsoc@sunpy.org"
115104
graphviz_output_format = "svg"
116105
sphinx_gallery_conf = {
117106
"backreferences_dir": Path("generated") / "modules",

docs/tutorial.rst

Lines changed: 5 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -281,11 +281,11 @@ Here, we are only interested in magnetograms and continuum intensity maps:
281281
282282
which are stored as FITS files with varying dimensions.
283283
284-
If we now want to submit an export request for a magnetogram and an intensity map of HARP number 4864, recorded at midnight on November 30, 2014, we can use the following export query string:
284+
If we now want to submit an export request for a magnetogram and an intensity map of HARP number 10490, recorded at eight am on December 7th, 2023, we can use the following export query string:
285285
286286
.. code-block:: python
287287
288-
>>> query_string = 'hmi.sharp_720s[4864][2014.11.30_00:00_TAI]{continuum, magnetogram}' # doctest: +REMOTE_DATA
288+
>>> query_string = 'hmi.sharp_720s[10490][2023.12.07_08:00:00_TAI]{continuum}' # doctest: +REMOTE_DATA
289289
290290
In order to obtain FITS files that include keyword data in their headers, we then need to use ``protocol='fits'`` when submitting the request using :meth:`drms.client.Client.export`:
291291
@@ -300,9 +300,7 @@ We now need to wait for the server to prepare the requested files:
300300
.. code-block:: python
301301
302302
>>> export_request.wait() # doctest: +REMOTE_DATA
303-
Export request pending. [id=..., status=2]
304-
Waiting for 5 seconds...
305-
...
303+
True
306304
307305
>>> export_request.status # doctest: +REMOTE_DATA
308306
0
@@ -325,10 +323,8 @@ Downloading the data works exactly like in the previous example, by using :meth:
325323
.. code-block:: python
326324
327325
>>> export_request.download(out_dir) # doctest: +REMOTE_DATA
328-
Downloading file 1 of 2...
329-
...
330-
Downloading file 2 of 2...
331-
...
326+
record url download
327+
0 warning=No FITS files were exported. The reque... http://jsoc.stanford.edu/... /...
332328
333329
If you want to access an existing export request that you have submitted earlier, or if you submitted an export request using the `JSOC Export Data <http://jsoc.stanford.edu/ajax/exportdata.html>`__ webpage.
334330
You can use :meth:`drms.client.Client.export_from_id` with the corresponding ``ExportID`` to create an `drms.client.ExportRequest` instance for this particular request.

drms/__init__.py

Lines changed: 15 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -9,14 +9,22 @@
99
* Homepage: https://github.com/sunpy/drms
1010
* Documentation: https://docs.sunpy.org/projects/drms/en/stable/
1111
"""
12+
import logging
1213
from pathlib import Path
1314

14-
from .client import Client, ExportRequest, SeriesInfo
15-
from .config import ServerConfig, register_server
16-
from .exceptions import DrmsError, DrmsExportError, DrmsOperationNotSupported, DrmsQueryError
17-
from .json import HttpJsonClient, HttpJsonRequest, JsocInfoConstants
18-
from .utils import to_datetime
19-
from .version import version as __version__
15+
logger = logging.getLogger(__name__)
16+
logging.basicConfig(
17+
level=logging.INFO,
18+
format="%(asctime)s - %(name)s - %(levelname)s: %(message)s",
19+
datefmt="%Y-%m-%d %H:%M:%S",
20+
)
21+
22+
from .client import Client, ExportRequest, SeriesInfo # NOQA: E402
23+
from .config import ServerConfig, register_server # NOQA: E402
24+
from .exceptions import DrmsError, DrmsExportError, DrmsOperationNotSupported, DrmsQueryError # NOQA: E402
25+
from .json import HttpJsonClient, HttpJsonRequest, JsocInfoConstants # NOQA: E402
26+
from .utils import to_datetime # NOQA: E402
27+
from .version import version as __version__ # NOQA: E402
2028

2129

2230
def _get_bibtex():
@@ -53,4 +61,5 @@ def _get_bibtex():
5361
"SeriesInfo",
5462
"ServerConfig",
5563
"to_datetime",
64+
"logger",
5665
]

drms/client.py

Lines changed: 12 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
import os
22
import re
33
import time
4-
import logging
54
from pathlib import Path
65
from collections import OrderedDict
76
from urllib.error import URLError, HTTPError
@@ -11,6 +10,8 @@
1110
import numpy as np
1211
import pandas as pd
1312

13+
from drms import logger
14+
1415
from .exceptions import DrmsExportError, DrmsOperationNotSupported, DrmsQueryError
1516
from .json import HttpJsonClient
1617
from .utils import _extract_series_name, _pd_to_numeric_coerce, _split_arg
@@ -455,7 +456,7 @@ def wait(self, *, timeout=None, sleep=5, retries_notfound=5):
455456

456457
while True:
457458
idstr = str(None) if self._requestid is None else (f"{self._requestid}")
458-
logging.info(f"Export request pending. [id={idstr}, status={self._status}]")
459+
logger.info(f"Export request pending. [id={idstr}, status={self._status}]")
459460

460461
# Use the user-provided sleep value or the server's wait value.
461462
# In case neither is available, wait for 5 seconds.
@@ -471,7 +472,7 @@ def wait(self, *, timeout=None, sleep=5, retries_notfound=5):
471472
if t_start + timeout + wait_secs - time.time() < 0:
472473
return False
473474

474-
logging.info(f"Waiting for {int(round(wait_secs))} seconds...")
475+
logger.info(f"Waiting for {int(round(wait_secs))} seconds...")
475476
time.sleep(wait_secs)
476477

477478
if self.has_finished():
@@ -481,7 +482,7 @@ def wait(self, *, timeout=None, sleep=5, retries_notfound=5):
481482
# Raise exception, if no retries are left.
482483
if retries_notfound <= 0:
483484
self._raise_on_error(notfound_ok=False)
484-
logging.info(f"Request not found on server, {retries_notfound} retries left.")
485+
logger.info(f"Request not found on server, {retries_notfound} retries left.")
485486
retries_notfound -= 1
486487

487488
def download(self, directory, *, index=None, fname_from_rec=None):
@@ -565,18 +566,18 @@ def download(self, directory, *, index=None, fname_from_rec=None):
565566
fpath = Path(out_dir) / filename
566567
fpath_new = self._next_available_filename(fpath)
567568
fpath_tmp = self._next_available_filename(f"{fpath_new}.part")
568-
logging.info(f"Downloading file {int(i + 1)} of {int(ndata)}...")
569-
logging.info(f" record: {di.record}")
570-
logging.info(f" filename: {di.filename}")
569+
logger.info(f"Downloading file {int(i + 1)} of {int(ndata)}...")
570+
logger.info(f" record: {di.record}")
571+
logger.info(f" filename: {di.filename}")
571572
try:
572573
urlretrieve(di.url, fpath_tmp)
573574
except (HTTPError, URLError):
574575
fpath_new = None
575-
logging.info(" -> Error: Could not download file")
576+
logger.info(" -> Error: Could not download file")
576577
else:
577578
fpath_new = self._next_available_filename(fpath)
578579
Path(fpath_tmp).rename(fpath_new)
579-
logging.info(f" -> {os.path.relpath(fpath_new)}")
580+
logger.info(f" -> {os.path.relpath(fpath_new)}")
580581
downloads.append(fpath_new)
581582

582583
res = data[["record", "url"]].copy()
@@ -650,7 +651,7 @@ def _generate_filenamefmt(self, sname):
650651
si = self.info(sname)
651652
except Exception as e: # NOQA: BLE001
652653
# Cannot generate filename format for unknown series.
653-
logging.warning(f"Cannot generate filename format for unknown series '{sname}' with {e}")
654+
logger.warning(f"Cannot generate filename format for unknown series '{sname}' with {e}")
654655
return None
655656

656657
pkfmt_list = []
@@ -700,7 +701,7 @@ def _filename_from_export_record(self, rs, *, old_fname=None):
700701
si = self.info(sname)
701702
except Exception as e: # NOQA: BLE001
702703
# Cannot generate filename for unknown series.
703-
logging.warning(f"Cannot generate filename format for unknown series '{sname}' with {e}")
704+
logger.warning(f"Cannot generate filename format for unknown series '{sname}' with {e}")
704705
return None
705706

706707
if pkeys is not None:

drms/json.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,10 @@
11
import json as _json
2-
import logging
32
from enum import Enum
43
from urllib.parse import urlencode, quote_plus
54
from urllib.request import HTTPError, urlopen
65

6+
from drms import logger
7+
78
from .config import ServerConfig, _server_configs
89
from .utils import _split_arg
910

@@ -86,7 +87,7 @@ def __repr__(self):
8687
return f"<HttpJsonClient: {self._server.name}>"
8788

8889
def _json_request(self, url):
89-
logging.info(url)
90+
logger.debug(f"URL for request: {url}")
9091
return HttpJsonRequest(url, self._server.encoding)
9192

9293
@property

drms/main.py

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,18 @@
11
import sys
2-
import logging
32
import argparse
43

54

65
def main():
76
import drms
87

98
args = parse_args(sys.argv[1:])
10-
# Create a Client instance
119
client = drms.Client(server=args.server, email=args.email)
12-
logging.info(f"client: {client}")
10+
drms.logger.info(f"client: {client}")
1311

1412

1513
def parse_args(args):
1614
import drms
1715

18-
# Handle command line options
1916
parser = argparse.ArgumentParser(description="drms, access HMI, AIA and MDI data with python")
2017
parser.add_argument(
2118
"--version",

setup.cfg

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,8 @@ console_scripts =
6767
[tool:pytest]
6868
testpaths = "drms" "docs"
6969
norecursedirs = ".tox" "build" "docs[\/]_build" "docs[\/]generated" "*.egg-info" "examples" ".history" "paper" "drms[\/]_dev"
70+
log_cli=true
71+
log_level=INFO
7072
doctest_plus = enabled
7173
doctest_optionflags = NORMALIZE_WHITESPACE FLOAT_CMP ELLIPSIS
7274
addopts = --doctest-rst -p no:unraisableexception -p no:threadexception

tox.ini

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,6 @@ envlist =
55
build_docs
66
codestyle
77
requires =
8-
setuptools
9-
pip
108
tox-pypi-filter
119

1210
[testenv]
@@ -44,6 +42,7 @@ deps =
4442
extras =
4543
dev
4644
commands =
45+
pip freeze --all --no-input
4746
sunpy: pytest -vvv -s -ra --pyargs sunpy.net.jsoc --timeout=120 --remote-data=any {posargs}
4847
!online: {env:PYTEST_COMMAND} {posargs}
4948
online: {env:PYTEST_COMMAND} --timeout=120 --remote-data=any {posargs}
@@ -53,7 +52,8 @@ changedir = docs
5352
description = Invoke sphinx-build to build the HTML docs
5453
extras = dev
5554
commands =
56-
sphinx-build -j auto --color -W --keep-going -b html -d _build/.doctrees . _build/html {posargs}
55+
pip freeze --all --no-input
56+
sphinx-build -j 1 --color -W --keep-going -b html -d _build/.doctrees . _build/html {posargs}
5757
python -c 'import pathlib; print("Documentation available under file://\{0\}".format(pathlib.Path(r"{toxinidir}") / "docs" / "_build" / "html"/ "index.html"))'
5858

5959
[testenv:codestyle]

0 commit comments

Comments
 (0)